{"repo":"okhttp","file":".editorconfig","line":1,"symbol":"root","kind":"field","lang":"editorconfig","code":"root = true"} {"repo":"okhttp","file":".editorconfig","line":3,"symbol":"[*]\n","kind":"section","lang":"editorconfig","code":"[*]\nindent_size = 2\nij_continuation_indent_size = 2\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true"} {"repo":"okhttp","file":".editorconfig","line":4,"symbol":"indent_size","kind":"field","lang":"editorconfig","code":"indent_size = 2"} {"repo":"okhttp","file":".editorconfig","line":5,"symbol":"ij_continuation_indent_size","kind":"field","lang":"editorconfig","code":"ij_continuation_indent_size = 2"} {"repo":"okhttp","file":".editorconfig","line":6,"symbol":"charset","kind":"field","lang":"editorconfig","code":"charset = utf-8"} {"repo":"okhttp","file":".editorconfig","line":7,"symbol":"trim_trailing_whitespace","kind":"field","lang":"editorconfig","code":"trim_trailing_whitespace = true"} {"repo":"okhttp","file":".editorconfig","line":8,"symbol":"insert_final_newline","kind":"field","lang":"editorconfig","code":"insert_final_newline = true"} {"repo":"okhttp","file":".editorconfig","line":10,"symbol":"[*.{kt, kts}]\n","kind":"section","lang":"editorconfig","code":"[*.{kt, kts}]\nij_kotlin_imports_layout = *"} {"repo":"okhttp","file":".editorconfig","line":11,"symbol":"ij_kotlin_imports_layout","kind":"field","lang":"editorconfig","code":"ij_kotlin_imports_layout = *"} {"repo":"okhttp","file":".github/renovate.json5","line":2,"symbol":"$schema","kind":"field","lang":"json5","code":"$schema: 'https://docs.renovatebot.com/renovate-schema.json'"} {"repo":"okhttp","file":".github/renovate.json5","line":2,"symbol":"'https://docs.renovatebot.com/renovate-schema.json'","kind":"field","lang":"json5","code":"$schema: 'https://docs.renovatebot.com/renovate-schema.json'"} {"repo":"okhttp","file":".github/renovate.json5","line":3,"symbol":"extends","kind":"field","lang":"json5","code":"extends: [\n 'github>lysine-dev/renovate-config:default.json5',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":6,"symbol":"labels","kind":"field","lang":"json5","code":"labels: [\n 'renovate',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":9,"symbol":"ignoreDeps","kind":"field","lang":"json5","code":"ignoreDeps: [\n 'com.squareup.okhttp3:okhttp',\n 'com.squareup.okhttp3:okhttp-tls',\n 'com.squareup.okhttp3:mockwebserver',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":14,"symbol":"packageRules","kind":"field","lang":"json5","code":"packageRules: [\n {\n groupName: 'bnd',\n matchPackageNames: [\n '/biz.*/',\n ],\n },\n {\n groupName: 'graalvm',\n matchPackageNames: [\n '/org.graalvm.*/',\n ],\n },\n {\n matchPackageNames: [\n 'org.objenesis:objenesis',\n ],\n allowedVersions: '<=2.6',\n },\n {\n extends: [\n 'monorepo:jetty',\n ],\n allowedVersions: '<10.0',\n description: 'JDK 11 requirement',\n },\n {\n extends: [\n 'monorepo:junit5',\n ],\n allowedVersions: '<5.14.0',\n },\n {\n matchPackageNames: [\n 'org.junit-pioneer:junit-pioneer',\n ],\n allowedVersions: '<2.0.0',\n description: 'JDK 11 requirement',\n },\n {\n matchPackageNames: [\n 'androidx.activity:activity-ktx',\n ],\n allowedVersions: '<=1.11.0',\n description: 'Android minSdk 23 requirement',\n }\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":16,"symbol":"groupName","kind":"field","lang":"json5","code":"groupName: 'bnd'"} {"repo":"okhttp","file":".github/renovate.json5","line":16,"symbol":"'bnd'","kind":"field","lang":"json5","code":"groupName: 'bnd'"} {"repo":"okhttp","file":".github/renovate.json5","line":17,"symbol":"matchPackageNames","kind":"field","lang":"json5","code":"matchPackageNames: [\n '/biz.*/',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":22,"symbol":"groupName","kind":"field","lang":"json5","code":"groupName: 'graalvm'"} {"repo":"okhttp","file":".github/renovate.json5","line":22,"symbol":"'graalvm'","kind":"field","lang":"json5","code":"groupName: 'graalvm'"} {"repo":"okhttp","file":".github/renovate.json5","line":23,"symbol":"matchPackageNames","kind":"field","lang":"json5","code":"matchPackageNames: [\n '/org.graalvm.*/',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":28,"symbol":"matchPackageNames","kind":"field","lang":"json5","code":"matchPackageNames: [\n 'org.objenesis:objenesis',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":31,"symbol":"allowedVersions","kind":"field","lang":"json5","code":"allowedVersions: '<=2.6'"} {"repo":"okhttp","file":".github/renovate.json5","line":31,"symbol":"'<=2.6'","kind":"field","lang":"json5","code":"allowedVersions: '<=2.6'"} {"repo":"okhttp","file":".github/renovate.json5","line":34,"symbol":"extends","kind":"field","lang":"json5","code":"extends: [\n 'monorepo:jetty',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":37,"symbol":"allowedVersions","kind":"field","lang":"json5","code":"allowedVersions: '<10.0'"} {"repo":"okhttp","file":".github/renovate.json5","line":37,"symbol":"'<10.0'","kind":"field","lang":"json5","code":"allowedVersions: '<10.0'"} {"repo":"okhttp","file":".github/renovate.json5","line":38,"symbol":"description","kind":"field","lang":"json5","code":"description: 'JDK 11 requirement'"} {"repo":"okhttp","file":".github/renovate.json5","line":38,"symbol":"'JDK 11 requirement'","kind":"field","lang":"json5","code":"description: 'JDK 11 requirement'"} {"repo":"okhttp","file":".github/renovate.json5","line":41,"symbol":"extends","kind":"field","lang":"json5","code":"extends: [\n 'monorepo:junit5',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":44,"symbol":"allowedVersions","kind":"field","lang":"json5","code":"allowedVersions: '<5.14.0'"} {"repo":"okhttp","file":".github/renovate.json5","line":44,"symbol":"'<5.14.0'","kind":"field","lang":"json5","code":"allowedVersions: '<5.14.0'"} {"repo":"okhttp","file":".github/renovate.json5","line":47,"symbol":"matchPackageNames","kind":"field","lang":"json5","code":"matchPackageNames: [\n 'org.junit-pioneer:junit-pioneer',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":50,"symbol":"allowedVersions","kind":"field","lang":"json5","code":"allowedVersions: '<2.0.0'"} {"repo":"okhttp","file":".github/renovate.json5","line":50,"symbol":"'<2.0.0'","kind":"field","lang":"json5","code":"allowedVersions: '<2.0.0'"} {"repo":"okhttp","file":".github/renovate.json5","line":51,"symbol":"description","kind":"field","lang":"json5","code":"description: 'JDK 11 requirement'"} {"repo":"okhttp","file":".github/renovate.json5","line":51,"symbol":"'JDK 11 requirement'","kind":"field","lang":"json5","code":"description: 'JDK 11 requirement'"} {"repo":"okhttp","file":".github/renovate.json5","line":54,"symbol":"matchPackageNames","kind":"field","lang":"json5","code":"matchPackageNames: [\n 'androidx.activity:activity-ktx',\n ]"} {"repo":"okhttp","file":".github/renovate.json5","line":57,"symbol":"allowedVersions","kind":"field","lang":"json5","code":"allowedVersions: '<=1.11.0'"} {"repo":"okhttp","file":".github/renovate.json5","line":57,"symbol":"'<=1.11.0'","kind":"field","lang":"json5","code":"allowedVersions: '<=1.11.0'"} {"repo":"okhttp","file":".github/renovate.json5","line":58,"symbol":"description","kind":"field","lang":"json5","code":"description: 'Android minSdk 23 requirement'"} {"repo":"okhttp","file":".github/renovate.json5","line":58,"symbol":"'Android minSdk 23 requirement'","kind":"field","lang":"json5","code":"description: 'Android minSdk 23 requirement'"} {"repo":"okhttp","file":".gitmodules","line":1,"symbol":"submodule","kind":"section","lang":"git_config","code":"[submodule \"okhttp-hpacktests/src/test/resources/hpack-test-case\"]\n\tpath = okhttp-hpacktests/src/test/resources/hpack-test-case\n\turl = https://github.com/http2jp/hpack-test-case.git"} {"repo":"okhttp","file":".gitmodules","line":2,"symbol":"path","kind":"field","lang":"git_config","code":"path = okhttp-hpacktests/src/test/resources/hpack-test-case"} {"repo":"okhttp","file":".gitmodules","line":3,"symbol":"url","kind":"field","lang":"git_config","code":"url = https://github.com/http2jp/hpack-test-case.git"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidDnsTest.kt","line":39,"symbol":"AndroidDnsTest","kind":"class","lang":"kotlin","doc":"Exercises [AndroidDns] as the resolver behind an [OkHttpClient], without service metadata (ECH). The requests go to a local [MockWebServer] over `localhost`, so the system resolver is driven but no external network is required.","code":"class AndroidDnsTest {\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setup() {\n // AndroidDns is backed by DnsResolver, which is API 29+.\n assumeTrue(Build.VERSION.SDK_INT >= 29)\n }\n\n @Test\n fun lookupResolvesLocalhostToLoopback() {\n val addresses = AndroidDns(includeServiceMetadata = false).lookup(\"localhost\")\n\n assertThat(addresses).isNotEmpty()\n assertThat(addresses).matchesPredicate { it.all(InetAddress::isLoopbackAddress) }\n }\n\n @Test\n fun getWithAndroidDns() {\n server.enqueue(MockResponse(body = \"hello\"))\n\n val client =\n OkHttpClient\n .Builder()\n .dns(AndroidDns(includeServiceMetadata = false))\n .build()\n\n // Force a hostname (not an IP literal) so the request goes through AndroidDns.\n val url = server.url(\"/\").newBuilder().host(\"localhost\").build()\n\n client.newCall(Request.Builder().url(url).build()).execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"hello\")\n }\n }\n}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidDnsTest.kt","line":43,"symbol":"setup","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setup() {\n // AndroidDns is backed by DnsResolver, which is API 29+.\n assumeTrue(Build.VERSION.SDK_INT >= 29)\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidDnsTest.kt","line":49,"symbol":"lookupResolvesLocalhostToLoopback","kind":"function","lang":"kotlin","code":"@Test\n fun lookupResolvesLocalhostToLoopback() {\n val addresses = AndroidDns(includeServiceMetadata = false).lookup(\"localhost\")\n\n assertThat(addresses).isNotEmpty()\n assertThat(addresses).matchesPredicate { it.all(InetAddress::isLoopbackAddress) }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidDnsTest.kt","line":57,"symbol":"getWithAndroidDns","kind":"function","lang":"kotlin","code":"@Test\n fun getWithAndroidDns() {\n server.enqueue(MockResponse(body = \"hello\"))\n\n val client =\n OkHttpClient\n .Builder()\n .dns(AndroidDns(includeServiceMetadata = false))\n .build()\n\n // Force a hostname (not an IP literal) so the request goes through AndroidDns.\n val url = server.url(\"/\").newBuilder().host(\"localhost\").build()\n\n client.newCall(Request.Builder().url(url).build()).execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"hello\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworkPinning.kt","line":32,"symbol":"AndroidNetworkPinning","kind":"class","lang":"kotlin","doc":"Apply as an Application [Interceptor] and based on [okhttp3.Request.tag] with type [Network], the appropriate [okhttp3.Dns] and [javax.net.SocketFactory] will be configured. Copied from https://github.com/square/okhttp/pull/8376, which proposed this as library code.","code":"@SuppressLint(\"NewApi\")\nclass AndroidNetworkPinning : Interceptor {\n override fun intercept(chain: Interceptor.Chain): Response {\n val request = chain.request()\n\n val pinnedNetwork = request.tag()\n\n val effectiveChain =\n if (pinnedNetwork != null) {\n chain\n .withSocketFactory(pinnedNetwork.socketFactory)\n .withDns(AndroidDns(network = pinnedNetwork))\n } else {\n chain\n }\n\n return effectiveChain.proceed(request)\n }\n}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworkPinning.kt","line":34,"symbol":"intercept","kind":"function","lang":"kotlin","code":"override fun intercept(chain: Interceptor.Chain): Response {\n val request = chain.request()\n\n val pinnedNetwork = request.tag()\n\n val effectiveChain =\n if (pinnedNetwork != null) {\n chain\n .withSocketFactory(pinnedNetwork.socketFactory)\n .withDns(AndroidDns(network = pinnedNetwork))\n } else {\n chain\n }\n\n return effectiveChain.proceed(request)\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":77,"symbol":"AndroidNetworksTest","kind":"class","lang":"kotlin","doc":"``` Network 100 is `wlan0` (10.0.2.16) and network 101 is `eth0` (10.0.2.15); both use NAT through the emulator host. `REQUEST:0` means nothing holds a request for it, AKA a *background* network. So need to request the network.","code":"@Tag(\"Remote\")\nclass AndroidNetworksTest {\n private val connectivityManager =\n ApplicationProvider\n .getApplicationContext()\n .getSystemService(ConnectivityManager::class.java)\n\n private val networkCallbacks = mutableListOf()\n\n private lateinit var client: OkHttpClient\n\n @BeforeEach\n fun setUp() {\n // ConnectivityManager.getActiveNetwork() is API 23. Everything else here — getAllByName,\n // getSocketFactory, requestNetwork, getLinkProperties — is API 21.\n assumeTrue(Build.VERSION.SDK_INT >= 23)\n\n client = OkHttpClient()\n }\n\n @AfterEach\n fun tearDown() {\n for (callback in networkCallbacks) {\n connectivityManager.unregisterNetworkCallback(callback)\n }\n networkCallbacks.clear()\n }\n\n /** The network the system would have picked anyway — network 100, Wi-Fi — named explicitly. */\n @Test\n fun defaultNetworkCarriesTheCall() {\n val network = connectivityManager.activeNetwork\n assertThat(network).isNotNull()\n\n val capabilities = capabilitiesOf(network)\n assertThat(capabilities?.hasCapability(NET_CAPABILITY_INTERNET)).isEqualTo(true)\n assertThat(capabilities?.hasCapability(NET_CAPABILITY_VALIDATED)).is"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":88,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n // ConnectivityManager.getActiveNetwork() is API 23. Everything else here — getAllByName,\n // getSocketFactory, requestNetwork, getLinkProperties — is API 21.\n assumeTrue(Build.VERSION.SDK_INT >= 23)\n\n client = OkHttpClient()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":97,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n for (callback in networkCallbacks) {\n connectivityManager.unregisterNetworkCallback(callback)\n }\n networkCallbacks.clear()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":106,"symbol":"defaultNetworkCarriesTheCall","kind":"function","lang":"kotlin","doc":"The network the system would have picked anyway — network 100, Wi-Fi — named explicitly.","code":"@Test\n fun defaultNetworkCarriesTheCall() {\n val network = connectivityManager.activeNetwork\n assertThat(network).isNotNull()\n\n val capabilities = capabilitiesOf(network)\n assertThat(capabilities?.hasCapability(NET_CAPABILITY_INTERNET)).isEqualTo(true)\n assertThat(capabilities?.hasCapability(NET_CAPABILITY_VALIDATED)).isEqualTo(true)\n\n assertThat(localAddressOverNetwork(network!!)).isIn(*linkAddressesOf(network))\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":123,"symbol":"nonDefaultNetworkCarriesTheCall","kind":"function","lang":"kotlin","doc":"A network that is not the default one — network 101, cellular, on the emulator. The test skips on a device that only has the one network, but it does not skip if the system hands back the default: that would mean this ran twice over the same network while appearing to cover two.","code":"@Test\n fun nonDefaultNetworkCarriesTheCall() {\n val default = connectivityManager.activeNetwork\n val (transport, transportName) =\n when {\n capabilitiesOf(default)?.hasTransport(TRANSPORT_CELLULAR) == true -> TRANSPORT_WIFI to \"Wi-Fi\"\n else -> TRANSPORT_CELLULAR to \"cellular\"\n }\n\n val network = requestNetwork(transport)\n assumeTrue(network != null, \"no $transportName network alongside the default one\")\n\n assertThat(network).isNotEqualTo(default)\n assertThat(capabilitiesOf(network)?.hasTransport(transport)).isEqualTo(true)\n\n val localAddress = localAddressOverNetwork(network!!)\n assertThat(localAddress).isIn(*linkAddressesOf(network))\n // The point of the test: a different interface from the one the call would have taken.\n assertThat(localAddress).isNotIn(*linkAddressesOf(default!!))\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":150,"symbol":"localAddressOverNetwork","kind":"function","lang":"kotlin","doc":"Makes a call pinned to [network] and returns the local address its socket ended up with. [AndroidNetworkPinning] pins both halves off the request tag: DNS and the socket factory. Without the socket factory a request resolved on one network still connects over the default one.","code":"private fun localAddressOverNetwork(network: Network): InetAddress? {\n var localAddress: InetAddress? = null\n\n val networkClient =\n client\n .newBuilder()\n .addInterceptor(AndroidNetworkPinning())\n .eventListener(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n localAddress = connection.socket().localAddress\n }\n },\n ).build()\n\n val request =\n Request\n .Builder()\n .url(URL)\n .tag(network)\n .build()\n\n try {\n networkClient.newCall(request).execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n }\n } catch (e: IOException) {\n // Skipped flaky emulator rather than failed\n if (e.isNetworkUnusable()) {\n abort(\"$network could not reach $URL: ${e.message}\")\n }\n throw e\n }\n\n return localAddress\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":159,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n localAddress = connection.socket().localAddress\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":195,"symbol":"isNetworkUnusable","kind":"function","lang":"kotlin","doc":"True if the call never got off the device: nothing resolved, or nothing connected. Checks the causes and the suppressed attempts too, since an address that loses the happy-eyeballs race is reported as a suppressed exception of the one that failed last.","code":"private fun Throwable.isNetworkUnusable(): Boolean =\n this is UnknownHostException ||\n this is SocketTimeoutException ||\n this is ConnectException ||\n cause?.isNetworkUnusable() == true ||\n suppressed.any { it.isNetworkUnusable() }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":207,"symbol":"requestNetwork","kind":"function","lang":"kotlin","doc":"Asks for a network on [transport] and returns it once it is available, or null if none turns up in time. The callback stays registered until [tearDown], because releasing the request is what would drop the network back into the background and break the calls made over it.","code":"private fun requestNetwork(transport: Int): Network? {\n val request =\n NetworkRequest\n .Builder()\n .addCapability(NET_CAPABILITY_INTERNET)\n .addTransportType(transport)\n .build()\n\n val available = LinkedBlockingQueue()\n val callback =\n object : NetworkCallback() {\n override fun onAvailable(network: Network) {\n available.offer(network)\n }\n }\n\n connectivityManager.requestNetwork(request, callback)\n networkCallbacks += callback\n\n return available.poll(20, SECONDS)\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":218,"symbol":"onAvailable","kind":"function","lang":"kotlin","code":"override fun onAvailable(network: Network) {\n available.offer(network)\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":230,"symbol":"linkAddressesOf","kind":"function","lang":"kotlin","doc":"The addresses assigned to [network]'s interface, such as 10.0.2.16 for the emulator's Wi-Fi.","code":"private fun linkAddressesOf(network: Network): Array =\n connectivityManager\n .getLinkProperties(network)\n ?.linkAddresses\n .orEmpty()\n .map { it.address }\n .toTypedArray()"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/AndroidNetworksTest.kt","line":238,"symbol":"capabilitiesOf","kind":"function","lang":"kotlin","code":"private fun capabilitiesOf(network: Network?): NetworkCapabilities? = connectivityManager.getNetworkCapabilities(network)"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":50,"symbol":"EchRemoteTest","kind":"class","lang":"kotlin","doc":"Confirms Encrypted Client Hello (ECH) end to end. Test with both [AndroidDns] and [DnsOverHttps]. See `res/xml/network_security_config.xml` for overrides.","code":"@SuppressLint(\"NewApi\")\n@Tag(\"Remote\")\n@Burst\nclass EchRemoteTest(\n private val dnsApi: DnsApi = DnsApi.Doh,\n) {\n private lateinit var client: OkHttpClient\n\n @BeforeEach\n fun setUp() {\n // ECH requires API 37.\n assumeTrue(Build.VERSION.SDK_INT >= 37)\n\n val bootstrapClient = OkHttpClient()\n val dns = dnsApi.create(bootstrapClient)\n client =\n bootstrapClient.newBuilder()\n .addNetworkInterceptor(RouteTagger)\n .dns(dns)\n .build()\n }\n\n @Test\n fun cloudflareUsesEch() {\n val call = client.newCall(Request(\"https://cloudflare-ech.com/cdn-cgi/trace\".toHttpUrl()))\n call.execute().use { response ->\n assertThat(call.routeList.routes.single().echConfigList).isNotNull()\n\n val body = response.body.string()\n assertThat(body).contains(\"sni=encrypted\")\n }\n }\n\n @Test\n fun echIsAcceptedOnTlsEchDev() {\n val call = client.newCall(Request(\"https://tls-ech.dev/\".toHttpUrl()))\n call.execute().use { response ->\n assertThat(call.routeList.routes.single().echConfigList).isNotNull()\n\n val body = response.body.string()\n\n // Only the heading identifies the server we reached; every page links to all of the others.\n "} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":58,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n // ECH requires API 37.\n assumeTrue(Build.VERSION.SDK_INT >= 37)\n\n val bootstrapClient = OkHttpClient()\n val dns = dnsApi.create(bootstrapClient)\n client =\n bootstrapClient.newBuilder()\n .addNetworkInterceptor(RouteTagger)\n .dns(dns)\n .build()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":72,"symbol":"cloudflareUsesEch","kind":"function","lang":"kotlin","code":"@Test\n fun cloudflareUsesEch() {\n val call = client.newCall(Request(\"https://cloudflare-ech.com/cdn-cgi/trace\".toHttpUrl()))\n call.execute().use { response ->\n assertThat(call.routeList.routes.single().echConfigList).isNotNull()\n\n val body = response.body.string()\n assertThat(body).contains(\"sni=encrypted\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":83,"symbol":"echIsAcceptedOnTlsEchDev","kind":"function","lang":"kotlin","code":"@Test\n fun echIsAcceptedOnTlsEchDev() {\n val call = client.newCall(Request(\"https://tls-ech.dev/\".toHttpUrl()))\n call.execute().use { response ->\n assertThat(call.routeList.routes.single().echConfigList).isNotNull()\n\n val body = response.body.string()\n\n // Only the heading identifies the server we reached; every page links to all of the others.\n assertThat(body).contains(\"

tls-ech.dev

\")\n assertThat(body).contains(\"You are using ECH\")\n assertThat(body).doesNotContain(\"not using ECH\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":98,"symbol":"echIsRetriedOnStaleTlsEchDev","kind":"function","lang":"kotlin","code":"@Test\n fun echIsRetriedOnStaleTlsEchDev() {\n val call = client.newCall(Request(\"https://stale.tls-ech.dev/\".toHttpUrl()))\n call.execute().use { response ->\n val routes = call.routeList.routes\n assertThat(routes).hasSize(2)\n assertThat(routes[0].echConfigList).isNotNull()\n assertThat(routes[1].echConfigList).isNotNull()\n\n val body = response.body.string()\n assertThat(body).contains(\"

stale.tls-ech.dev

\")\n assertThat(body).contains(\"You are using ECH\")\n assertThat(body).doesNotContain(\"not using ECH\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":118,"symbol":"echIsAcceptedOnWrongTlsEchDev","kind":"function","lang":"kotlin","doc":"This page redirects to 'https://wrong.tls-ech.dev:445/', but nothing is listening on that port on that server.","code":"@Test\n fun echIsAcceptedOnWrongTlsEchDev() {\n val verifiedHostnames = mutableListOf()\n val hostnameVerifier = client.hostnameVerifier\n val client =\n client\n .newBuilder()\n .hostnameVerifier { hostname, session ->\n verifiedHostnames += hostname\n hostnameVerifier.verify(hostname, session)\n }\n .followRedirects(false)\n .build()\n\n val call = client.newCall(Request(\"https://wrong.tls-ech.dev/\".toHttpUrl()))\n call.execute().use { response ->\n assertThat(call.routeList.routes.single().echConfigList).isNotNull()\n\n assertThat(response.code).isEqualTo(302)\n assertThat(response.headers[\"Location\"])\n .isEqualTo(\"https://wrong.tls-ech.dev:445/\")\n assertThat(verifiedHostnames).contains(\"wrong.tls-ech.dev\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":144,"symbol":"tlsIsNotUsedOnTls12TlsEchDev","kind":"function","lang":"kotlin","doc":"TLS 1.2 cannot carry ECH.","code":"@Test\n fun tlsIsNotUsedOnTls12TlsEchDev() {\n val call = client.newCall(Request(\"https://tls12.tls-ech.dev/\".toHttpUrl()))\n call.execute().use { response ->\n val routes = call.routeList.routes\n assertThat(routes).hasSize(2)\n assertThat(routes[0].echConfigList).isNotNull()\n assertThat(routes[1].echConfigList).isNull()\n\n val body = response.body.string()\n assertThat(body).contains(\"

tls12.tls-ech.dev

\")\n assertThat(body).contains(\"You are not using ECH\")\n assertThat(body).doesNotContain(\"You are using ECH\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":160,"symbol":"echIsAcceptedOnDefoIe","kind":"function","lang":"kotlin","code":"@Test\n fun echIsAcceptedOnDefoIe() {\n val call = client.newCall(Request(\"https://defo.ie/ech-check.php\".toHttpUrl()))\n call.execute().use { response ->\n assertThat(call.routeList.routes.single().echConfigList).isNotNull()\n\n val body = response.body.string()\n assertThat(body).contains(\"SSL_ECH_STATUS: success\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":174,"symbol":"policyDisabledHostDoesNotUseEch","kind":"function","lang":"kotlin","doc":"Disabled by policy.","code":"@Test\n fun policyDisabledHostDoesNotUseEch() {\n val call = client.newCall(Request(\"https://crypto.cloudflare.com/cdn-cgi/trace\".toHttpUrl()))\n call.execute().use { response ->\n assertThat(call.routeList.routes.single().echConfigList).isNotNull()\n\n val body = response.body.string()\n assertThat(body).contains(\"sni=plaintext\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":185,"symbol":"DnsApi","kind":"enum","lang":"kotlin","code":"enum class DnsApi {\n Android {\n override fun create(client: OkHttpClient) = AndroidDns()\n },\n\n Doh {\n /** DNS server is addressed by IP, so resolving the resolver doesn't need a resolver. */\n override fun create(client: OkHttpClient) = DnsOverHttps.Builder()\n .client(client)\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .includeServiceMetadata(true)\n .build()\n };\n\n abstract fun create(client: OkHttpClient): Dns\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":186,"symbol":"Android","kind":"enum_member","lang":"kotlin","code":"Android {\n override fun create(client: OkHttpClient) = AndroidDns()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":187,"symbol":"create","kind":"function","lang":"kotlin","code":"override fun create(client: OkHttpClient) = AndroidDns()"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":190,"symbol":"Doh","kind":"enum_member","lang":"kotlin","code":"Doh {\n /** DNS server is addressed by IP, so resolving the resolver doesn't need a resolver. */\n override fun create(client: OkHttpClient) = DnsOverHttps.Builder()\n .client(client)\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .includeServiceMetadata(true)\n .build()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":192,"symbol":"create","kind":"function","lang":"kotlin","doc":"DNS server is addressed by IP, so resolving the resolver doesn't need a resolver.","code":"override fun create(client: OkHttpClient) = DnsOverHttps.Builder()\n .client(client)\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .includeServiceMetadata(true)\n .build()"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":199,"symbol":"create","kind":"function","lang":"kotlin","code":"abstract fun create(client: OkHttpClient): Dns"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":207,"symbol":"RouteTagger","kind":"object","lang":"kotlin","doc":"Collect Route information to confirm we sent an ECH config list to our TLS stack. Whether we actually encrypted the client hello depends on our TLS stack.","code":"private object RouteTagger : Interceptor {\n override fun intercept(chain: Interceptor.Chain): Response {\n val routeList = chain.call().routeList\n routeList.routes += chain.connection()!!.route()\n return chain.proceed(chain.request())\n }\n}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":208,"symbol":"intercept","kind":"function","lang":"kotlin","code":"override fun intercept(chain: Interceptor.Chain): Response {\n val routeList = chain.call().routeList\n routeList.routes += chain.connection()!!.route()\n return chain.proceed(chain.request())\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/EchRemoteTest.kt","line":221,"symbol":"RouteList","kind":"class","lang":"kotlin","doc":"All of the routes used to retrieve an HTTP response.","code":"private class RouteList {\n val routes = mutableListOf()\n}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":118,"symbol":"OkHttpTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slow\")\nclass OkHttpTest {\n @Suppress(\"RedundantVisibilityModifier\")\n @JvmField\n @RegisterExtension\n public val platform = PlatformRule()\n\n @Suppress(\"RedundantVisibilityModifier\")\n @JvmField\n @RegisterExtension\n public val clientTestRule =\n OkHttpClientTestRule().apply {\n logger = Logger.getLogger(OkHttpTest::class.java.name)\n }\n\n private var client: OkHttpClient =\n clientTestRule\n .newClientBuilder()\n .addInterceptor(CompressionInterceptor(Zstd, Brotli, Gzip))\n .build()\n\n private val moshi =\n Moshi\n .Builder()\n .add(KotlinJsonAdapterFactory())\n .build()\n\n private val handshakeCertificates = localhost()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setup() {\n // Needed because of Platform.resetForTests\n PlatformRegistry.applicationContext = ApplicationProvider.getApplicationContext()\n }\n\n @Test\n fun testPlatform() {\n assertTrue(Platform.isAndroid)\n\n if (Build.VERSION.SDK_INT >= 29) {\n assertTrue(Platform.get() is Android10Platform)\n } else {\n assertTrue(Platform.get() is AndroidPlatform)\n }\n }\n\n @Test\n fun testRequest() {\n assumeNetwork()\n\n va"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":150,"symbol":"setup","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setup() {\n // Needed because of Platform.resetForTests\n PlatformRegistry.applicationContext = ApplicationProvider.getApplicationContext()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":156,"symbol":"testPlatform","kind":"function","lang":"kotlin","code":"@Test\n fun testPlatform() {\n assertTrue(Platform.isAndroid)\n\n if (Build.VERSION.SDK_INT >= 29) {\n assertTrue(Platform.get() is Android10Platform)\n } else {\n assertTrue(Platform.get() is AndroidPlatform)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":167,"symbol":"testRequest","kind":"function","lang":"kotlin","code":"@Test\n fun testRequest() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://api.twitter.com/robots.txt\").build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":180,"symbol":"testLocalhostInsecure","kind":"function","lang":"kotlin","code":"@Test\n fun testLocalhostInsecure() {\n assumeTrue(Build.VERSION.SDK_INT >= 24)\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .apply {\n if (Build.VERSION.SDK_INT >= 24) {\n addInsecureHost(server.hostName)\n }\n }.build()\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n localhostInsecureRequest()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":202,"symbol":"testRequestWithSniRequirement","kind":"function","lang":"kotlin","code":"@Test\n fun testRequestWithSniRequirement() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://docs.fabric.io/android/changelog.html\").build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":215,"symbol":"testConscryptRequest","kind":"function","lang":"kotlin","code":"@Test\n fun testConscryptRequest() {\n assumeNetwork()\n\n try {\n Security.insertProviderAt(Conscrypt.newProviderBuilder().build(), 1)\n\n val request = Request.Builder().url(\"https://facebook.com/robots.txt\").build()\n\n var socketClass: String? = null\n\n // Need fresh client to reset sslSocketFactoryOrNull\n client =\n OkHttpClient\n .Builder()\n .eventListenerFactory(\n clientTestRule.wrap(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socketClass = connection.socket().javaClass.name\n }\n },\n ),\n ).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(Protocol.HTTP_2, response.protocol)\n assertEquals(200, response.code)\n // see https://github.com/google/conscrypt/blob/b9463b2f74df42d85c73715a5f19e005dfb7b802/android/src/main/java/org/conscrypt/Platform.java#L613\n when {\n Build.VERSION.SDK_INT >= 24 -> {\n // Conscrypt 2.5+ defaults to SS"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":233,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socketClass = connection.socket().javaClass.name\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":271,"symbol":"testConscryptRequestLocalhostInsecure","kind":"function","lang":"kotlin","code":"@Test\n fun testConscryptRequestLocalhostInsecure() {\n try {\n Security.insertProviderAt(Conscrypt.newProviderBuilder().build(), 1)\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .addInsecureHost(server.hostName)\n .build()\n\n // Need fresh client to reset sslSocketFactoryOrNull\n client =\n OkHttpClient\n .Builder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n localhostInsecureRequest()\n } finally {\n Security.removeProvider(\"Conscrypt\")\n client.close()\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":296,"symbol":"testRequestUsesPlayProvider","kind":"function","lang":"kotlin","code":"@Test\n fun testRequestUsesPlayProvider() {\n assumeNetwork()\n\n try {\n try {\n ProviderInstaller.installIfNeeded(InstrumentationRegistry.getInstrumentation().targetContext)\n } catch (gpsnae: GooglePlayServicesNotAvailableException) {\n throw TestAbortedException(\"Google Play Services not available\", gpsnae)\n }\n\n assertEquals(\n ProviderInstaller.PROVIDER_NAME,\n SSLContext.getInstance(\"TLS\").provider.name,\n )\n\n val request = Request.Builder().url(\"https://facebook.com/robots.txt\").build()\n\n var socketClass: String? = null\n\n // Need fresh client to reset sslSocketFactoryOrNull\n client =\n OkHttpClient\n .Builder()\n .eventListenerFactory(\n clientTestRule.wrap(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socketClass = connection.socket().javaClass.name\n }\n },\n ),\n ).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(Protoco"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":323,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socketClass = connection.socket().javaClass.name\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":361,"symbol":"testRequestUsesPlayProviderLocalhostInsecure","kind":"function","lang":"kotlin","code":"@Test\n fun testRequestUsesPlayProviderLocalhostInsecure() {\n try {\n try {\n ProviderInstaller.installIfNeeded(InstrumentationRegistry.getInstrumentation().targetContext)\n } catch (gpsnae: GooglePlayServicesNotAvailableException) {\n throw TestAbortedException(\"Google Play Services not available\", gpsnae)\n }\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .addPlatformTrustedCertificates()\n .addInsecureHost(server.hostName)\n .build()\n\n // Need fresh client to reset sslSocketFactoryOrNull\n client =\n OkHttpClient\n .Builder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n localhostInsecureRequest()\n } finally {\n Security.removeProvider(ProviderInstaller.PROVIDER_NAME)\n client.close()\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":391,"symbol":"localhostInsecureRequest","kind":"function","lang":"kotlin","code":"private fun localhostInsecureRequest() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n\n server.enqueue(MockResponse())\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n client.newCall(request).execute().use {\n assertEquals(200, it.code)\n assertEquals(listOf(), it.handshake?.peerCertificates)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":404,"symbol":"testRequestUsesAndroidConscrypt","kind":"function","lang":"kotlin","code":"@Test\n fun testRequestUsesAndroidConscrypt() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://facebook.com/robots.txt\").build()\n\n var socketClass: String? = null\n\n client =\n client\n .newBuilder()\n .eventListenerFactory(\n clientTestRule.wrap(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socketClass = connection.socket().javaClass.name\n }\n },\n ),\n ).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(Protocol.HTTP_2, response.protocol)\n if (Build.VERSION.SDK_INT >= 29) {\n assertEquals(TlsVersion.TLS_1_3, response.handshake?.tlsVersion)\n } else {\n assertEquals(TlsVersion.TLS_1_2, response.handshake?.tlsVersion)\n }\n assertEquals(200, response.code)\n assertTrue(socketClass?.startsWith(\"com.android.org.conscrypt.\") == true)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":418,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socketClass = connection.socket().javaClass.name\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":442,"symbol":"testRequestUsesAndroidConscryptLocalhostInsecure","kind":"function","lang":"kotlin","code":"@Test\n fun testRequestUsesAndroidConscryptLocalhostInsecure() {\n assumeTrue(Build.VERSION.SDK_INT >= 24)\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .addPlatformTrustedCertificates()\n .apply {\n if (Build.VERSION.SDK_INT >= 24) {\n addInsecureHost(server.hostName)\n }\n }.build()\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n localhostInsecureRequest()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":465,"symbol":"testHttpRequestNotBlockedOnLegacyAndroid","kind":"function","lang":"kotlin","code":"@Test\n fun testHttpRequestNotBlockedOnLegacyAndroid() {\n assumeTrue(Build.VERSION.SDK_INT < 23)\n\n val request = Request.Builder().url(\"http://squareup.com/robots.txt\").build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":478,"symbol":"testHttpRequestBlocked","kind":"function","lang":"kotlin","code":"@Test\n @Disabled(\"cleartext required for additional okhttp wide tests\")\n fun testHttpRequestBlocked() {\n assumeTrue(Build.VERSION.SDK_INT >= 23)\n\n val request = Request.Builder().url(\"http://squareup.com/robots.txt\").build()\n\n try {\n client.newCall(request).execute()\n fail(\"expected cleartext blocking\")\n } catch (_: java.net.UnknownServiceException) {\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":505,"symbol":"testSSLFeatures","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun testSSLFeatures() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://www.howsmyssl.com/a/check\").build()\n\n val response = client.newCall(request).execute()\n\n val results =\n response.use {\n moshi.adapter(HowsMySslResults::class.java).fromJson(response.body.string())!!\n }\n\n Platform.get().log(\"results $results\", Platform.WARN)\n\n assertTrue(results.session_ticket_supported)\n assertEquals(\"Probably Okay\", results.rating)\n // TODO map to expected versions automatically, test ignored for now. Run manually.\n assertEquals(\"TLS 1.3\", results.tls_version)\n assertEquals(0, results.insecure_cipher_suites.size)\n\n assertEquals(TlsVersion.TLS_1_3, response.handshake?.tlsVersion)\n assertEquals(Protocol.HTTP_2, response.protocol)\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":531,"symbol":"testMockWebserverRequest","kind":"function","lang":"kotlin","code":"@Test\n fun testMockWebserverRequest() {\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n assertEquals(Protocol.HTTP_2, response.protocol)\n val tlsVersion = response.handshake?.tlsVersion\n assertTrue(tlsVersion == TlsVersion.TLS_1_2 || tlsVersion == TlsVersion.TLS_1_3)\n assertEquals(\n \"CN=localhost\",\n (response.handshake!!.peerCertificates.first() as X509Certificate).subjectDN.name,\n )\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":553,"symbol":"testCertificatePinningFailure","kind":"function","lang":"kotlin","code":"@Test\n fun testCertificatePinningFailure() {\n enableTls()\n\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(server.hostName, \"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\")\n .build()\n client = client.newBuilder().certificatePinner(certificatePinner).build()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n try {\n client.newCall(request).execute()\n fail(\"\")\n } catch (e: Exception) {\n // The API 37 emulator can surface the verification failure wrapped (as a cause or a\n // suppressed exception) rather than thrown directly, so accept any of those shapes.\n val hasPeerUnverified = e is SSLPeerUnverifiedException ||\n e.suppressedExceptions.any { it is SSLPeerUnverifiedException } ||\n e.cause is SSLPeerUnverifiedException\n if (!hasPeerUnverified) {\n throw e\n }\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":583,"symbol":"testCertificatePinningSuccess","kind":"function","lang":"kotlin","code":"@Test\n fun testCertificatePinningSuccess() {\n enableTls()\n\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\n server.hostName,\n CertificatePinner.pin(handshakeCertificates.trustManager.acceptedIssuers[0]),\n ).build()\n client = client.newBuilder().certificatePinner(certificatePinner).build()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":607,"symbol":"testEventListener","kind":"function","lang":"kotlin","code":"@Test\n fun testEventListener() {\n val eventRecorder = EventRecorder()\n\n enableTls()\n\n client =\n client\n .newBuilder()\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n\n server.enqueue(MockResponse(body = \"abc1\"))\n server.enqueue(MockResponse(body = \"abc2\"))\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n client.newCall(request).execute().use { response ->\n assertEquals(200, response.code)\n }\n\n assertEquals(\n listOf(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n SecureConnectStart::class,\n SecureConnectEnd::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n ),\n eventRecorder.eventSequence.toList().withoutFailedConnectAttempts()"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":683,"symbol":"withoutFailedConnectAttempts","kind":"function","lang":"kotlin","doc":"Returns these events with failed connection attempts removed. On a dual-stack loopback the address MockWebServer isn't bound to is tried first, producing a [ConnectStart]/[ConnectFailed] pair before the successful [ConnectStart] (seen on the API 37 emulator). Dropping those pairs keeps the event assertion stable across single- and dual-stack environments.","code":"private fun List.withoutFailedConnectAttempts(): List =\n fold(mutableListOf()) { events, event ->\n if (event is ConnectFailed) {\n // Drop the ConnectFailed and the ConnectStart that opened the failed attempt.\n if (events.lastOrNull() is ConnectStart) events.removeAt(events.lastIndex)\n } else {\n events += event\n }\n events\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":694,"symbol":"testSessionReuse","kind":"function","lang":"kotlin","code":"@Test\n fun testSessionReuse() {\n val sessionIds = mutableListOf()\n\n enableTls()\n\n client =\n client\n .newBuilder()\n .eventListenerFactory(\n clientTestRule.wrap(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n val sslSocket = connection.socket() as SSLSocket\n\n sessionIds.add(\n sslSocket.session.id\n .toByteString()\n .hex(),\n )\n }\n },\n ),\n ).build()\n\n server.enqueue(MockResponse(body = \"abc1\"))\n server.enqueue(MockResponse(body = \"abc2\"))\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n client.newCall(request).execute().use { response ->\n assertEquals(200, response.code)\n }\n\n client.connectionPool.evictAll()\n assertEquals(0, client.connectionPool.connectionCount())\n\n client.newCall(request).execute().use { response ->\n assertEquals(200, response.code)\n }\n\n assertEquals(2, sessionIds.size)\n assertEquals(sessionIds[0], sessi"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":706,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n val sslSocket = connection.socket() as SSLSocket\n\n sessionIds.add(\n sslSocket.session.id\n .toByteString()\n .hex(),\n )\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":742,"symbol":"testDnsOverHttps","kind":"function","lang":"kotlin","code":"@Test\n fun testDnsOverHttps() {\n assumeNetwork()\n\n client =\n client\n .newBuilder()\n .eventListenerFactory(clientTestRule.wrap(LoggingEventListener.Factory()))\n .build()\n\n val dohDns = buildCloudflareIp(client)\n val dohEnabledClient =\n client\n .newBuilder()\n .eventListener(EventListener.NONE)\n .dns(dohDns)\n .build()\n\n dohEnabledClient.get(\"https://www.twitter.com/robots.txt\")\n dohEnabledClient.get(\"https://www.facebook.com/robots.txt\")\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":764,"symbol":"testCustomTrustManager","kind":"function","lang":"kotlin","code":"@Test\n fun testCustomTrustManager() {\n assumeNetwork()\n\n val trustManager =\n object : X509TrustManager {\n override fun checkClientTrusted(\n chain: Array?,\n authType: String?,\n ) {}\n\n override fun checkServerTrusted(\n chain: Array?,\n authType: String?,\n ) {}\n\n override fun getAcceptedIssuers(): Array = arrayOf()\n }\n\n val sslContext =\n Platform.get().newSSLContext().apply {\n init(null, arrayOf(trustManager), null)\n }\n val sslSocketFactory = sslContext.socketFactory\n\n val hostnameVerifier = HostnameVerifier { _, _ -> true }\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(sslSocketFactory, trustManager)\n .hostnameVerifier(hostnameVerifier)\n .build()\n\n client.get(\"https://www.facebook.com/robots.txt\")\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":770,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n chain: Array?,\n authType: String?,\n ) {}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":775,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n chain: Array?,\n authType: String?,\n ) {}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":780,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = arrayOf()"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":801,"symbol":"testCustomSSLSocketFactoryWithoutALPN","kind":"function","lang":"kotlin","code":"@Test\n fun testCustomSSLSocketFactoryWithoutALPN() {\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val sslSocketFactory = client.sslSocketFactory\n val trustManager = client.x509TrustManager!!\n\n val delegatingSocketFactory =\n object : DelegatingSSLSocketFactory(sslSocketFactory) {\n override fun configureSocket(sslSocket: SSLSocket): SSLSocket =\n object : DelegatingSSLSocket(sslSocket) {\n override fun getApplicationProtocol(): String = throw UnsupportedOperationException()\n }\n }\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(delegatingSocketFactory, trustManager)\n .build()\n\n val request = Request.Builder().url(server.url(\"/\").toString()).build()\n val response = client.newCall(request).execute()\n response.use {\n assertEquals(200, response.code)\n assertEquals(Protocol.HTTP_1_1, response.protocol)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":812,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"override fun configureSocket(sslSocket: SSLSocket): SSLSocket =\n object : DelegatingSSLSocket(sslSocket) {\n override fun getApplicationProtocol(): String = throw UnsupportedOperationException()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":814,"symbol":"getApplicationProtocol","kind":"function","lang":"kotlin","code":"override fun getApplicationProtocol(): String = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":832,"symbol":"testCustomTrustManagerWithAndroidCheck","kind":"function","lang":"kotlin","code":"@Test\n fun testCustomTrustManagerWithAndroidCheck() {\n assumeNetwork()\n\n var withHostCalled = false\n var withoutHostCalled = false\n val trustManager =\n object : X509TrustManager {\n override fun checkClientTrusted(\n chain: Array?,\n authType: String?,\n ) {}\n\n override fun checkServerTrusted(\n chain: Array?,\n authType: String?,\n ) {\n withoutHostCalled = true\n }\n\n // called by Android via reflection in X509TrustManagerExtensions\n @Suppress(\"unused\", \"UNUSED_PARAMETER\")\n fun checkServerTrusted(\n chain: Array,\n authType: String,\n hostname: String,\n ): List {\n withHostCalled = true\n return chain.toList()\n }\n\n override fun getAcceptedIssuers(): Array = arrayOf()\n }\n\n val sslContext =\n Platform.get().newSSLContext().apply {\n init(null, arrayOf(trustManager), null)\n }\n val sslSocketFactory = sslContext.socketFactory\n\n val hostnameVerifier = HostnameVerifier { _, _ -> true }\n\n clien"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":840,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n chain: Array?,\n authType: String?,\n ) {}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":845,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n chain: Array?,\n authType: String?,\n ) {\n withoutHostCalled = true\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":853,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","doc":"called by Android via reflection in X509TrustManagerExtensions","code":"@Suppress(\"unused\", \"UNUSED_PARAMETER\")\n fun checkServerTrusted(\n chain: Array,\n authType: String,\n hostname: String,\n ): List {\n withHostCalled = true\n return chain.toList()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":863,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = arrayOf()"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":892,"symbol":"testUnderscoreRequest","kind":"function","lang":"kotlin","code":"@Test\n fun testUnderscoreRequest() {\n assumeNetwork()\n\n val request =\n Request.Builder().url(\"https://example_underscore_123.s3.amazonaws.com/\").build()\n\n try {\n client.newCall(request).execute().close()\n // Hopefully this passes\n } catch (ioe: IOException) {\n // https://github.com/lysine-dev/okhttp/issues/5840\n when (ioe.cause) {\n is IllegalArgumentException -> {\n assertEquals(\"Android internal error\", ioe.message)\n }\n\n is CertificateException -> {\n assertTrue(ioe.cause?.cause is IllegalArgumentException)\n assertEquals(\n true,\n ioe.cause\n ?.cause\n ?.message\n ?.startsWith(\"Invalid input to toASCII\"),\n )\n }\n\n else -> {\n throw ioe\n }\n }\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":927,"symbol":"testBouncyCastleRequest","kind":"function","lang":"kotlin","code":"@Test\n @Disabled(\"breaks conscrypt test\")\n fun testBouncyCastleRequest() {\n assumeNetwork()\n\n try {\n Security.insertProviderAt(BouncyCastleProvider(), 1)\n Security.insertProviderAt(BouncyCastleJsseProvider(), 2)\n\n var socketClass: String? = null\n\n val trustManager =\n TrustManagerFactory\n .getInstance(TrustManagerFactory.getDefaultAlgorithm())\n .apply {\n init(null as KeyStore?)\n }.trustManagers\n .first() as X509TrustManager\n\n val sslContext =\n Platform.get().newSSLContext().apply {\n // TODO remove most of this code after https://github.com/bcgit/bc-java/issues/686\n init(null, arrayOf(trustManager), SecureRandom())\n }\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(sslContext.socketFactory, trustManager)\n .eventListenerFactory(\n clientTestRule.wrap(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socketClass = connection.socket().javaClass.name\n }\n "} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":959,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socketClass = connection.socket().javaClass.name\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":985,"symbol":"testLoggingLevels","kind":"function","lang":"kotlin","code":"@Test\n @Disabled(\"TODO: currently logging okhttp3.internal.concurrent.TaskRunner, okhttp3.internal.http2.Http2\")\n fun testLoggingLevels() {\n enableTls()\n\n val testHandler =\n object : Handler() {\n val calls = mutableMapOf()\n\n override fun publish(record: LogRecord) {\n calls\n .getOrPut(record.loggerName) { AtomicInteger(0) }\n .incrementAndGet()\n }\n\n override fun flush() {\n }\n\n override fun close() {\n }\n }.apply {\n level = Level.FINEST\n }\n\n Logger\n .getLogger(\"\")\n .addHandler(testHandler)\n Logger\n .getLogger(\"okhttp3\")\n .addHandler(testHandler)\n Logger\n .getLogger(Http2::class.java.name)\n .addHandler(testHandler)\n Logger\n .getLogger(TaskRunner::class.java.name)\n .addHandler(testHandler)\n Logger\n .getLogger(OkHttpClient::class.java.name)\n .addHandler(testHandler)\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n\n val response =\n client\n .newCall(request)\n .execute()\n\n re"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":994,"symbol":"publish","kind":"function","lang":"kotlin","code":"override fun publish(record: LogRecord) {\n calls\n .getOrPut(record.loggerName) { AtomicInteger(0) }\n .incrementAndGet()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":1000,"symbol":"flush","kind":"function","lang":"kotlin","code":"override fun flush() {\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":1003,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":1048,"symbol":"testCachedRequest","kind":"function","lang":"kotlin","code":"fun testCachedRequest() {\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\", headers = Headers.headersOf(\"cache-control\", \"public, max-age=3\")))\n server.enqueue(MockResponse(body = \"abc\"))\n\n val ctxt = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext\n\n val cacheSize = 1L * 1024 * 1024 // 1MB\n val cache = Cache(ctxt.cacheDir.resolve(\"testCache\"), cacheSize)\n\n try {\n client =\n client\n .newBuilder()\n .cache(cache)\n .build()\n\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n\n client\n .newCall(request)\n .execute()\n .use {\n assertEquals(200, it.code)\n assertNull(it.cacheResponse)\n assertNotNull(it.networkResponse)\n\n assertEquals(3, it.cacheControl.maxAgeSeconds)\n assertTrue(it.cacheControl.isPublic)\n }\n\n client\n .newCall(request)\n .execute()\n .use {\n assertEquals(200, it.code)\n assertNotNull(it.cacheResponse)\n assertNull(it.networkResponse)\n }\n\n assertEquals(1, cache.hitCount())\n assertEqual"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":1101,"symbol":"get","kind":"function","lang":"kotlin","code":"private fun OkHttpClient.get(url: String) {\n val request = Request.Builder().url(url).build()\n val response = this.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":1110,"symbol":"buildCloudflareIp","kind":"function","lang":"kotlin","code":"fun buildCloudflareIp(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .build()"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":1117,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":1128,"symbol":"assumeNetwork","kind":"function","lang":"kotlin","code":"private fun assumeNetwork() {\n try {\n InetAddress.getByName(\"www.google.com\")\n } catch (uhe: UnknownHostException) {\n throw TestAbortedException(uhe.message, uhe)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/OkHttpTest.kt","line":1136,"symbol":"close","kind":"function","lang":"kotlin","code":"fun OkHttpClient.close() {\n dispatcher.executorService.shutdown()\n connectionPool.evictAll()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/SingleAndroidTest.kt","line":31,"symbol":"SingleAndroidTest","kind":"class","lang":"kotlin","doc":"This single Junit 4 test is our Android test suite on API 21-25.","code":"class SingleAndroidTest {\n private val handshakeCertificates = localhost()\n\n private var client: OkHttpClient =\n OkHttpClient\n .Builder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).connectionPool(ConnectionPool(0, 1, TimeUnit.SECONDS))\n .build()\n\n private val server =\n MockWebServer()\n\n @Test\n fun testHttpsRequest() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n\n server.enqueue(MockResponse())\n server.start()\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n\n while (client.connectionPool.connectionCount() > 0) {\n Thread.sleep(1000)\n }\n }\n\n @Test\n fun testHttpRequest() {\n server.enqueue(MockResponse())\n server.start()\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n\n while (client.connectionPool.connectionCount() > 0) {\n Thread.sleep(1000)\n }\n }\n}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/SingleAndroidTest.kt","line":46,"symbol":"testHttpsRequest","kind":"function","lang":"kotlin","code":"@Test\n fun testHttpsRequest() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n\n server.enqueue(MockResponse())\n server.start()\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n\n while (client.connectionPool.connectionCount() > 0) {\n Thread.sleep(1000)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/SingleAndroidTest.kt","line":66,"symbol":"testHttpRequest","kind":"function","lang":"kotlin","code":"@Test\n fun testHttpRequest() {\n server.enqueue(MockResponse())\n server.start()\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n }\n\n while (client.connectionPool.connectionCount() > 0) {\n Thread.sleep(1000)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/StrictModeTest.kt","line":34,"symbol":"StrictModeTest","kind":"class","lang":"kotlin","code":"@Isolated\n@SdkSuppress(minSdkVersion = 28)\nclass StrictModeTest {\n private val violations = mutableListOf()\n\n @AfterEach\n fun cleanup() {\n StrictMode.setThreadPolicy(\n ThreadPolicy\n .Builder()\n .permitAll()\n .build(),\n )\n }\n\n @Test\n fun testInit() {\n Platform.resetForTests()\n\n applyStrictMode()\n\n // Not currently safe\n // See https://github.com/lysine-dev/okhttp/pull/8248\n OkHttpClient()\n\n assertThat(violations).hasSize(1)\n assertThat(violations[0].message).isEqualTo(\"newSSLContext\")\n }\n\n @Test\n fun testNewCall() {\n Platform.resetForTests()\n\n val client = OkHttpClient()\n\n applyStrictMode()\n\n // Safe on main\n client.newCall(Request(\"https://google.com/robots.txt\".toHttpUrl()))\n\n assertThat(violations).isEmpty()\n }\n\n private fun applyStrictMode() {\n StrictMode.setThreadPolicy(\n ThreadPolicy\n .Builder()\n .detectCustomSlowCalls()\n .penaltyListener({ it.run() }) {\n violations.add(it)\n }.build(),\n )\n }\n}"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/StrictModeTest.kt","line":39,"symbol":"cleanup","kind":"function","lang":"kotlin","code":"@AfterEach\n fun cleanup() {\n StrictMode.setThreadPolicy(\n ThreadPolicy\n .Builder()\n .permitAll()\n .build(),\n )\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/StrictModeTest.kt","line":49,"symbol":"testInit","kind":"function","lang":"kotlin","code":"@Test\n fun testInit() {\n Platform.resetForTests()\n\n applyStrictMode()\n\n // Not currently safe\n // See https://github.com/lysine-dev/okhttp/pull/8248\n OkHttpClient()\n\n assertThat(violations).hasSize(1)\n assertThat(violations[0].message).isEqualTo(\"newSSLContext\")\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/StrictModeTest.kt","line":63,"symbol":"testNewCall","kind":"function","lang":"kotlin","code":"@Test\n fun testNewCall() {\n Platform.resetForTests()\n\n val client = OkHttpClient()\n\n applyStrictMode()\n\n // Safe on main\n client.newCall(Request(\"https://google.com/robots.txt\".toHttpUrl()))\n\n assertThat(violations).isEmpty()\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/StrictModeTest.kt","line":77,"symbol":"applyStrictMode","kind":"function","lang":"kotlin","code":"private fun applyStrictMode() {\n StrictMode.setThreadPolicy(\n ThreadPolicy\n .Builder()\n .detectCustomSlowCalls()\n .penaltyListener({ it.run() }) {\n violations.add(it)\n }.build(),\n )\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/alpn/AlpnOverrideTest.kt","line":37,"symbol":"AlpnOverrideTest","kind":"class","lang":"kotlin","doc":"Tests for ALPN overriding on Android.","code":"@Tag(\"Remote\")\nclass AlpnOverrideTest {\n class CustomSSLSocketFactory(\n delegate: SSLSocketFactory,\n ) : DelegatingSSLSocketFactory(delegate) {\n override fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n val parameters = sslSocket.sslParameters\n Log.d(\"CustomSSLSocketFactory\", \"old applicationProtocols: $parameters.applicationProtocols\")\n parameters.applicationProtocols = arrayOf(\"x-amzn-http-ca\")\n sslSocket.sslParameters = parameters\n }\n\n return sslSocket\n }\n }\n\n var client = OkHttpClient()\n\n @Test\n fun getWithCustomSocketFactory() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(CustomSSLSocketFactory(client.sslSocketFactory), client.x509TrustManager!!)\n .connectionSpecs(\n listOf(\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .supportsTlsExtensions(false)\n .build(),\n ),\n ).eventListener(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n "} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/alpn/AlpnOverrideTest.kt","line":39,"symbol":"CustomSSLSocketFactory","kind":"class","lang":"kotlin","code":"class CustomSSLSocketFactory(\n delegate: SSLSocketFactory,\n ) : DelegatingSSLSocketFactory(delegate) {\n override fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n val parameters = sslSocket.sslParameters\n Log.d(\"CustomSSLSocketFactory\", \"old applicationProtocols: $parameters.applicationProtocols\")\n parameters.applicationProtocols = arrayOf(\"x-amzn-http-ca\")\n sslSocket.sslParameters = parameters\n }\n\n return sslSocket\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/alpn/AlpnOverrideTest.kt","line":42,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"override fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n val parameters = sslSocket.sslParameters\n Log.d(\"CustomSSLSocketFactory\", \"old applicationProtocols: $parameters.applicationProtocols\")\n parameters.applicationProtocols = arrayOf(\"x-amzn-http-ca\")\n sslSocket.sslParameters = parameters\n }\n\n return sslSocket\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/alpn/AlpnOverrideTest.kt","line":56,"symbol":"getWithCustomSocketFactory","kind":"function","lang":"kotlin","code":"@Test\n fun getWithCustomSocketFactory() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(CustomSSLSocketFactory(client.sslSocketFactory), client.x509TrustManager!!)\n .connectionSpecs(\n listOf(\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .supportsTlsExtensions(false)\n .build(),\n ),\n ).eventListener(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n val sslSocket = connection.socket() as SSLSocket\n println(\"Requested \" + sslSocket.sslParameters.applicationProtocols.joinToString())\n println(\"Negotiated \" + sslSocket.applicationProtocol)\n }\n },\n ).build()\n\n val request =\n Request\n .Builder()\n .url(\"https://www.google.com\")\n .build()\n client.newCall(request).execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/alpn/AlpnOverrideTest.kt","line":71,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n val sslSocket = connection.socket() as SSLSocket\n println(\"Requested \" + sslSocket.sslParameters.applicationProtocols.joinToString())\n println(\"Negotiated \" + sslSocket.applicationProtocol)\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/letsencrypt/LetsEncryptClientTest.kt","line":33,"symbol":"LetsEncryptClientTest","kind":"class","lang":"kotlin","doc":"Test for new Let's Encrypt Root Certificate.","code":"@Tag(\"Remote\")\nclass LetsEncryptClientTest {\n @Test fun get() {\n // These tests wont actually run before Android 8.0 as per\n // https://github.com/mannodermaus/android-junit5\n // Raised https://github.com/mannodermaus/android-junit5/issues/228 to reevaluate\n val androidMorEarlier = Build.VERSION.SDK_INT <= 23\n\n val clientBuilder = OkHttpClient.Builder()\n\n if (androidMorEarlier) {\n val cert: X509Certificate =\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELN"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/letsencrypt/LetsEncryptClientTest.kt","line":35,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test fun get() {\n // These tests wont actually run before Android 8.0 as per\n // https://github.com/mannodermaus/android-junit5\n // Raised https://github.com/mannodermaus/android-junit5/issues/228 to reevaluate\n val androidMorEarlier = Build.VERSION.SDK_INT <= 23\n\n val clientBuilder = OkHttpClient.Builder()\n\n if (androidMorEarlier) {\n val cert: X509Certificate =\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n B5T0Y3HsLuJvW5iB4YlcNHlsd"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/sni/SniOverrideTest.kt","line":40,"symbol":"SniOverrideTest","kind":"class","lang":"kotlin","doc":"Tests for SNI overriding on Android.","code":"@Tag(\"Remote\")\nclass SniOverrideTest {\n var client =\n OkHttpClient\n .Builder()\n .build()\n\n @Test\n fun getWithCustomSocketFactory() {\n assumeTrue(Build.VERSION.SDK_INT >= 24)\n\n class CustomSSLSocketFactory(\n delegate: SSLSocketFactory,\n ) : DelegatingSSLSocketFactory(delegate) {\n override fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n val parameters = sslSocket.sslParameters\n val sni = parameters.serverNames\n Log.d(\"CustomSSLSocketFactory\", \"old SNI: $sni\")\n parameters.serverNames = mutableListOf(SNIHostName(\"cloudflare-dns.com\"))\n sslSocket.sslParameters = parameters\n }\n\n return sslSocket\n }\n }\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(CustomSSLSocketFactory(client.sslSocketFactory), client.x509TrustManager!!)\n .hostnameVerifier { hostname, session ->\n val s = \"hostname: $hostname peerHost:${session.peerHost}\"\n Log.d(\"SniOverrideTest\", s)\n try {\n val cert = session.peerCertificates[0] as X509Certificate\n for ("} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/sni/SniOverrideTest.kt","line":47,"symbol":"getWithCustomSocketFactory","kind":"function","lang":"kotlin","code":"@Test\n fun getWithCustomSocketFactory() {\n assumeTrue(Build.VERSION.SDK_INT >= 24)\n\n class CustomSSLSocketFactory(\n delegate: SSLSocketFactory,\n ) : DelegatingSSLSocketFactory(delegate) {\n override fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n val parameters = sslSocket.sslParameters\n val sni = parameters.serverNames\n Log.d(\"CustomSSLSocketFactory\", \"old SNI: $sni\")\n parameters.serverNames = mutableListOf(SNIHostName(\"cloudflare-dns.com\"))\n sslSocket.sslParameters = parameters\n }\n\n return sslSocket\n }\n }\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(CustomSSLSocketFactory(client.sslSocketFactory), client.x509TrustManager!!)\n .hostnameVerifier { hostname, session ->\n val s = \"hostname: $hostname peerHost:${session.peerHost}\"\n Log.d(\"SniOverrideTest\", s)\n try {\n val cert = session.peerCertificates[0] as X509Certificate\n for (name in cert.subjectAlternativeNames) {\n if (name[0] as Int == 2) {\n Log.d(\"Sn"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/sni/SniOverrideTest.kt","line":51,"symbol":"CustomSSLSocketFactory","kind":"class","lang":"kotlin","code":"class CustomSSLSocketFactory(\n delegate: SSLSocketFactory,\n ) : DelegatingSSLSocketFactory(delegate) {\n override fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n val parameters = sslSocket.sslParameters\n val sni = parameters.serverNames\n Log.d(\"CustomSSLSocketFactory\", \"old SNI: $sni\")\n parameters.serverNames = mutableListOf(SNIHostName(\"cloudflare-dns.com\"))\n sslSocket.sslParameters = parameters\n }\n\n return sslSocket\n }\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/sni/SniOverrideTest.kt","line":54,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"override fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n val parameters = sslSocket.sslParameters\n val sni = parameters.serverNames\n Log.d(\"CustomSSLSocketFactory\", \"old SNI: $sni\")\n parameters.serverNames = mutableListOf(SNIHostName(\"cloudflare-dns.com\"))\n sslSocket.sslParameters = parameters\n }\n\n return sslSocket\n }"} {"repo":"okhttp","file":"android-test/src/androidTest/java/okhttp/android/test/sni/SniOverrideTest.kt","line":101,"symbol":"getWithDns","kind":"function","lang":"kotlin","code":"@Test\n fun getWithDns() {\n client =\n client\n .newBuilder()\n .dns {\n Dns.SYSTEM.lookup(\"sni.cloudflaressl.com\")\n }.build()\n\n val request =\n Request\n .Builder()\n .url(\"https://cloudflare-dns.com/cdn-cgi/trace\")\n .build()\n client.newCall(request).execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(response.body.string()).contains(\"h=cloudflare-dns.com\")\n }\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidLoggingTest.kt","line":37,"symbol":"AndroidLoggingTest","kind":"class","lang":"kotlin","code":"@RunWith(RobolectricTestRunner::class)\nclass AndroidLoggingTest {\n val clientBuilder =\n OkHttpClient.Builder().connectionSpecs(listOf(ConnectionSpec.CLEARTEXT)).dns {\n throw UnknownHostException(\"shortcircuit\")\n }\n\n val request = Request(\"http://google.com/robots.txt\".toHttpUrl())\n\n @Test\n fun testHttpLoggingInterceptor() {\n val interceptor =\n HttpLoggingInterceptor().apply {\n level = HttpLoggingInterceptor.Level.BASIC\n }\n\n val client = clientBuilder.addInterceptor(interceptor).build()\n\n try {\n client.newCall(request).execute()\n } catch (uhe: UnknownHostException) {\n // expected\n }\n\n val logs = ShadowLog.getLogsForTag(AndroidPlatform.Tag)\n assertThat(logs.map { it.type }).containsOnly(Log.INFO)\n assertThat(\n logs.map {\n it.msg.replace(\n \"\\\\d+\".toRegex(),\n \"\",\n )\n },\n ).containsExactly(\n \"--> GET http://google.com/robots.txt\",\n \"<-- HTTP FAILED: java.net.UnknownHostException: shortcircuit. ${request.url} (ms)\",\n )\n // We should consider if these logs should retain Exceptions\n assertThat(logs.last().throwable).isNull()\n }\n\n @Test\n fun testLoggingEventLi"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidLoggingTest.kt","line":46,"symbol":"testHttpLoggingInterceptor","kind":"function","lang":"kotlin","code":"@Test\n fun testHttpLoggingInterceptor() {\n val interceptor =\n HttpLoggingInterceptor().apply {\n level = HttpLoggingInterceptor.Level.BASIC\n }\n\n val client = clientBuilder.addInterceptor(interceptor).build()\n\n try {\n client.newCall(request).execute()\n } catch (uhe: UnknownHostException) {\n // expected\n }\n\n val logs = ShadowLog.getLogsForTag(AndroidPlatform.Tag)\n assertThat(logs.map { it.type }).containsOnly(Log.INFO)\n assertThat(\n logs.map {\n it.msg.replace(\n \"\\\\d+\".toRegex(),\n \"\",\n )\n },\n ).containsExactly(\n \"--> GET http://google.com/robots.txt\",\n \"<-- HTTP FAILED: java.net.UnknownHostException: shortcircuit. ${request.url} (ms)\",\n )\n // We should consider if these logs should retain Exceptions\n assertThat(logs.last().throwable).isNull()\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidLoggingTest.kt","line":78,"symbol":"testLoggingEventListener","kind":"function","lang":"kotlin","code":"@Test\n fun testLoggingEventListener() {\n val client = clientBuilder.eventListenerFactory(LoggingEventListener.Factory()).build()\n\n try {\n client.newCall(request).execute()\n } catch (uhe: UnknownHostException) {\n // expected\n }\n\n val logs = ShadowLog.getLogsForTag(AndroidPlatform.Tag)\n assertThat(logs.map { it.type }).containsOnly(Log.INFO)\n assertThat(\n logs.map {\n it.msg.replace(\n \"\\\\[\\\\d+ ms] \".toRegex(),\n \"\",\n )\n },\n ).containsExactly(\n \"callStart: Request{method=GET, url=http://google.com/robots.txt}\",\n \"proxySelectStart: http://google.com/\",\n \"proxySelectEnd: [DIRECT]\",\n \"dnsStart: google.com\",\n \"callFailed: java.net.UnknownHostException: shortcircuit\",\n )\n // We should consider if these logs should retain Exceptions\n assertThat(logs.last().throwable).isNull()\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidSocketAdapterTest.kt","line":42,"symbol":"AndroidSocketAdapterTest","kind":"class","lang":"kotlin","code":"@RunWith(ParameterizedRobolectricTestRunner::class)\nclass AndroidSocketAdapterTest(\n val adapter: SocketAdapter,\n) {\n val context: SSLContext by lazy {\n val provider: Provider = Conscrypt.newProviderBuilder().provideTrustManager(true).build()\n\n SSLContext.getInstance(\"TLS\", provider).apply {\n init(null, null, null)\n }\n }\n\n @Test\n fun testMatchesSupportedSocket() {\n val socketFactory = context.socketFactory\n\n val sslSocket = socketFactory.createSocket() as SSLSocket\n assertTrue(adapter.matchesSocket(sslSocket))\n\n adapter.configureTlsExtensions(sslSocket, null, listOf(HTTP_2, HTTP_1_1), null)\n // not connected\n assertNull(adapter.getSelectedProtocol(sslSocket))\n }\n\n @Test\n fun testMatchesSupportedAndroidSocketFactory() {\n assumeTrue(adapter is StandardAndroidSocketAdapter)\n\n assertTrue(adapter.matchesSocketFactory(context.socketFactory))\n assertNotNull(adapter.trustManager(context.socketFactory))\n }\n\n @Test\n fun testDoesntMatchSupportedCustomSocketFactory() {\n assumeFalse(adapter is StandardAndroidSocketAdapter)\n\n assertFalse(adapter.matchesSocketFactory(context.socketFactory))\n assertNull(adapter.trustManager(context.socke"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidSocketAdapterTest.kt","line":54,"symbol":"testMatchesSupportedSocket","kind":"function","lang":"kotlin","code":"@Test\n fun testMatchesSupportedSocket() {\n val socketFactory = context.socketFactory\n\n val sslSocket = socketFactory.createSocket() as SSLSocket\n assertTrue(adapter.matchesSocket(sslSocket))\n\n adapter.configureTlsExtensions(sslSocket, null, listOf(HTTP_2, HTTP_1_1), null)\n // not connected\n assertNull(adapter.getSelectedProtocol(sslSocket))\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidSocketAdapterTest.kt","line":66,"symbol":"testMatchesSupportedAndroidSocketFactory","kind":"function","lang":"kotlin","code":"@Test\n fun testMatchesSupportedAndroidSocketFactory() {\n assumeTrue(adapter is StandardAndroidSocketAdapter)\n\n assertTrue(adapter.matchesSocketFactory(context.socketFactory))\n assertNotNull(adapter.trustManager(context.socketFactory))\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidSocketAdapterTest.kt","line":74,"symbol":"testDoesntMatchSupportedCustomSocketFactory","kind":"function","lang":"kotlin","code":"@Test\n fun testDoesntMatchSupportedCustomSocketFactory() {\n assumeFalse(adapter is StandardAndroidSocketAdapter)\n\n assertFalse(adapter.matchesSocketFactory(context.socketFactory))\n assertNull(adapter.trustManager(context.socketFactory))\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidSocketAdapterTest.kt","line":82,"symbol":"testCustomSocket","kind":"function","lang":"kotlin","code":"@Test\n fun testCustomSocket() {\n val socketFactory = DelegatingSSLSocketFactory(context.socketFactory)\n\n assertFalse(adapter.matchesSocketFactory(socketFactory))\n\n val sslSocket =\n object : DelegatingSSLSocket(context.socketFactory.createSocket() as SSLSocket) {}\n assertFalse(adapter.matchesSocket(sslSocket))\n\n adapter.configureTlsExtensions(sslSocket, null, listOf(HTTP_2, HTTP_1_1), null)\n // not connected\n assertNull(adapter.getSelectedProtocol(sslSocket))\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/AndroidSocketAdapterTest.kt","line":98,"symbol":"data","kind":"function","lang":"kotlin","code":"@JvmStatic\n @Parameters(name = \"{0}\")\n fun data(): Collection =\n listOfNotNull(\n DeferredSocketAdapter(ConscryptSocketAdapter.factory),\n DeferredSocketAdapter(AndroidSocketAdapter.factory(\"org.conscrypt\")),\n StandardAndroidSocketAdapter.buildIfSupported(\"org.conscrypt\"),\n )"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/BaseOkHttpClientUnitTest.kt","line":35,"symbol":"BaseOkHttpClientUnitTest","kind":"class","lang":"kotlin","code":"abstract class BaseOkHttpClientUnitTest {\n private lateinit var client: OkHttpClient\n\n @Before\n fun setUp() {\n client =\n OkHttpClient\n .Builder()\n .cache(Cache(FakeFileSystem(), \"/cache\".toPath(), 10_000_000))\n .build()\n }\n\n @Test\n fun testRequestExternal() {\n assumeNetwork()\n\n val request = Request(\"https://www.google.com/robots.txt\".toHttpUrl())\n\n val networkRequest =\n request\n .newBuilder()\n .build()\n\n val call = client.newCall(networkRequest)\n\n call.execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.cacheResponse).isNull()\n }\n\n val cachedCall = client.newCall(request)\n\n cachedCall.execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.cacheResponse).isNotNull()\n }\n }\n\n @Test\n open fun testPublicSuffixDb() {\n val httpUrl = \"https://www.google.co.uk\".toHttpUrl()\n assertThat(httpUrl.topPrivateDomain()).isEqualTo(\"google.co.uk\")\n }\n\n private fun assumeNetwork() {\n try {\n InetAddress.getByName(\"www.google.com\")\n } catch (uhe: UnknownHostException) {\n throw AssumptionViolatedExceptio"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/BaseOkHttpClientUnitTest.kt","line":38,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@Before\n fun setUp() {\n client =\n OkHttpClient\n .Builder()\n .cache(Cache(FakeFileSystem(), \"/cache\".toPath(), 10_000_000))\n .build()\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/BaseOkHttpClientUnitTest.kt","line":47,"symbol":"testRequestExternal","kind":"function","lang":"kotlin","code":"@Test\n fun testRequestExternal() {\n assumeNetwork()\n\n val request = Request(\"https://www.google.com/robots.txt\".toHttpUrl())\n\n val networkRequest =\n request\n .newBuilder()\n .build()\n\n val call = client.newCall(networkRequest)\n\n call.execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.cacheResponse).isNull()\n }\n\n val cachedCall = client.newCall(request)\n\n cachedCall.execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.cacheResponse).isNotNull()\n }\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/BaseOkHttpClientUnitTest.kt","line":73,"symbol":"testPublicSuffixDb","kind":"function","lang":"kotlin","code":"@Test\n open fun testPublicSuffixDb() {\n val httpUrl = \"https://www.google.co.uk\".toHttpUrl()\n assertThat(httpUrl.topPrivateDomain()).isEqualTo(\"google.co.uk\")\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/BaseOkHttpClientUnitTest.kt","line":79,"symbol":"assumeNetwork","kind":"function","lang":"kotlin","code":"private fun assumeNetwork() {\n try {\n InetAddress.getByName(\"www.google.com\")\n } catch (uhe: UnknownHostException) {\n throw AssumptionViolatedException(uhe.message, uhe)\n }\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/DisabledInitialiserTest.kt","line":36,"symbol":"DisabledInitialiserTest","kind":"class","lang":"kotlin","code":"@RunWith(RobolectricTestRunner::class)\n@Config(\n sdk = [23, 26, 30, 33, 35],\n)\nclass DisabledInitialiserTest {\n @Before\n fun setContext() {\n // Ensure we aren't succeeding because of another test\n Platform.resetForTests()\n PlatformRegistry.applicationContext = null\n }\n\n @Test\n fun testWithoutContext() {\n val httpUrl = \"https://www.google.co.uk\".toHttpUrl()\n assertFailure { httpUrl.topPrivateDomain() }.all {\n hasMessage(\"Unable to load PublicSuffixDatabase.list resource.\")\n cause().isNotNull().all {\n hasMessage(\n \"Platform applicationContext not initialized. \" +\n \"Startup Initializer possibly disabled, \" +\n \"call OkHttp.initialize before test.\",\n )\n hasClass()\n }\n }\n }\n\n companion object {\n @AfterClass\n @JvmStatic\n fun resetContext() {\n // Ensure we don't make other tests fail\n Platform.resetForTests()\n }\n }\n}"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/DisabledInitialiserTest.kt","line":41,"symbol":"setContext","kind":"function","lang":"kotlin","code":"@Before\n fun setContext() {\n // Ensure we aren't succeeding because of another test\n Platform.resetForTests()\n PlatformRegistry.applicationContext = null\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/DisabledInitialiserTest.kt","line":48,"symbol":"testWithoutContext","kind":"function","lang":"kotlin","code":"@Test\n fun testWithoutContext() {\n val httpUrl = \"https://www.google.co.uk\".toHttpUrl()\n assertFailure { httpUrl.topPrivateDomain() }.all {\n hasMessage(\"Unable to load PublicSuffixDatabase.list resource.\")\n cause().isNotNull().all {\n hasMessage(\n \"Platform applicationContext not initialized. \" +\n \"Startup Initializer possibly disabled, \" +\n \"call OkHttp.initialize before test.\",\n )\n hasClass()\n }\n }\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/DisabledInitialiserTest.kt","line":65,"symbol":"resetContext","kind":"function","lang":"kotlin","code":"@AfterClass\n @JvmStatic\n fun resetContext() {\n // Ensure we don't make other tests fail\n Platform.resetForTests()\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/NonRobolectricOkHttpClientTest.kt","line":33,"symbol":"NonRobolectricOkHttpClientTest","kind":"class","lang":"kotlin","doc":"Android test running with only stubs.","code":"@RunWith(JUnit4::class)\nclass NonRobolectricOkHttpClientTest : BaseOkHttpClientUnitTest() {\n @Test\n override fun testPublicSuffixDb() {\n assertFailure { super.testPublicSuffixDb() }.all {\n hasMessage(\"Unable to load PublicSuffixDatabase.list resource.\")\n cause().isNotNull().all {\n hasMessage(\n \"Platform applicationContext not initialized. \" +\n \"Possibly running Android unit test without Robolectric. \" +\n \"Android tests should run with Robolectric \" +\n \"and call OkHttp.initialize before test\",\n )\n hasClass()\n }\n }\n }\n}"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/NonRobolectricOkHttpClientTest.kt","line":35,"symbol":"testPublicSuffixDb","kind":"function","lang":"kotlin","code":"@Test\n override fun testPublicSuffixDb() {\n assertFailure { super.testPublicSuffixDb() }.all {\n hasMessage(\"Unable to load PublicSuffixDatabase.list resource.\")\n cause().isNotNull().all {\n hasMessage(\n \"Platform applicationContext not initialized. \" +\n \"Possibly running Android unit test without Robolectric. \" +\n \"Android tests should run with Robolectric \" +\n \"and call OkHttp.initialize before test\",\n )\n hasClass()\n }\n }\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/RobolectricOkHttpClientTest.kt","line":26,"symbol":"RobolectricOkHttpClientTest","kind":"class","lang":"kotlin","code":"@RunWith(RobolectricTestRunner::class)\n@Config(\n sdk = [23, 26, 30, 33, 35],\n)\nclass RobolectricOkHttpClientTest : BaseOkHttpClientUnitTest() {\n @Before\n fun setContext() {\n // This is awkward because Robolectric won't run our initializers and we don't want test deps\n // https://github.com/robolectric/robolectric/issues/8461\n OkHttp.initialize(ApplicationProvider.getApplicationContext())\n }\n}"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/RobolectricOkHttpClientTest.kt","line":31,"symbol":"setContext","kind":"function","lang":"kotlin","code":"@Before\n fun setContext() {\n // This is awkward because Robolectric won't run our initializers and we don't want test deps\n // https://github.com/robolectric/robolectric/issues/8461\n OkHttp.initialize(ApplicationProvider.getApplicationContext())\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/ShadowDnsResolver.kt","line":27,"symbol":"ShadowDnsResolver","kind":"class","lang":"kotlin","code":"@Implements(DnsResolver::class)\nclass ShadowDnsResolver {\n var responder: (Request) -> Unit = {\n it.callback.onAnswer(listOf(), 0)\n }\n\n data class Request(\n val network: Network?,\n val domain: String,\n val nsType: Int,\n val flags: Int,\n val callback: DnsResolver.Callback>,\n )\n\n @Implementation\n fun query(\n network: Network?,\n domain: String,\n nsType: Int,\n flags: Int,\n executor: Executor,\n cancellationSignal: CancellationSignal?,\n callback: DnsResolver.Callback>,\n ) {\n responder(Request(network, domain, nsType, flags, callback))\n }\n\n companion object {\n @Implementation\n @JvmStatic\n fun getInstance(): DnsResolver = Shadow.newInstance(DnsResolver::class.java, arrayOf(), arrayOf())\n }\n}"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/ShadowDnsResolver.kt","line":41,"symbol":"query","kind":"function","lang":"kotlin","code":"@Implementation\n fun query(\n network: Network?,\n domain: String,\n nsType: Int,\n flags: Int,\n executor: Executor,\n cancellationSignal: CancellationSignal?,\n callback: DnsResolver.Callback>,\n ) {\n responder(Request(network, domain, nsType, flags, callback))\n }"} {"repo":"okhttp","file":"android-test/src/test/kotlin/okhttp/android/test/ShadowDnsResolver.kt","line":55,"symbol":"getInstance","kind":"function","lang":"kotlin","code":"@Implementation\n @JvmStatic\n fun getInstance(): DnsResolver = Shadow.newInstance(DnsResolver::class.java, arrayOf(), arrayOf())"} {"repo":"okhttp","file":"android-test/src/test/resources/robolectric.properties","line":1,"symbol":"sdk","kind":"field","lang":"properties","code":"sdk=36"} {"repo":"okhttp","file":"android-test-app/src/androidTest/kotlin/okhttp/android/testapp/IdnaTest.kt","line":22,"symbol":"IdnaTest","kind":"class","lang":"kotlin","code":"class IdnaTest {\n @Test\n fun testHostnameFunction() {\n assertEquals(\"xn--n3h.net\", \"https://☃.net/robots.txt\".toHttpUrl().host)\n }\n}"} {"repo":"okhttp","file":"android-test-app/src/androidTest/kotlin/okhttp/android/testapp/IdnaTest.kt","line":23,"symbol":"testHostnameFunction","kind":"function","lang":"kotlin","code":"@Test\n fun testHostnameFunction() {\n assertEquals(\"xn--n3h.net\", \"https://☃.net/robots.txt\".toHttpUrl().host)\n }"} {"repo":"okhttp","file":"android-test-app/src/androidTest/kotlin/okhttp/android/testapp/PublicSuffixDatabaseTest.kt","line":26,"symbol":"PublicSuffixDatabaseTest","kind":"class","lang":"kotlin","doc":"Run with \"./gradlew :android-test-app:connectedCheck -PandroidBuild=true\" and make sure ANDROID_SDK_ROOT is set.","code":"class PublicSuffixDatabaseTest {\n @Test\n fun testTopLevelDomain() {\n assertThat(\"https://www.google.com/robots.txt\".toHttpUrl().topPrivateDomain()).isEqualTo(\"google.com\")\n }\n}"} {"repo":"okhttp","file":"android-test-app/src/androidTest/kotlin/okhttp/android/testapp/PublicSuffixDatabaseTest.kt","line":27,"symbol":"testTopLevelDomain","kind":"function","lang":"kotlin","code":"@Test\n fun testTopLevelDomain() {\n assertThat(\"https://www.google.com/robots.txt\".toHttpUrl().topPrivateDomain()).isEqualTo(\"google.com\")\n }"} {"repo":"okhttp","file":"android-test-app/src/main/kotlin/okhttp/android/testapp/MainActivity.kt","line":29,"symbol":"MainActivity","kind":"class","lang":"kotlin","code":"open class MainActivity : ComponentActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n\n val client = OkHttpClient()\n\n // Ensure we are compiling against the right variant\n println(AndroidPlatform.isSupported)\n\n val url = \"https://github.com/lysine-dev/okhttp\".toHttpUrl()\n println(url.topPrivateDomain())\n\n client.newCall(Request(url)).enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n println(\"failed: $e\")\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n println(\"response: ${response.code}\")\n response.close()\n }\n },\n )\n }\n}"} {"repo":"okhttp","file":"android-test-app/src/main/kotlin/okhttp/android/testapp/MainActivity.kt","line":30,"symbol":"onCreate","kind":"function","lang":"kotlin","code":"override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n\n val client = OkHttpClient()\n\n // Ensure we are compiling against the right variant\n println(AndroidPlatform.isSupported)\n\n val url = \"https://github.com/lysine-dev/okhttp\".toHttpUrl()\n println(url.topPrivateDomain())\n\n client.newCall(Request(url)).enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n println(\"failed: $e\")\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n println(\"response: ${response.code}\")\n response.close()\n }\n },\n )\n }"} {"repo":"okhttp","file":"android-test-app/src/main/kotlin/okhttp/android/testapp/MainActivity.kt","line":43,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n println(\"failed: $e\")\n }"} {"repo":"okhttp","file":"android-test-app/src/main/kotlin/okhttp/android/testapp/MainActivity.kt","line":50,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n println(\"response: ${response.code}\")\n response.close()\n }"} {"repo":"okhttp","file":"android-test-app/src/main/kotlin/okhttp/android/testapp/TestApplication.kt","line":23,"symbol":"TestApplication","kind":"class","lang":"kotlin","code":"class TestApplication : Application() {\n override fun onCreate() {\n super.onCreate()\n\n if (isSecondaryProcess()) {\n OkHttp.initialize(applicationContext)\n }\n }\n\n private fun isSecondaryProcess(): Boolean = getProcess() != packageName\n\n @SuppressLint(\"DiscouragedPrivateApi\")\n private fun getProcess(): String? =\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n getProcessName()\n } else {\n Class\n .forName(\"android.app.ActivityThread\")\n .getDeclaredMethod(\"currentProcessName\")\n .apply { isAccessible = true }\n .invoke(null) as String\n }\n}"} {"repo":"okhttp","file":"android-test-app/src/main/kotlin/okhttp/android/testapp/TestApplication.kt","line":24,"symbol":"onCreate","kind":"function","lang":"kotlin","code":"override fun onCreate() {\n super.onCreate()\n\n if (isSecondaryProcess()) {\n OkHttp.initialize(applicationContext)\n }\n }"} {"repo":"okhttp","file":"android-test-app/src/main/kotlin/okhttp/android/testapp/TestApplication.kt","line":32,"symbol":"isSecondaryProcess","kind":"function","lang":"kotlin","code":"private fun isSecondaryProcess(): Boolean = getProcess() != packageName"} {"repo":"okhttp","file":"android-test-app/src/main/kotlin/okhttp/android/testapp/TestApplication.kt","line":34,"symbol":"getProcess","kind":"function","lang":"kotlin","code":"@SuppressLint(\"DiscouragedPrivateApi\")\n private fun getProcess(): String? =\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n getProcessName()\n } else {\n Class\n .forName(\"android.app.ActivityThread\")\n .getDeclaredMethod(\"currentProcessName\")\n .apply { isAccessible = true }\n .invoke(null) as String\n }"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/AlpnVersions.kt","line":18,"symbol":"alpnBootVersionForPatchVersion","kind":"function","lang":"kotlin","doc":"https://www.eclipse.org/jetty/documentation/current/alpn-chapter.html#alpn-versions","code":"private fun alpnBootVersionForPatchVersion(patchVersion: Int): String? =\n when (patchVersion) {\n in 0..24 -> \"8.1.0.v20141016\"\n in 25..30 -> \"8.1.2.v20141202\"\n in 31..50 -> \"8.1.3.v20150130\"\n in 51..59 -> \"8.1.4.v20150727\"\n in 60..64 -> \"8.1.5.v20150921\"\n in 65..70 -> \"8.1.6.v20151105\"\n in 71..77 -> \"8.1.7.v20160121\"\n in 78..101 -> \"8.1.8.v20160420\"\n in 102..111 -> \"8.1.9.v20160720\"\n in 112..120 -> \"8.1.10.v20161026\"\n in 121..160 -> \"8.1.11.v20170118\"\n in 161..181 -> \"8.1.12.v20180117\"\n in 191..242 -> \"8.1.13.v20181017\"\n else -> null\n }"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/AlpnVersions.kt","line":40,"symbol":"alpnBootVersion","kind":"function","lang":"kotlin","doc":"Returns the alpn-boot version specific to this OpenJDK 8 JVM, or null if this is not a Java 8 VM. https://github.com/xjdr/xio/blob/master/alpn-boot.gradle","code":"fun alpnBootVersion(): String? {\n val version = System.getProperty(\"alpn.boot.version\")\n\n if (version != null) {\n return version\n }\n\n val javaVersion = System.getProperty(\"java.version\")\n val match = \"1\\\\.8\\\\.0_(\\\\d+)(-.*)?\".toRegex().find(javaVersion) ?: return null\n\n return alpnBootVersionForPatchVersion(match.groupValues.first().toInt())\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":48,"symbol":"BndBuildAction","kind":"class","lang":"kotlin","doc":"A static BuildAction that does not capture the Task instance, enabling Configuration Cache compatibility. This class is based on bundled code from the BND Gradle Plugin. https://github.com/bndtools/bnd/blob/master/gradle-plugins/biz.aQute.bnd.gradle/src/main/java/aQute/bnd/gradle/BundleTaskExtension.java","code":"class BndBuildAction(\n private val properties: MapProperty,\n private val classpath: ConfigurableFileCollection,\n private val sourcepath: FileCollection,\n private val bundleSymbolicName: Provider,\n private val bundleVersion: Provider,\n private val bndfile: RegularFileProperty,\n private val bnd: Provider,\n private val layout: ProjectLayout,\n private val entryCompression: ZipEntryCompression,\n private val preserveFileTimestamps: Boolean,\n) : Action {\n constructor(\n extension: BundleTaskExtension,\n task: GradleJar,\n sourceSet: FileCollection,\n ) : this(\n extension.properties,\n extension.classpath,\n // Sourcepath default: all source\n sourceSet,\n // Symbolic name default logic\n task.archiveBaseName.zip(task.archiveClassifier) { baseName, classifier ->\n if (classifier.isNullOrEmpty()) baseName else \"$baseName-$classifier\"\n },\n task.archiveVersion.orElse(\"0\").map { version ->\n MavenVersion.parseMavenString(version).osGiVersion.toString()\n },\n extension.bndfile,\n extension.bnd,\n task.project.layout,\n task.entryCompression,\n task.isPreserveFileTimestamps,\n )\n\n override fun ex"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":83,"symbol":"execute","kind":"function","lang":"kotlin","code":"override fun execute(task: Task) {\n task as GradleJar\n val temporaryDir = task.temporaryDir\n val projectDir = layout.projectDirectory.asFile\n\n val gradleProperties = Properties()\n properties.get().forEach { (k, v) ->\n if (v is Provider<*>) {\n val value = v.getOrNull()\n if (value != null) gradleProperties[k] = value\n } else {\n gradleProperties[k] = v\n }\n }\n\n // Set default values if not present\n if (!gradleProperties.containsKey(Constants.BUNDLE_SYMBOLICNAME)) {\n gradleProperties[Constants.BUNDLE_SYMBOLICNAME] = bundleSymbolicName.get()\n }\n if (!gradleProperties.containsKey(Constants.BUNDLE_VERSION)) {\n gradleProperties[Constants.BUNDLE_VERSION] = bundleVersion.get()\n }\n\n // Do not capture 'task' in gradleProperties to avoid serialization issues\n\n try {\n Builder(Processor(gradleProperties, false)).use { builder ->\n val temporaryBndFile = File.createTempFile(\"bnd\", \".bnd\", temporaryDir)\n IO.writer(temporaryBndFile).use { writer ->\n val bndFileVal = bndfile.asFile.getOrNull()\n if (bndFileVal != null && bndFileVal.isFile) {\n Processor(gradleProperties).le"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":180,"symbol":"isZip","kind":"function","lang":"kotlin","code":"private fun isZip(file: File): Boolean =\n try {\n ZipFile(file).close()\n true\n } catch (e: Exception) {\n false\n }"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":193,"symbol":"installWorkaround","kind":"function","lang":"kotlin","doc":"BND is incompatible with Kotlin/Multiplatform because it assumes the JVM source set's name is 'main'. Work around this by creating a 'main' source set that forwards to 'jvmMain'.","code":"fun installWorkaround(project: org.gradle.api.Project): org.gradle.api.tasks.SourceSet {\n val sourceSets =\n project.extensions\n .getByType(org.gradle.api.plugins.JavaPluginExtension::class.java)\n .sourceSets\n val existingMain = sourceSets.findByName(\"main\")\n if (existingMain != null) return existingMain\n\n val jvmMainSourceSet = sourceSets.getByName(\"jvmMain\")\n val mainSourceSet =\n object : org.gradle.api.tasks.SourceSet by jvmMainSourceSet {\n override fun getName() = \"main\"\n\n override fun getProcessResourcesTaskName() = \"${jvmMainSourceSet.processResourcesTaskName}ForFakeMain\"\n\n override fun getCompileJavaTaskName() = \"${jvmMainSourceSet.compileJavaTaskName}ForFakeMain\"\n\n override fun getClassesTaskName() = \"${jvmMainSourceSet.classesTaskName}ForFakeMain\"\n\n override fun getCompileOnlyConfigurationName(): String = jvmMainSourceSet.compileOnlyConfigurationName + \"ForFakeMain\"\n\n override fun getCompileClasspathConfigurationName(): String = jvmMainSourceSet.compileClasspathConfigurationName + \"ForFakeMain\"\n\n override fun getImplementationConfigurationName(): String = "} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":204,"symbol":"getName","kind":"function","lang":"kotlin","code":"override fun getName() = \"main\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":206,"symbol":"getProcessResourcesTaskName","kind":"function","lang":"kotlin","code":"override fun getProcessResourcesTaskName() = \"${jvmMainSourceSet.processResourcesTaskName}ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":208,"symbol":"getCompileJavaTaskName","kind":"function","lang":"kotlin","code":"override fun getCompileJavaTaskName() = \"${jvmMainSourceSet.compileJavaTaskName}ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":210,"symbol":"getClassesTaskName","kind":"function","lang":"kotlin","code":"override fun getClassesTaskName() = \"${jvmMainSourceSet.classesTaskName}ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":212,"symbol":"getCompileOnlyConfigurationName","kind":"function","lang":"kotlin","code":"override fun getCompileOnlyConfigurationName(): String = jvmMainSourceSet.compileOnlyConfigurationName + \"ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":214,"symbol":"getCompileClasspathConfigurationName","kind":"function","lang":"kotlin","code":"override fun getCompileClasspathConfigurationName(): String = jvmMainSourceSet.compileClasspathConfigurationName + \"ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":216,"symbol":"getImplementationConfigurationName","kind":"function","lang":"kotlin","code":"override fun getImplementationConfigurationName(): String = jvmMainSourceSet.implementationConfigurationName + \"ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":218,"symbol":"getAnnotationProcessorConfigurationName","kind":"function","lang":"kotlin","code":"override fun getAnnotationProcessorConfigurationName(): String =\n jvmMainSourceSet.annotationProcessorConfigurationName + \"ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":221,"symbol":"getRuntimeClasspathConfigurationName","kind":"function","lang":"kotlin","code":"override fun getRuntimeClasspathConfigurationName(): String = jvmMainSourceSet.runtimeClasspathConfigurationName + \"ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":223,"symbol":"getRuntimeOnlyConfigurationName","kind":"function","lang":"kotlin","code":"override fun getRuntimeOnlyConfigurationName(): String = jvmMainSourceSet.runtimeOnlyConfigurationName + \"ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/BndBuildAction.kt","line":225,"symbol":"getTaskName","kind":"function","lang":"kotlin","code":"override fun getTaskName(\n verb: String?,\n target: String?,\n ) = \"${jvmMainSourceSet.getTaskName(verb, target)}ForFakeMain\""} {"repo":"okhttp","file":"build-logic/src/main/kotlin/JavaModules.kt","line":31,"symbol":"applyJavaModules","kind":"function","lang":"kotlin","code":"fun Project.applyJavaModules(\n moduleName: String,\n defaultVersion: Int = 8,\n javaModuleVersion: Int = 9,\n enableValidation: Boolean = true,\n) {\n plugins.withId(\"org.jetbrains.kotlin.jvm\") {\n applyJavaModulesJvm(\n moduleName = moduleName,\n defaultVersion = defaultVersion,\n javaModuleVersion = javaModuleVersion,\n enableValidation = enableValidation,\n )\n }\n\n plugins.withId(\"org.jetbrains.kotlin.multiplatform\") {\n applyJavaModulesMultiplatform(\n moduleName = moduleName,\n javaModuleVersion = javaModuleVersion,\n enableValidation = enableValidation,\n )\n }\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/JavaModules.kt","line":55,"symbol":"applyJavaModulesJvm","kind":"function","lang":"kotlin","code":"private fun Project.applyJavaModulesJvm(\n moduleName: String,\n defaultVersion: Int,\n javaModuleVersion: Int,\n enableValidation: Boolean,\n) {\n plugins.apply(\"me.champeau.mrjar\")\n\n configure {\n targetVersions(defaultVersion, javaModuleVersion)\n }\n\n tasks.named(\"compileJava9Java\").configure {\n val compileKotlinTask = tasks.getByName(\"compileKotlin\") as KotlinJvmCompile\n\n if (enableValidation) {\n compileKotlinTask.source(file(\"src/main/java9\"))\n }\n\n configureModuleInfoCompilation(moduleName, compileKotlinTask)\n\n val javaToolchains = project.extensions.getByType()\n val javaPluginExtension = project.extensions.getByType()\n javaCompiler.set(javaToolchains.compilerFor(javaPluginExtension.toolchain))\n }\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/JavaModules.kt","line":82,"symbol":"applyJavaModulesMultiplatform","kind":"function","lang":"kotlin","code":"private fun Project.applyJavaModulesMultiplatform(\n moduleName: String,\n javaModuleVersion: Int,\n enableValidation: Boolean,\n) {\n val compileJavaModuleInfo =\n tasks.register(\"compileJavaModuleInfo\") {\n val compileKotlinTask = tasks.getByName(\"compileKotlinJvm\") as KotlinJvmCompile\n val targetDir = compileKotlinTask.destinationDirectory.dir(\"../java9\")\n val sourceDir = file(\"src/jvmMain/java9\")\n\n val javaToolchains = project.extensions.getByType()\n javaCompiler.set(\n javaToolchains.compilerFor {\n languageVersion.set(JavaLanguageVersion.of(11))\n },\n )\n\n source(sourceDir)\n if (enableValidation) {\n compileKotlinTask.source(sourceDir)\n }\n\n outputs.dir(targetDir)\n destinationDirectory.set(targetDir)\n sourceCompatibility = JavaVersion.toVersion(javaModuleVersion).toString()\n targetCompatibility = JavaVersion.toVersion(javaModuleVersion).toString()\n options.release.set(javaModuleVersion)\n\n configureModuleInfoCompilation(moduleName, compileKotlinTask)\n }\n\n tasks.named(\"jvmJar\").configure {\n manifest {\n attributes(mapOf(\"Multi-Rel"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/JavaModules.kt","line":125,"symbol":"configureModuleInfoCompilation","kind":"function","lang":"kotlin","code":"private fun JavaCompile.configureModuleInfoCompilation(\n moduleName: String,\n compileKotlinTask: KotlinJvmCompile,\n) {\n dependsOn(compileKotlinTask)\n\n // Ignore warnings about using 'requires transitive' on automatic modules.\n options.compilerArgs.add(\"-Xlint:-requires-transitive-automatic\")\n\n // Patch the Kotlin output into the compilation so exporting packages works correctly.\n options.compilerArgs.addAll(\n listOf(\n \"--patch-module\",\n \"$moduleName=${compileKotlinTask.destinationDirectory.get().asFile}\",\n ),\n )\n\n classpath = compileKotlinTask.libraries\n modularity.inferModulePath.set(true)\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/Osgi.kt","line":30,"symbol":"applyOsgi","kind":"function","lang":"kotlin","code":"fun Project.applyOsgi(vararg bndProperties: String) {\n plugins.withId(\"org.jetbrains.kotlin.jvm\") { applyOsgi(\"jar\", \"osgiApi\", bndProperties) }\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/Osgi.kt","line":34,"symbol":"applyOsgi","kind":"function","lang":"kotlin","code":"private fun Project.applyOsgi(\n jarTaskName: String,\n osgiApiConfigurationName: String,\n bndProperties: Array,\n) {\n val osgi = project.sourceSets.create(\"osgi\")\n val osgiApi = project.configurations.getByName(osgiApiConfigurationName)\n\n project.dependencies { osgiApi(kotlinOsgi) }\n\n val jarTask = tasks.getByName(jarTaskName)\n val bundleExtension =\n jarTask.extensions.create(\n BundleTaskExtension.NAME,\n BundleTaskExtension::class.java,\n jarTask,\n )\n bundleExtension.run {\n setClasspath(osgi.compileClasspath + sourceSets[\"main\"].compileClasspath)\n properties.empty()\n bnd(*bndProperties)\n }\n jarTask.doLast(\n \"buildBundle\",\n BndBuildAction(bundleExtension, jarTask, sourceSets[\"main\"].allSource),\n )\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/Osgi.kt","line":62,"symbol":"applyOsgiMultiplatform","kind":"function","lang":"kotlin","code":"fun Project.applyOsgiMultiplatform(vararg bndProperties: String) {\n // BND is incompatible with Kotlin/Multiplatform because it assumes the JVM source set's\n // name is\n // 'main'. Work around this by creating a 'main' source set that forwards to 'jvmMain'.\n //\n // The forwarding SourceSet also needs to fake out some task names to prevent them from\n // being\n // registered twice.\n //\n // https://github.com/bndtools/bnd/issues/6590\n val mainSourceSet = BndBuildAction.installWorkaround(project)\n\n val osgiApi = configurations.create(\"osgiApi\")\n dependencies { osgiApi(kotlinOsgi) }\n\n tasks.named(\"jvmJar\").configure {\n val bundleExtension =\n extensions.create(\n BundleTaskExtension.NAME,\n BundleTaskExtension::class.java,\n this,\n )\n val osgiApiArtifacts = osgiApi.artifacts\n val jvmMainClasses = tasks.named(\"jvmMainClasses\").map { it.outputs.files }\n bundleExtension.apply {\n classpath(osgiApiArtifacts)\n classpath(jvmMainClasses)\n properties.empty()\n bnd(*bndProperties)\n }\n doLast(\"buildBundle\", BndBuildAction(bundleExtension, this, mainSourceSet.allSource))\n }\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/okhttp.jvm-conventions.gradle.kts","line":13,"symbol":"library","kind":"function","lang":"kotlin","code":"fun library(alias: String) = libs.findLibrary(alias).get().get().let {\n \"${it.module.group}:${it.module.name}:${it.versionConstraint.requiredVersion}\"\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/okhttp.jvm-conventions.gradle.kts","line":16,"symbol":"version","kind":"function","lang":"kotlin","code":"fun version(alias: String) = libs.findVersion(alias).get().toString()"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/okhttp.quality-conventions.gradle.kts","line":15,"symbol":"library","kind":"function","lang":"kotlin","code":"fun library(alias: String) = libs.findLibrary(alias).get().get().let {\n \"${it.module.group}:${it.module.name}:${it.versionConstraint.requiredVersion}\"\n}"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/okhttp.quality-conventions.gradle.kts","line":18,"symbol":"version","kind":"function","lang":"kotlin","code":"fun version(alias: String) = libs.findVersion(alias).get().toString()"} {"repo":"okhttp","file":"build-logic/src/main/kotlin/okhttp.testing-conventions.gradle.kts","line":12,"symbol":"library","kind":"function","lang":"kotlin","code":"fun library(alias: String) = libs.findLibrary(alias).get().get().let {\n \"${it.module.group}:${it.module.name}:${it.versionConstraint.requiredVersion}\"\n}"} {"repo":"okhttp","file":"deploy_website.sh","line":9,"symbol":"REPO","kind":"variable","lang":"bash","code":"REPO=\"git@github.com:lysine-dev/okhttp.git\""} {"repo":"okhttp","file":"deploy_website.sh","line":10,"symbol":"DIR","kind":"variable","lang":"bash","code":"DIR=temp-clone"} {"repo":"okhttp","file":"fuzzing/fuzzingserver-test.sh","line":3,"symbol":"SCRIPT_DIR","kind":"variable","lang":"bash","code":"SCRIPT_DIR=\"$( cd \"$( dirname \"$0\" )\" && pwd )\""} {"repo":"okhttp","file":"fuzzing/fuzzingserver-update-expected.sh","line":3,"symbol":"SCRIPT_DIR","kind":"variable","lang":"bash","code":"SCRIPT_DIR=\"$( cd \"$( dirname \"$0\" )\" && pwd )\""} {"repo":"okhttp","file":"gradle/gradle-daemon-jvm.properties","line":2,"symbol":"toolchainVendor","kind":"field","lang":"properties","code":"toolchainVendor=ADOPTIUM"} {"repo":"okhttp","file":"gradle/gradle-daemon-jvm.properties","line":3,"symbol":"toolchainVersion","kind":"field","lang":"properties","code":"toolchainVersion=21"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":1,"symbol":"distributionBase","kind":"field","lang":"properties","code":"distributionBase=GRADLE_USER_HOME"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":2,"symbol":"distributionPath","kind":"field","lang":"properties","code":"distributionPath=wrapper/dists"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":3,"symbol":"distributionUrl","kind":"field","lang":"properties","code":"distributionUrl=https\\://services.gradle.org/distributions/gradle-9.6.1-bin.zip"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":4,"symbol":"networkTimeout","kind":"field","lang":"properties","code":"networkTimeout=10000"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":5,"symbol":"retries","kind":"field","lang":"properties","code":"retries=0"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":6,"symbol":"retryBackOffMs","kind":"field","lang":"properties","code":"retryBackOffMs=500"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":7,"symbol":"validateDistributionUrl","kind":"field","lang":"properties","code":"validateDistributionUrl=true"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":8,"symbol":"zipStoreBase","kind":"field","lang":"properties","code":"zipStoreBase=GRADLE_USER_HOME"} {"repo":"okhttp","file":"gradle/wrapper/gradle-wrapper.properties","line":9,"symbol":"zipStorePath","kind":"field","lang":"properties","code":"zipStorePath=wrapper/dists"} {"repo":"okhttp","file":"gradle.properties","line":1,"symbol":"org.gradle.caching","kind":"field","lang":"properties","code":"org.gradle.caching=true"} {"repo":"okhttp","file":"gradle.properties","line":2,"symbol":"org.gradle.parallel","kind":"field","lang":"properties","code":"org.gradle.parallel=true"} {"repo":"okhttp","file":"gradle.properties","line":5,"symbol":"org.gradle.configuration-cache","kind":"field","lang":"properties","code":"org.gradle.configuration-cache=true"} {"repo":"okhttp","file":"gradle.properties","line":6,"symbol":"org.gradle.configuration-cache.problems","kind":"field","lang":"properties","code":"org.gradle.configuration-cache.problems=fail"} {"repo":"okhttp","file":"gradle.properties","line":7,"symbol":"org.gradle.configuration-cache.parallel","kind":"field","lang":"properties","code":"org.gradle.configuration-cache.parallel=true"} {"repo":"okhttp","file":"gradle.properties","line":10,"symbol":"org.gradle.isolated-projects","kind":"field","lang":"properties","code":"org.gradle.isolated-projects=true"} {"repo":"okhttp","file":"gradle.properties","line":12,"symbol":"android.useAndroidX","kind":"field","lang":"properties","code":"android.useAndroidX=true"} {"repo":"okhttp","file":"gradle.properties","line":13,"symbol":"kotlin.mpp.applyDefaultHierarchyTemplate","kind":"field","lang":"properties","code":"kotlin.mpp.applyDefaultHierarchyTemplate=false"} {"repo":"okhttp","file":"gradle.properties","line":15,"symbol":"androidBuild","kind":"field","lang":"properties","code":"androidBuild=false"} {"repo":"okhttp","file":"gradle.properties","line":16,"symbol":"graalBuild","kind":"field","lang":"properties","code":"graalBuild=false"} {"repo":"okhttp","file":"gradle.properties","line":17,"symbol":"loomBuild","kind":"field","lang":"properties","code":"loomBuild=false"} {"repo":"okhttp","file":"gradle.properties","line":18,"symbol":"okhttpModuleTests","kind":"field","lang":"properties","code":"okhttpModuleTests=false"} {"repo":"okhttp","file":"gradle.properties","line":19,"symbol":"okhttpDokka","kind":"field","lang":"properties","code":"okhttpDokka=false"} {"repo":"okhttp","file":"gradle.properties","line":22,"symbol":"org.gradle.jvmargs","kind":"field","lang":"properties","code":"org.gradle.jvmargs=-Dfile.encoding=UTF-8"} {"repo":"okhttp","file":"gradle.properties","line":25,"symbol":"android.builtInKotlin","kind":"field","lang":"properties","code":"android.builtInKotlin=true"} {"repo":"okhttp","file":"gradle.properties","line":26,"symbol":"android.newDsl","kind":"field","lang":"properties","code":"android.newDsl=true"} {"repo":"okhttp","file":"gradlew","line":70,"symbol":"app_path","kind":"variable","lang":"bash","doc":"Resolve links: $0 may be a link","code":"app_path=$0"} {"repo":"okhttp","file":"gradlew","line":74,"symbol":"APP_HOME","kind":"variable","lang":"bash","code":"APP_HOME=${app_path%\"${app_path##*/}\"}"} {"repo":"okhttp","file":"gradlew","line":77,"symbol":"ls","kind":"variable","lang":"bash","code":"ls=$( ls -ld \"$app_path\" )"} {"repo":"okhttp","file":"gradlew","line":78,"symbol":"link","kind":"variable","lang":"bash","code":"link=${ls#*' -> '}"} {"repo":"okhttp","file":"gradlew","line":80,"symbol":"app_path","kind":"variable","lang":"bash","code":"app_path=$link"} {"repo":"okhttp","file":"gradlew","line":81,"symbol":"app_path","kind":"variable","lang":"bash","code":"app_path=$APP_HOME$link"} {"repo":"okhttp","file":"gradlew","line":87,"symbol":"APP_BASE_NAME","kind":"variable","lang":"bash","doc":"This is normally unused shellcheck disable=SC2034","code":"APP_BASE_NAME=${0##*/}"} {"repo":"okhttp","file":"gradlew","line":89,"symbol":"APP_HOME","kind":"variable","lang":"bash","doc":"Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)","code":"APP_HOME=$( cd -P \"${APP_HOME:-./}\" > /dev/null && printf '%s\\n' \"$PWD\" )"} {"repo":"okhttp","file":"gradlew","line":92,"symbol":"MAX_FD","kind":"variable","lang":"bash","doc":"Use the maximum available, or set MAX_FD != -1 to use that value.","code":"MAX_FD=maximum"} {"repo":"okhttp","file":"gradlew","line":94,"symbol":"warn","kind":"function","lang":"bash","code":"warn () {\n echo \"$*\"\n} >&2"} {"repo":"okhttp","file":"gradlew","line":98,"symbol":"die","kind":"function","lang":"bash","code":"die () {\n echo\n echo \"$*\"\n echo\n exit 1\n} >&2"} {"repo":"okhttp","file":"gradlew","line":106,"symbol":"cygwin","kind":"variable","lang":"bash","doc":"OS specific support (must be 'true' or 'false').","code":"cygwin=false"} {"repo":"okhttp","file":"gradlew","line":107,"symbol":"msys","kind":"variable","lang":"bash","code":"msys=false"} {"repo":"okhttp","file":"gradlew","line":108,"symbol":"darwin","kind":"variable","lang":"bash","code":"darwin=false"} {"repo":"okhttp","file":"gradlew","line":109,"symbol":"nonstop","kind":"variable","lang":"bash","code":"nonstop=false"} {"repo":"okhttp","file":"gradlew","line":111,"symbol":"cygwin","kind":"variable","lang":"bash","code":"cygwin=true"} {"repo":"okhttp","file":"gradlew","line":112,"symbol":"darwin","kind":"variable","lang":"bash","code":"darwin=true"} {"repo":"okhttp","file":"gradlew","line":113,"symbol":"msys","kind":"variable","lang":"bash","code":"msys=true"} {"repo":"okhttp","file":"gradlew","line":114,"symbol":"nonstop","kind":"variable","lang":"bash","code":"nonstop=true"} {"repo":"okhttp","file":"gradlew","line":123,"symbol":"JAVACMD","kind":"variable","lang":"bash","doc":"IBM's JDK on AIX uses strange locations for the executables","code":"JAVACMD=$JAVA_HOME/jre/sh/java"} {"repo":"okhttp","file":"gradlew","line":125,"symbol":"JAVACMD","kind":"variable","lang":"bash","code":"JAVACMD=$JAVA_HOME/bin/java"} {"repo":"okhttp","file":"gradlew","line":134,"symbol":"JAVACMD","kind":"variable","lang":"bash","code":"JAVACMD=java"} {"repo":"okhttp","file":"gradlew","line":150,"symbol":"MAX_FD","kind":"variable","lang":"bash","doc":"In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. shellcheck disable=SC2039,SC3045","code":"MAX_FD=$( ulimit -H -n )"} {"repo":"okhttp","file":"gradlew","line":173,"symbol":"APP_HOME","kind":"variable","lang":"bash","code":"APP_HOME=$( cygpath --path --mixed \"$APP_HOME\" )"} {"repo":"okhttp","file":"gradlew","line":175,"symbol":"JAVACMD","kind":"variable","lang":"bash","code":"JAVACMD=$( cygpath --unix \"$JAVACMD\" )"} {"repo":"okhttp","file":"gradlew","line":182,"symbol":"t","kind":"variable","lang":"bash","code":"t=${arg#/}"} {"repo":"okhttp","file":"gradlew","line":182,"symbol":"t","kind":"variable","lang":"bash","code":"t=/"} {"repo":"okhttp","file":"gradlew","line":187,"symbol":"arg","kind":"variable","lang":"bash","code":"arg=$( cygpath --path --ignore --mixed \"$arg\" )"} {"repo":"okhttp","file":"gradlew","line":203,"symbol":"DEFAULT_JVM_OPTS","kind":"variable","lang":"bash","doc":"Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.","code":"DEFAULT_JVM_OPTS='\"-Xmx64m\" \"-Xms64m\"'"} {"repo":"okhttp","file":"maven-tests/.mvn/wrapper/maven-wrapper.properties","line":17,"symbol":"wrapperVersion","kind":"field","lang":"properties","code":"wrapperVersion=3.3.4"} {"repo":"okhttp","file":"maven-tests/.mvn/wrapper/maven-wrapper.properties","line":18,"symbol":"distributionType","kind":"field","lang":"properties","code":"distributionType=only-script"} {"repo":"okhttp","file":"maven-tests/.mvn/wrapper/maven-wrapper.properties","line":19,"symbol":"distributionUrl","kind":"field","lang":"properties","code":"distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/4.0.0-rc-6/apache-maven-4.0.0-rc-6-bin.zip"} {"repo":"okhttp","file":"maven-tests/mvnw","line":36,"symbol":"native_path","kind":"function","lang":"bash","doc":"OS specific support.","code":"native_path() { printf %s\\\\n \"$1\"; }"} {"repo":"okhttp","file":"maven-tests/mvnw","line":39,"symbol":"JAVA_HOME","kind":"variable","lang":"bash","code":"JAVA_HOME=\"$(cygpath --unix \"$JAVA_HOME\")\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":40,"symbol":"native_path","kind":"function","lang":"bash","code":"native_path() { cygpath --path --windows \"$1\"; }"} {"repo":"okhttp","file":"maven-tests/mvnw","line":45,"symbol":"set_java_home","kind":"function","lang":"bash","doc":"set JAVACMD and JAVACCMD","code":"set_java_home() {\n # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched\n if [ -n \"${JAVA_HOME-}\" ]; then\n if [ -x \"$JAVA_HOME/jre/sh/java\" ]; then\n # IBM's JDK on AIX uses strange locations for the executables\n JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n JAVACCMD=\"$JAVA_HOME/jre/sh/javac\"\n else\n JAVACMD=\"$JAVA_HOME/bin/java\"\n JAVACCMD=\"$JAVA_HOME/bin/javac\"\n\n if [ ! -x \"$JAVACMD\" ] || [ ! -x \"$JAVACCMD\" ]; then\n echo \"The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run.\" >&2\n echo \"JAVA_HOME is set to \\\"$JAVA_HOME\\\", but \\\"\\$JAVA_HOME/bin/java\\\" or \\\"\\$JAVA_HOME/bin/javac\\\" does not exist.\" >&2\n return 1\n fi\n fi\n else\n JAVACMD=\"$(\n 'set' +e\n 'unset' -f command 2>/dev/null\n 'command' -v java\n )\" || :\n JAVACCMD=\"$(\n 'set' +e\n 'unset' -f command 2>/dev/null\n 'command' -v javac\n )\" || :\n\n if [ ! -x \"${JAVACMD-}\" ] || [ ! -x \"${JAVACCMD-}\" ]; then\n echo \"The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run.\" >&2\n return 1\n fi\n fi\n}"} {"repo":"okhttp","file":"maven-tests/mvnw","line":50,"symbol":"JAVACMD","kind":"variable","lang":"bash","doc":"IBM's JDK on AIX uses strange locations for the executables","code":"JAVACMD=\"$JAVA_HOME/jre/sh/java\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":51,"symbol":"JAVACCMD","kind":"variable","lang":"bash","code":"JAVACCMD=\"$JAVA_HOME/jre/sh/javac\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":53,"symbol":"JAVACMD","kind":"variable","lang":"bash","code":"JAVACMD=\"$JAVA_HOME/bin/java\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":54,"symbol":"JAVACCMD","kind":"variable","lang":"bash","code":"JAVACCMD=\"$JAVA_HOME/bin/javac\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":63,"symbol":"JAVACMD","kind":"variable","lang":"bash","code":"JAVACMD=\"$(\n 'set' +e\n 'unset' -f command 2>/dev/null\n 'command' -v java\n )\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":68,"symbol":"JAVACCMD","kind":"variable","lang":"bash","code":"JAVACCMD=\"$(\n 'set' +e\n 'unset' -f command 2>/dev/null\n 'command' -v javac\n )\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":82,"symbol":"hash_string","kind":"function","lang":"bash","doc":"hash string like Java String::hashCode","code":"hash_string() {\n str=\"${1:-}\" h=0\n while [ -n \"$str\" ]; do\n char=\"${str%\"${str#?}\"}\"\n h=$(((h * 31 + $(LC_CTYPE=C printf %d \"'$char\")) % 4294967296))\n str=\"${str#?}\"\n done\n printf %x\\\\n $h\n}"} {"repo":"okhttp","file":"maven-tests/mvnw","line":83,"symbol":"str","kind":"variable","lang":"bash","code":"str=\"${1:-}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":83,"symbol":"h","kind":"variable","lang":"bash","code":"h=0"} {"repo":"okhttp","file":"maven-tests/mvnw","line":85,"symbol":"char","kind":"variable","lang":"bash","code":"char=\"${str%\"${str#?}\"}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":86,"symbol":"h","kind":"variable","lang":"bash","code":"h=$(((h * 31 + $(LC_CTYPE=C printf %d \"'$char\")) % 4294967296))"} {"repo":"okhttp","file":"maven-tests/mvnw","line":86,"symbol":"LC_CTYPE","kind":"variable","lang":"bash","code":"LC_CTYPE=C"} {"repo":"okhttp","file":"maven-tests/mvnw","line":87,"symbol":"str","kind":"variable","lang":"bash","code":"str=\"${str#?}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":92,"symbol":"verbose","kind":"function","lang":"bash","code":"verbose() { :; }"} {"repo":"okhttp","file":"maven-tests/mvnw","line":93,"symbol":"verbose","kind":"function","lang":"bash","code":"verbose() { printf %s\\\\n \"${1-}\"; }"} {"repo":"okhttp","file":"maven-tests/mvnw","line":95,"symbol":"die","kind":"function","lang":"bash","code":"die() {\n printf %s\\\\n \"$1\" >&2\n exit 1\n}"} {"repo":"okhttp","file":"maven-tests/mvnw","line":100,"symbol":"trim","kind":"function","lang":"bash","code":"trim() {\n # MWRAPPER-139:\n # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.\n # Needed for removing poorly interpreted newline sequences when running in more\n # exotic environments such as mingw bash on Windows.\n printf \"%s\" \"${1}\" | tr -d '[:space:]'\n}"} {"repo":"okhttp","file":"maven-tests/mvnw","line":109,"symbol":"IFS","kind":"variable","lang":"bash","doc":"parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties","code":"IFS=\"=\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":111,"symbol":"distributionUrl","kind":"variable","lang":"bash","code":"distributionUrl=$(trim \"${value-}\")"} {"repo":"okhttp","file":"maven-tests/mvnw","line":112,"symbol":"distributionSha256Sum","kind":"variable","lang":"bash","code":"distributionSha256Sum=$(trim \"${value-}\")"} {"repo":"okhttp","file":"maven-tests/mvnw","line":119,"symbol":"MVN_CMD","kind":"variable","lang":"bash","code":"MVN_CMD=mvnd.sh"} {"repo":"okhttp","file":"maven-tests/mvnw","line":119,"symbol":"_MVNW_REPO_PATTERN","kind":"variable","lang":"bash","code":"_MVNW_REPO_PATTERN=/maven/mvnd/"} {"repo":"okhttp","file":"maven-tests/mvnw","line":121,"symbol":"distributionPlatform","kind":"variable","lang":"bash","code":"distributionPlatform=windows-amd64"} {"repo":"okhttp","file":"maven-tests/mvnw","line":122,"symbol":"distributionPlatform","kind":"variable","lang":"bash","code":"distributionPlatform=darwin-amd64"} {"repo":"okhttp","file":"maven-tests/mvnw","line":123,"symbol":"distributionPlatform","kind":"variable","lang":"bash","code":"distributionPlatform=darwin-aarch64"} {"repo":"okhttp","file":"maven-tests/mvnw","line":124,"symbol":"distributionPlatform","kind":"variable","lang":"bash","code":"distributionPlatform=linux-amd64"} {"repo":"okhttp","file":"maven-tests/mvnw","line":127,"symbol":"distributionPlatform","kind":"variable","lang":"bash","code":"distributionPlatform=linux-amd64"} {"repo":"okhttp","file":"maven-tests/mvnw","line":130,"symbol":"distributionUrl","kind":"variable","lang":"bash","code":"distributionUrl=\"${distributionUrl%-bin.*}-$distributionPlatform.zip\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":132,"symbol":"MVN_CMD","kind":"variable","lang":"bash","code":"MVN_CMD=mvnd.sh"} {"repo":"okhttp","file":"maven-tests/mvnw","line":132,"symbol":"_MVNW_REPO_PATTERN","kind":"variable","lang":"bash","code":"_MVNW_REPO_PATTERN=/maven/mvnd/"} {"repo":"okhttp","file":"maven-tests/mvnw","line":133,"symbol":"MVN_CMD","kind":"variable","lang":"bash","code":"MVN_CMD=\"mvn${0##*/mvnw}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":133,"symbol":"_MVNW_REPO_PATTERN","kind":"variable","lang":"bash","code":"_MVNW_REPO_PATTERN=/org/apache/maven/"} {"repo":"okhttp","file":"maven-tests/mvnw","line":138,"symbol":"distributionUrl","kind":"variable","lang":"bash","doc":"apply MVNW_REPOURL and calculate MAVEN_HOME maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/","code":"distributionUrl=\"$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*\"$_MVNW_REPO_PATTERN\"}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":139,"symbol":"distributionUrlName","kind":"variable","lang":"bash","code":"distributionUrlName=\"${distributionUrl##*/}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":140,"symbol":"distributionUrlNameMain","kind":"variable","lang":"bash","code":"distributionUrlNameMain=\"${distributionUrlName%.*}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":141,"symbol":"distributionUrlNameMain","kind":"variable","lang":"bash","code":"distributionUrlNameMain=\"${distributionUrlNameMain%-bin}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":142,"symbol":"MAVEN_USER_HOME","kind":"variable","lang":"bash","code":"MAVEN_USER_HOME=\"${MAVEN_USER_HOME:-${HOME}/.m2}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":143,"symbol":"MAVEN_HOME","kind":"variable","lang":"bash","code":"MAVEN_HOME=\"${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string \"$distributionUrl\")\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":145,"symbol":"exec_maven","kind":"function","lang":"bash","code":"exec_maven() {\n unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :\n exec \"$MAVEN_HOME/bin/$MVN_CMD\" \"$@\" || die \"cannot exec $MAVEN_HOME/bin/$MVN_CMD\"\n}"} {"repo":"okhttp","file":"maven-tests/mvnw","line":161,"symbol":"TMP_DOWNLOAD_DIR","kind":"variable","lang":"bash","doc":"prepare tmp dir","code":"TMP_DOWNLOAD_DIR=\"$(mktemp -d)\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":162,"symbol":"clean","kind":"function","lang":"bash","code":"clean() { rm -rf -- \"$TMP_DOWNLOAD_DIR\"; }"} {"repo":"okhttp","file":"maven-tests/mvnw","line":177,"symbol":"distributionUrl","kind":"variable","lang":"bash","code":"distributionUrl=\"${distributionUrl%.zip}.tar.gz\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":178,"symbol":"distributionUrlName","kind":"variable","lang":"bash","code":"distributionUrlName=\"${distributionUrl##*/}\""} {"repo":"okhttp","file":"maven-tests/mvnw","line":182,"symbol":"__MVNW_QUIET_WGET","kind":"variable","lang":"bash","doc":"verbose opt","code":"__MVNW_QUIET_WGET=--quiet"} {"repo":"okhttp","file":"maven-tests/mvnw","line":182,"symbol":"__MVNW_QUIET_CURL","kind":"variable","lang":"bash","doc":"verbose opt","code":"__MVNW_QUIET_CURL=--silent"} {"repo":"okhttp","file":"maven-tests/mvnw","line":182,"symbol":"__MVNW_QUIET_UNZIP","kind":"variable","lang":"bash","doc":"verbose opt","code":"__MVNW_QUIET_UNZIP=-q"} {"repo":"okhttp","file":"maven-tests/mvnw","line":182,"symbol":"__MVNW_QUIET_TAR","kind":"variable","lang":"bash","doc":"verbose opt","code":"__MVNW_QUIET_TAR=''"} {"repo":"okhttp","file":"maven-tests/mvnw","line":183,"symbol":"__MVNW_QUIET_WGET","kind":"variable","lang":"bash","code":"__MVNW_QUIET_WGET=''"} {"repo":"okhttp","file":"maven-tests/mvnw","line":183,"symbol":"__MVNW_QUIET_CURL","kind":"variable","lang":"bash","code":"__MVNW_QUIET_CURL=''"} {"repo":"okhttp","file":"maven-tests/mvnw","line":183,"symbol":"__MVNW_QUIET_UNZIP","kind":"variable","lang":"bash","code":"__MVNW_QUIET_UNZIP=''"} {"repo":"okhttp","file":"maven-tests/mvnw","line":183,"symbol":"__MVNW_QUIET_TAR","kind":"variable","lang":"bash","code":"__MVNW_QUIET_TAR=v"} {"repo":"okhttp","file":"maven-tests/mvnw","line":187,"symbol":"MVNW_USERNAME","kind":"variable","lang":"bash","code":"MVNW_USERNAME=''"} {"repo":"okhttp","file":"maven-tests/mvnw","line":187,"symbol":"MVNW_PASSWORD","kind":"variable","lang":"bash","code":"MVNW_PASSWORD=''"} {"repo":"okhttp","file":"maven-tests/mvnw","line":188,"symbol":"MVNW_USERNAME","kind":"variable","lang":"bash","code":"MVNW_USERNAME=''"} {"repo":"okhttp","file":"maven-tests/mvnw","line":188,"symbol":"MVNW_PASSWORD","kind":"variable","lang":"bash","code":"MVNW_PASSWORD=''"} {"repo":"okhttp","file":"maven-tests/mvnw","line":199,"symbol":"javaSource","kind":"variable","lang":"bash","code":"javaSource=\"$TMP_DOWNLOAD_DIR/Downloader.java\""} {"repo":"okhttp","file":"maven-tests/src/main/java/com/squareup/okhttp3/maventest/SampleHttpClient.java","line":27,"symbol":"SampleHttpClient","kind":"class","lang":"java","code":"public class SampleHttpClient {\n private final OkHttpClient client;\n\n public SampleHttpClient() {\n client = new OkHttpClient.Builder().build();\n }\n\n public void makeCall(HttpUrl url) throws IOException {\n try (Response response = client.newCall(new Request(url, Headers.EMPTY, \"GET\", null)).execute()) {\n System.out.println(response.body().string());\n }\n }\n}"} {"repo":"okhttp","file":"maven-tests/src/main/java/com/squareup/okhttp3/maventest/SampleHttpClient.java","line":30,"symbol":"SampleHttpClient","kind":"constructor","lang":"java","code":"public SampleHttpClient() {\n client = new OkHttpClient.Builder().build();\n }"} {"repo":"okhttp","file":"maven-tests/src/main/java/com/squareup/okhttp3/maventest/SampleHttpClient.java","line":34,"symbol":"makeCall","kind":"method","lang":"java","code":"public void makeCall(HttpUrl url) throws IOException {\n try (Response response = client.newCall(new Request(url, Headers.EMPTY, \"GET\", null)).execute()) {\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"maven-tests/src/test/java/com/squareup/okhttp3/maventest/AppTest.java","line":28,"symbol":"AppTest","kind":"class","lang":"java","doc":"Unit test for simple App.","code":"public class AppTest {\n private final MockWebServer mockWebServer = new MockWebServer();\n\n @Test\n public void testApp() throws IOException {\n mockWebServer.enqueue(new MockResponse(200, Headers.of(), \"Hello, Maven!\"));\n mockWebServer.start();\n\n new SampleHttpClient().makeCall(mockWebServer.url(\"/\"));\n }\n}"} {"repo":"okhttp","file":"maven-tests/src/test/java/com/squareup/okhttp3/maventest/AppTest.java","line":31,"symbol":"testApp","kind":"method","lang":"java","code":"@Test\n public void testApp() throws IOException {\n mockWebServer.enqueue(new MockResponse(200, Headers.of(), \"Hello, Maven!\"));\n mockWebServer.start();\n\n new SampleHttpClient().makeCall(mockWebServer.url(\"/\"));\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/Dispatcher.kt","line":21,"symbol":"Dispatcher","kind":"class","lang":"kotlin","doc":"Handler for mock server requests.","code":"public abstract class Dispatcher : Closeable {\n /**\n * Returns a response to satisfy `request`. This method may block (for instance, to wait on\n * a CountdownLatch).\n */\n @Throws(InterruptedException::class)\n public abstract fun dispatch(request: RecordedRequest): MockResponse\n\n /**\n * Returns an early guess of the next response, used for policy on how an incoming request should\n * be received. The default implementation returns an empty response. Mischievous implementations\n * can return other values to test HTTP edge cases, such as unhappy socket policies or throttled\n * request bodies.\n */\n public open fun peek(): MockResponse = MockResponse()\n\n /**\n * Release any resources held by this dispatcher. Any requests that are currently being dispatched\n * should return immediately. Responses returned after shutdown will not be transmitted: their\n * socket connections have already been closed.\n */\n public open override fun close() {}\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/Dispatcher.kt","line":26,"symbol":"dispatch","kind":"function","lang":"kotlin","doc":"Returns a response to satisfy `request`. This method may block (for instance, to wait on a CountdownLatch).","code":"@Throws(InterruptedException::class)\n public abstract fun dispatch(request: RecordedRequest): MockResponse"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/Dispatcher.kt","line":35,"symbol":"peek","kind":"function","lang":"kotlin","doc":"Returns an early guess of the next response, used for policy on how an incoming request should be received. The default implementation returns an empty response. Mischievous implementations can return other values to test HTTP edge cases, such as unhappy socket policies or throttled request bodies.","code":"public open fun peek(): MockResponse = MockResponse()"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/Dispatcher.kt","line":42,"symbol":"close","kind":"function","lang":"kotlin","doc":"Release any resources held by this dispatcher. Any requests that are currently being dispatched should return immediately. Responses returned after shutdown will not be transmitted: their socket connections have already been closed.","code":"public open override fun close() {}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":37,"symbol":"MockResponse","kind":"class","lang":"kotlin","doc":"A scripted response to be replayed by the mock web server.","code":"public class MockResponse {\n /** Returns the HTTP response line, such as \"HTTP/1.1 200 OK\". */\n public val status: String\n\n public val code: Int\n get() {\n val statusParts = status.split(' ', limit = 3)\n require(statusParts.size >= 2) { \"Unexpected status: $status\" }\n return statusParts[1].toInt()\n }\n\n public val message: String\n get() {\n val statusParts = status.split(' ', limit = 3)\n require(statusParts.size >= 2) { \"Unexpected status: $status\" }\n return statusParts[2]\n }\n\n public val headers: Headers\n public val trailers: Headers\n\n // At most one of (body,webSocketListener,streamHandler) is non-null.\n public val body: MockResponseBody?\n public val webSocketListener: WebSocketListener?\n public val socketHandler: SocketHandler?\n\n public val inTunnel: Boolean\n public val informationalResponses: List\n\n public val throttleBytesPerPeriod: Long\n public val throttlePeriodNanos: Long\n\n public val failHandshake: Boolean\n public val onRequestStart: SocketEffect?\n public val doNotReadRequestBody: Boolean\n public val onRequestBody: SocketEffect?\n public val onResponseStart: SocketEffect?\n public val onResponseBody: So"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":124,"symbol":"newBuilder","kind":"function","lang":"kotlin","code":"public fun newBuilder(): Builder = Builder(this)"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":126,"symbol":"toString","kind":"function","lang":"kotlin","code":"public override fun toString(): String = status"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":128,"symbol":"Builder","kind":"class","lang":"kotlin","code":"public class Builder : Cloneable {\n public var inTunnel: Boolean\n private set\n\n private val informationalResponses_: MutableList\n public val informationalResponses: List\n get() = informationalResponses_.toList()\n\n public var status: String\n private set\n\n public var code: Int\n get() {\n val statusParts = status.split(' ', limit = 3)\n require(statusParts.size >= 2) { \"Unexpected status: $status\" }\n return statusParts[1].toInt()\n }\n private set(value) {\n val reason =\n when (value) {\n in 100..199 -> \"Informational\"\n in 200..299 -> \"OK\"\n in 300..399 -> \"Redirection\"\n in 400..499 -> \"Client Error\"\n in 500..599 -> \"Server Error\"\n else -> \"Mock Response\"\n }\n status = \"HTTP/1.1 $value $reason\"\n }\n\n private var headers_: Headers.Builder\n public val headers: Headers\n get() = headers_.build()\n\n private var trailers_: Headers.Builder\n public val trailers: Headers\n get() = trailers_.build()\n\n // At most one of (body,webSocketListener,socketHandler) is non-null.\n private var b"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":288,"symbol":"code","kind":"function","lang":"kotlin","code":"public fun code(code: Int): Builder =\n apply {\n this.code = code\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":294,"symbol":"status","kind":"function","lang":"kotlin","doc":"Sets the status and returns this.","code":"public fun status(status: String): Builder =\n apply {\n this.status = status\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":303,"symbol":"clearHeaders","kind":"function","lang":"kotlin","doc":"Removes all HTTP headers including any \"Content-Length\" and \"Transfer-encoding\" headers that were added by default.","code":"public fun clearHeaders(): Builder =\n apply {\n headers_ = Headers.Builder()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":312,"symbol":"addHeader","kind":"function","lang":"kotlin","doc":"Adds [header] as an HTTP header. For well-formed HTTP [header] should contain a name followed by a colon and a value.","code":"public fun addHeader(header: String): Builder =\n apply {\n headers_.add(header)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":321,"symbol":"addHeader","kind":"function","lang":"kotlin","doc":"Adds a new header with the name and value. This may be used to add multiple headers with the same name.","code":"public fun addHeader(\n name: String,\n value: Any,\n ): Builder =\n apply {\n headers_.add(name, value.toString())\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":334,"symbol":"addHeaderLenient","kind":"function","lang":"kotlin","doc":"Adds a new header with the name and value. This may be used to add multiple headers with the same name. Unlike [addHeader] this does not validate the name and value.","code":"public fun addHeaderLenient(\n name: String,\n value: Any,\n ): Builder =\n apply {\n addHeaderLenient(headers_, name, value.toString())\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":343,"symbol":"setHeader","kind":"function","lang":"kotlin","doc":"Removes all headers named [name], then adds a new header with the name and value.","code":"public fun setHeader(\n name: String,\n value: Any,\n ): Builder =\n apply {\n removeHeader(name)\n addHeader(name, value)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":353,"symbol":"removeHeader","kind":"function","lang":"kotlin","doc":"Removes all headers named [name].","code":"public fun removeHeader(name: String): Builder =\n apply {\n headers_.removeAll(name)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":358,"symbol":"body","kind":"function","lang":"kotlin","code":"public fun body(body: Buffer): Builder = body(body.toMockResponseBody())"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":360,"symbol":"body","kind":"function","lang":"kotlin","code":"public fun body(body: MockResponseBody): Builder =\n apply {\n setHeader(\"Content-Length\", body.contentLength)\n this.body = body\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":367,"symbol":"body","kind":"function","lang":"kotlin","doc":"Sets the response body to the UTF-8 encoded bytes of [body].","code":"public fun body(body: String): Builder = body(Buffer().writeUtf8(body))"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":369,"symbol":"socketHandler","kind":"function","lang":"kotlin","code":"public fun socketHandler(socketHandler: SocketHandler): Builder =\n apply {\n this.socketHandler = socketHandler\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":377,"symbol":"chunkedBody","kind":"function","lang":"kotlin","doc":"Sets the response body to [body], chunked every [maxChunkSize] bytes.","code":"public fun chunkedBody(\n body: Buffer,\n maxChunkSize: Int = Int.MAX_VALUE,\n ): Builder =\n apply {\n removeHeader(\"Content-Length\")\n headers_.add(\"Transfer-encoding: chunked\")\n\n val bytesOut = Buffer()\n while (!body.exhausted()) {\n val chunkSize = minOf(body.size, maxChunkSize.toLong())\n bytesOut.writeHexadecimalUnsignedLong(chunkSize)\n bytesOut.writeUtf8(\"\\r\\n\")\n bytesOut.write(body, chunkSize)\n bytesOut.writeUtf8(\"\\r\\n\")\n }\n bytesOut.writeUtf8(\"0\\r\\n\") // Last chunk. Trailers follow!\n this.body = bytesOut.toMockResponseBody()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":401,"symbol":"chunkedBody","kind":"function","lang":"kotlin","doc":"Sets the response body to the UTF-8 encoded bytes of [body], chunked every [maxChunkSize] bytes.","code":"public fun chunkedBody(\n body: String,\n maxChunkSize: Int = Int.MAX_VALUE,\n ): Builder = chunkedBody(Buffer().writeUtf8(body), maxChunkSize)"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":407,"symbol":"headers","kind":"function","lang":"kotlin","doc":"Sets the headers and returns this.","code":"public fun headers(headers: Headers): Builder =\n apply {\n this.headers_ = headers.newBuilder()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":413,"symbol":"trailers","kind":"function","lang":"kotlin","doc":"Sets the trailers and returns this.","code":"public fun trailers(trailers: Headers): Builder =\n apply {\n this.trailers_ = trailers.newBuilder()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":419,"symbol":"failHandshake","kind":"function","lang":"kotlin","doc":"Don't trust the client during the SSL handshake.","code":"public fun failHandshake(): Builder =\n apply {\n failHandshake = true\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":425,"symbol":"onRequestStart","kind":"function","lang":"kotlin","doc":"Trigger [socketEffect] before the request headers are read.","code":"public fun onRequestStart(socketEffect: SocketEffect?): Builder =\n apply {\n this.onRequestStart = socketEffect\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":435,"symbol":"doNotReadRequestBody","kind":"function","lang":"kotlin","doc":"Process the response without even attempting to reading the request body. For HTTP/2 this will close the response stream after the response body or trailers. For HTTP/1 this will close the socket after the response body or trailers.","code":"public fun doNotReadRequestBody(): Builder =\n apply {\n doNotReadRequestBody = true\n onResponseEnd = CloseStream(ErrorCode.NO_ERROR.httpCode)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":442,"symbol":"onRequestBody","kind":"function","lang":"kotlin","doc":"Trigger [socketEffect] while reading the request body.","code":"public fun onRequestBody(socketEffect: SocketEffect?): Builder =\n apply {\n this.onRequestBody = socketEffect\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":448,"symbol":"onResponseStart","kind":"function","lang":"kotlin","doc":"Trigger [socketEffect] before the response headers are sent.","code":"public fun onResponseStart(socketEffect: SocketEffect?): Builder =\n apply {\n this.onResponseStart = socketEffect\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":454,"symbol":"onResponseBody","kind":"function","lang":"kotlin","doc":"Trigger [socketEffect] while writing the response body.","code":"public fun onResponseBody(socketEffect: SocketEffect?): Builder =\n apply {\n this.onResponseBody = socketEffect\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":460,"symbol":"onResponseEnd","kind":"function","lang":"kotlin","doc":"Trigger [socketEffect] after writing the response body.","code":"public fun onResponseEnd(socketEffect: SocketEffect?): Builder =\n apply {\n this.onResponseEnd = socketEffect\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":465,"symbol":"shutdownServer","kind":"function","lang":"kotlin","code":"public fun shutdownServer(shutdownServer: Boolean): Builder =\n apply {\n this.shutdownServer = shutdownServer\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":474,"symbol":"throttleBody","kind":"function","lang":"kotlin","doc":"Throttles the request reader and response writer to sleep for the given period after each series of [bytesPerPeriod] bytes are transferred. Use this to simulate network behavior.","code":"public fun throttleBody(\n bytesPerPeriod: Long,\n period: Long,\n unit: TimeUnit,\n ): Builder =\n apply {\n throttleBytesPerPeriod = bytesPerPeriod\n throttlePeriodNanos = unit.toNanos(period)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":484,"symbol":"headersDelay","kind":"function","lang":"kotlin","code":"public fun headersDelay(\n delay: Long,\n unit: TimeUnit,\n ): Builder =\n apply {\n headersDelayNanos = unit.toNanos(delay)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":496,"symbol":"bodyDelay","kind":"function","lang":"kotlin","doc":"Set the delayed time of the response body to [delay]. This applies to the response body only; response headers are not affected.","code":"public fun bodyDelay(\n delay: Long,\n unit: TimeUnit,\n ): Builder =\n apply {\n bodyDelayNanos = unit.toNanos(delay)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":504,"symbol":"trailersDelay","kind":"function","lang":"kotlin","code":"public fun trailersDelay(\n delay: Long,\n unit: TimeUnit,\n ): Builder =\n apply {\n trailersDelayNanos = unit.toNanos(delay)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":516,"symbol":"addPush","kind":"function","lang":"kotlin","doc":"When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this attaches a pushed stream to this response.","code":"public fun addPush(promise: PushPromise): Builder =\n apply {\n this.pushPromises_ += promise\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":525,"symbol":"settings","kind":"function","lang":"kotlin","doc":"When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this pushes [settings] before writing the response.","code":"public fun settings(settings: Settings): Builder =\n apply {\n this.settings_.clear()\n this.settings_.merge(settings)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":535,"symbol":"webSocketUpgrade","kind":"function","lang":"kotlin","doc":"Attempts to perform a web socket upgrade on the connection. This will overwrite any previously set status, body, or streamHandler.","code":"public fun webSocketUpgrade(listener: WebSocketListener): Builder =\n apply {\n status = \"HTTP/1.1 101 Switching Protocols\"\n setHeader(\"Connection\", \"Upgrade\")\n setHeader(\"Upgrade\", \"websocket\")\n webSocketListener = listener\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":550,"symbol":"inTunnel","kind":"function","lang":"kotlin","doc":"Configures this response to be served as a response to an HTTP CONNECT request, either for doing HTTPS through an HTTP proxy, or HTTP/2 prior knowledge through an HTTP proxy. When a new connection is received, all in-tunnel responses are served before the connection is upgraded to HTTPS or HTTP/2.","code":"public fun inTunnel(): Builder =\n apply {\n removeHeader(\"Content-Length\")\n inTunnel = true\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":561,"symbol":"addInformationalResponse","kind":"function","lang":"kotlin","doc":"Adds an HTTP 1xx response to precede this response. Note that this response's [headers delay][headersDelay] applies after this response is transmitted. Set a headers delay on that response to delay its transmission.","code":"public fun addInformationalResponse(response: MockResponse): Builder =\n apply {\n informationalResponses_ += response\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":566,"symbol":"add100Continue","kind":"function","lang":"kotlin","code":"public fun add100Continue(): Builder =\n apply {\n addInformationalResponse(MockResponse(code = 100))\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":571,"symbol":"clone","kind":"function","lang":"kotlin","code":"public override fun clone(): Builder = build().newBuilder()"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt","line":573,"symbol":"build","kind":"function","lang":"kotlin","code":"public fun build(): MockResponse = MockResponse(this)"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponseBody.kt","line":28,"symbol":"MockResponseBody","kind":"interface","lang":"kotlin","doc":"The body of a [MockResponse]. Unlike [okhttp3.ResponseBody], this interface is designed to be implemented by writers and not called by readers.","code":"public interface MockResponseBody {\n /** The length of this response in bytes, or -1 if unknown. */\n public val contentLength: Long\n\n @Throws(IOException::class)\n public fun writeTo(sink: BufferedSink)\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockResponseBody.kt","line":32,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n public fun writeTo(sink: BufferedSink)"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":97,"symbol":"MockWebServer","kind":"class","lang":"kotlin","doc":"A scriptable web server. Callers supply canned responses and the server replays them upon request in sequence.","code":"public class MockWebServer : Closeable {\n private val taskRunnerBackend =\n TaskRunner.RealBackend(\n threadFactory(\"MockWebServer TaskRunner\", daemon = false),\n )\n private val taskRunner = TaskRunner(taskRunnerBackend)\n private val requestQueue = LinkedBlockingQueue()\n private val openClientSockets =\n Collections.newSetFromMap(ConcurrentHashMap())\n private val openConnections =\n Collections.newSetFromMap(ConcurrentHashMap())\n\n private val atomicRequestCount = AtomicInteger()\n\n private var serverSocketFactory_: ServerSocketFactory? = null\n private var serverSocket: ServerSocket? = null\n\n /** Non-null after [start]. */\n private var socketAddress_: InetSocketAddress? = null\n\n private var sslSocketFactory: SSLSocketFactory? = null\n private var clientAuth = CLIENT_AUTH_NONE\n\n private var closed: Boolean = false\n\n /**\n * The number of HTTP requests received thus far by this server. This may exceed the number of\n * HTTP connections when connection reuse is in practice.\n */\n public val requestCount: Int\n get() = atomicRequestCount.get()\n\n /** The number of bytes of the POST body to keep in "} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":196,"symbol":"url","kind":"function","lang":"kotlin","doc":"Returns a URL for connecting to this server. @param path the request path, such as \"/\".","code":"public fun url(path: String): HttpUrl =\n HttpUrl\n .Builder()\n .scheme(if (sslSocketFactory != null) \"https\" else \"http\")\n .host(hostName)\n .port(port)\n .build()\n .resolve(path)!!"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":208,"symbol":"useHttps","kind":"function","lang":"kotlin","doc":"Serve requests with HTTPS rather than otherwise.","code":"public fun useHttps(sslSocketFactory: SSLSocketFactory) {\n this.sslSocketFactory = sslSocketFactory\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":217,"symbol":"noClientAuth","kind":"function","lang":"kotlin","doc":"Configure the server to not perform SSL authentication of the client. This leaves authentication to another layer such as in an HTTP cookie or header. This is the default and most common configuration.","code":"public fun noClientAuth() {\n this.clientAuth = CLIENT_AUTH_NONE\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":228,"symbol":"requestClientAuth","kind":"function","lang":"kotlin","doc":"Configure the server to [want client auth][SSLSocket.setWantClientAuth]. If the client presents a certificate that is [trusted][TrustManager] the handshake will proceed normally. The connection will also proceed normally if the client presents no certificate at all! But if the client presents an untrusted certificate the handshake will fail and no connection will be established.","code":"public fun requestClientAuth() {\n this.clientAuth = CLIENT_AUTH_REQUESTED\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":238,"symbol":"requireClientAuth","kind":"function","lang":"kotlin","doc":"Configure the server to [need client auth][SSLSocket.setNeedClientAuth]. If the client presents a certificate that is [trusted][TrustManager] the handshake will proceed normally. If the client presents an untrusted certificate or no certificate at all the handshake will fail and no connection will be established.","code":"public fun requireClientAuth() {\n this.clientAuth = CLIENT_AUTH_REQUIRED\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":249,"symbol":"takeRequest","kind":"function","lang":"kotlin","doc":"Awaits the next HTTP request, removes it, and returns it. Callers should use this to verify the request was sent as intended. This method will block until the request is available, possibly forever. @return the head of the request queue","code":"@Throws(InterruptedException::class)\n public fun takeRequest(): RecordedRequest = requestQueue.take()"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":261,"symbol":"takeRequest","kind":"function","lang":"kotlin","doc":"given time. @param timeout how long to wait before giving up, in units of [unit] @param unit a [TimeUnit] determining how to interpret the [timeout] parameter @return the head of the request queue","code":"@Throws(InterruptedException::class)\n public fun takeRequest(\n timeout: Long,\n unit: TimeUnit,\n ): RecordedRequest? = requestQueue.poll(timeout, unit)"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":275,"symbol":"enqueue","kind":"function","lang":"kotlin","doc":"served by the first enqueued response; the second request by the second enqueued response; and so on. @throws ClassCastException if the default dispatcher has been replaced with [setDispatcher][dispatcher].","code":"public fun enqueue(response: MockResponse) {\n (dispatcher as QueueDispatcher).enqueue(response)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":285,"symbol":"start","kind":"function","lang":"kotlin","doc":"Starts the server on the loopback interface for the given port. @param port the port to listen to, or 0 for any available port. Automated tests should always use port 0 to avoid flakiness when a specific port is unavailable.","code":"@Throws(IOException::class)\n @JvmOverloads\n public fun start(port: Int = 0) {\n start(InetAddress.getByName(\"localhost\"), port)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":298,"symbol":"start","kind":"function","lang":"kotlin","doc":"Starts the server on the given address and port. @param inetAddress the address to create the server socket on @param port the port to listen to, or 0 for any available port. Automated tests should always use port 0 to avoid flakiness when a specific port is unavailable.","code":"@Throws(IOException::class)\n public fun start(\n inetAddress: InetAddress,\n port: Int,\n ) {\n start(InetSocketAddress(inetAddress, port))\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":311,"symbol":"start","kind":"function","lang":"kotlin","doc":"Starts the server and binds to the given socket address. @param socketAddress the socket address to bind the server on","code":"@Synchronized\n @Throws(IOException::class)\n private fun start(socketAddress: InetSocketAddress) {\n check(!closed) { \"close() already called\" }\n\n val alreadyStartedAddress = socketAddress_\n if (alreadyStartedAddress != null) {\n check(socketAddress.address == alreadyStartedAddress.address) {\n \"unexpected address\"\n }\n check(socketAddress.port == 0 || socketAddress.port == alreadyStartedAddress.port) {\n \"unexpected port\"\n }\n return // Already started.\n }\n\n var boundSocketAddress = socketAddress\n try {\n val serverSocketFactory =\n serverSocketFactory_\n ?: (Platform.get().serverSocketFactory.also { this.serverSocketFactory_ = it })\n\n val serverSocket =\n serverSocketFactory\n .createServerSocket()!!\n .also { this.serverSocket = it }\n\n // Reuse if the user specified a port\n serverSocket.reuseAddress = socketAddress.port != 0\n serverSocket.bind(socketAddress, 50)\n\n // If the local port was 0, it'll be non-zero after bind().\n boundSocketAddress = InetSocketAddress(boundSocketAddress.address, serverSocket.localPort)\n } finally {\n this.socketAddress_ = bo"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":374,"symbol":"acceptConnections","kind":"function","lang":"kotlin","code":"@Throws(Exception::class)\n private fun acceptConnections() {\n var nextConnectionIndex = 0\n while (true) {\n val socket: Socket\n try {\n socket = serverSocket!!.accept()\n } catch (e: SocketException) {\n logger.fine(\"${this@MockWebServer} done accepting connections: ${e.message}\")\n return\n }\n\n val peek = dispatcher.peek()\n if (peek.onRequestStart is CloseSocket) {\n dispatchBookkeepingRequest(\n connectionIndex = nextConnectionIndex++,\n exchangeIndex = 0,\n socket = MockWebServerSocket(socket),\n )\n socket.close()\n } else {\n openClientSockets.add(socket)\n serveConnection(nextConnectionIndex++, socket, peek)\n }\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":401,"symbol":"close","kind":"function","lang":"kotlin","code":"public override fun close() {\n if (closed) return\n closed = true\n\n if (!started) return // Nothing to shut down.\n val serverSocket = this.serverSocket ?: return // If this is null, start() must have failed.\n\n // Cause acceptConnections() to break out.\n serverSocket.closeQuietly()\n\n // Await shutdown.\n for (queue in taskRunner.activeQueues()) {\n if (!queue.idleLatch().await(5, TimeUnit.SECONDS)) {\n throw AssertionError(\"Gave up waiting for queue to shut down\")\n }\n }\n taskRunnerBackend.shutdown()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":420,"symbol":"serveConnection","kind":"function","lang":"kotlin","code":"private fun serveConnection(\n connectionIndex: Int,\n raw: Socket,\n firstExchangePeek: MockResponse,\n ) {\n taskRunner.newQueue().execute(\"MockWebServer ${raw.remoteSocketAddress}\", cancelable = false) {\n try {\n SocketHandler(connectionIndex, raw, firstExchangePeek).handle()\n } catch (e: IOException) {\n logger.fine(\"$this connection from ${raw.inetAddress} failed: $e\")\n } catch (e: Exception) {\n logger.log(Level.SEVERE, \"$this connection from ${raw.inetAddress} crashed\", e)\n }\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":436,"symbol":"SocketHandler","kind":"class","lang":"kotlin","code":"internal inner class SocketHandler(\n private val connectionIndex: Int,\n private val raw: Socket,\n private val firstExchangePeek: MockResponse,\n ) {\n private var nextExchangeIndex = 0\n\n @Throws(Exception::class)\n fun handle() {\n if (!processTunnelRequests()) return\n\n val protocol: Protocol\n val socket: MockWebServerSocket\n when {\n sslSocketFactory != null -> {\n if (firstExchangePeek.failHandshake) {\n dispatchBookkeepingRequest(\n connectionIndex = connectionIndex,\n exchangeIndex = nextExchangeIndex++,\n socket = MockWebServerSocket(raw),\n )\n processHandshakeFailure(raw)\n return\n }\n val sslSocket =\n sslSocketFactory!!.createSocket(\n raw,\n raw.inetAddress.hostAddress,\n raw.port,\n true,\n ) as SSLSocket\n sslSocket.useClientMode = false\n if (clientAuth == CLIENT_AUTH_REQUIRED) {\n sslSocket.needClientAuth = true\n } else if (clientAuth == CLIENT_AUTH_REQUESTED) {\n sslSocket.wantClientAuth = true\n }\n "} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":443,"symbol":"handle","kind":"function","lang":"kotlin","code":"@Throws(Exception::class)\n fun handle() {\n if (!processTunnelRequests()) return\n\n val protocol: Protocol\n val socket: MockWebServerSocket\n when {\n sslSocketFactory != null -> {\n if (firstExchangePeek.failHandshake) {\n dispatchBookkeepingRequest(\n connectionIndex = connectionIndex,\n exchangeIndex = nextExchangeIndex++,\n socket = MockWebServerSocket(raw),\n )\n processHandshakeFailure(raw)\n return\n }\n val sslSocket =\n sslSocketFactory!!.createSocket(\n raw,\n raw.inetAddress.hostAddress,\n raw.port,\n true,\n ) as SSLSocket\n sslSocket.useClientMode = false\n if (clientAuth == CLIENT_AUTH_REQUIRED) {\n sslSocket.needClientAuth = true\n } else if (clientAuth == CLIENT_AUTH_REQUESTED) {\n sslSocket.wantClientAuth = true\n }\n openClientSockets.add(sslSocket)\n\n if (protocolNegotiationEnabled) {\n Platform.get().configureTlsExtensions(\n sslSocket = sslSocket,\n hostname = null,\n "} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":555,"symbol":"processTunnelRequests","kind":"function","lang":"kotlin","doc":"Respond to `CONNECT` requests until a non-tunnel response is peeked. Returns true if further calls should be attempted on the socket.","code":"@Throws(IOException::class, InterruptedException::class)\n private fun processTunnelRequests(): Boolean {\n if (!dispatcher.peek().inTunnel) return true // No tunnel requests.\n\n val socket = MockWebServerSocket(raw)\n while (true) {\n val socketStillGood = processOneRequest(socket)\n\n // Clean up after the last exchange on a socket.\n if (!socketStillGood) {\n raw.close()\n openClientSockets.remove(raw)\n return false\n }\n\n if (!dispatcher.peek().inTunnel) return true // No more tunnel requests.\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":578,"symbol":"processOneRequest","kind":"function","lang":"kotlin","doc":"Reads a request and writes its response. Returns true if further calls should be attempted on the socket.","code":"@Throws(IOException::class, InterruptedException::class)\n private fun processOneRequest(socket: MockWebServerSocket): Boolean {\n if (socket.source.exhausted()) {\n return false // No more requests on this socket.\n }\n\n val request =\n readRequest(\n socket = socket,\n connectionIndex = connectionIndex,\n exchangeIndex = nextExchangeIndex++,\n )\n atomicRequestCount.incrementAndGet()\n requestQueue.add(request)\n\n if (request.failure != null) {\n return false // Nothing to respond to.\n }\n\n val response = dispatcher.dispatch(request)\n\n try {\n if (handleSocketEffect(response.onResponseStart, socket)) {\n return false\n }\n\n var reuseSocket = true\n val requestWantsSocket = \"Upgrade\".equals(request.headers[\"Connection\"], ignoreCase = true)\n val requestWantsWebSocket =\n requestWantsSocket &&\n \"websocket\".equals(request.headers[\"Upgrade\"], ignoreCase = true)\n val responseWantsSocket = response.socketHandler != null\n val responseWantsWebSocket = response.webSocketListener != null\n if (requestWantsWebSocket && responseW"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":641,"symbol":"processHandshakeFailure","kind":"function","lang":"kotlin","code":"@Throws(Exception::class)\n private fun processHandshakeFailure(raw: Socket) {\n val context = SSLContext.getInstance(\"TLS\")\n context.init(null, arrayOf(UNTRUSTED_TRUST_MANAGER), SecureRandom())\n val sslSocketFactory = context.socketFactory\n val socket =\n sslSocketFactory.createSocket(\n raw,\n raw.inetAddress.hostAddress,\n raw.port,\n true,\n ) as SSLSocket\n try {\n socket.startHandshake() // we're testing a handshake failure\n throw AssertionError()\n } catch (_: IOException) {\n }\n socket.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":661,"symbol":"dispatchBookkeepingRequest","kind":"function","lang":"kotlin","code":"@Throws(InterruptedException::class)\n private fun dispatchBookkeepingRequest(\n connectionIndex: Int,\n exchangeIndex: Int,\n socket: MockWebServerSocket,\n requestLine: RequestLine = DEFAULT_REQUEST_LINE_HTTP_1,\n ) {\n val request =\n RecordedRequest(\n requestLine = requestLine,\n headers = headersOf(),\n chunkSizes = null,\n bodySize = 0L,\n body = null,\n connectionIndex = connectionIndex,\n exchangeIndex = exchangeIndex,\n socket = socket,\n )\n atomicRequestCount.incrementAndGet()\n requestQueue.add(request)\n dispatcher.dispatch(request)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":685,"symbol":"readRequest","kind":"function","lang":"kotlin","doc":"@param exchangeIndex the index of this request on this connection.","code":"@Throws(IOException::class)\n private fun readRequest(\n socket: MockWebServerSocket,\n connectionIndex: Int,\n exchangeIndex: Int,\n ): RecordedRequest {\n var request: RequestLine = DEFAULT_REQUEST_LINE_HTTP_1\n val headers = Headers.Builder()\n var contentLength = -1L\n var chunked = false\n var hasBody = false\n val requestBody = TruncatingBuffer(bodyLimit)\n var chunkSizes: List? = null\n var failure: IOException? = null\n\n try {\n val requestLineString = socket.source.readUtf8LineStrict()\n if (requestLineString.isEmpty()) {\n throw ProtocolException(\"no request because the stream is exhausted\")\n }\n request = decodeRequestLine(requestLineString)\n\n while (true) {\n val header = socket.source.readUtf8LineStrict()\n if (header.isEmpty()) {\n break\n }\n addHeaderLenient(headers, header)\n val lowercaseHeader = header.lowercase(Locale.US)\n if (contentLength == -1L && lowercaseHeader.startsWith(\"content-length:\")) {\n contentLength = header.substring(15).trim().toLong()\n }\n if (lowercaseHeader.startsWith(\"transfer-encoding:\") &&\n lowercaseHeader.sub"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":797,"symbol":"handleWebSocketUpgrade","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun handleWebSocketUpgrade(\n socket: MockWebServerSocket,\n request: RecordedRequest,\n response: MockResponse,\n ) {\n val key = request.headers[\"Sec-WebSocket-Key\"]\n val webSocketResponse =\n response\n .newBuilder()\n .setHeader(\"Sec-WebSocket-Accept\", WebSocketProtocol.acceptHeader(key!!))\n .build()\n writeHttpResponse(socket, webSocketResponse)\n\n // Adapt the request and response into our Request and Response domain model.\n val scheme = if (request.handshake != null) \"https\" else \"http\"\n val authority = request.headers[\"Host\"] // Has host and port.\n val fancyRequest =\n Request\n .Builder()\n .url(\"$scheme://$authority/\")\n .headers(request.headers)\n .build()\n val fancyResponse =\n Response\n .Builder()\n .code(webSocketResponse.code)\n .message(webSocketResponse.message)\n .headers(webSocketResponse.headers)\n .request(fancyRequest)\n .protocol(Protocol.HTTP_1_1)\n .build()\n\n val webSocket =\n RealWebSocket(\n taskRunner = taskRunner,\n originalRequest = fancyRequest,\n listener = webSocke"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":856,"symbol":"writeHttpResponse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun writeHttpResponse(\n socket: MockWebServerSocket,\n response: MockResponse,\n ) {\n socket.sleepWhileOpen(response.headersDelayNanos)\n socket.sink.writeUtf8(response.status)\n socket.sink.writeUtf8(\"\\r\\n\")\n\n writeHeaders(socket.sink, response.headers)\n\n if (response.socketHandler != null) {\n response.socketHandler.handle(socket)\n return\n }\n\n val body = response.body ?: return\n socket.sleepWhileOpen(response.bodyDelayNanos)\n val responseBodySink =\n socket.sink\n .withThrottlingAndSocketEffect(\n policy = response,\n socketEffect = response.onResponseBody,\n expectedByteCount = body.contentLength,\n socket = socket,\n ).buffer()\n body.writeTo(responseBodySink)\n responseBodySink.flush()\n\n socket.sleepWhileOpen(response.trailersDelayNanos)\n if (\"chunked\".equals(response.headers[\"Transfer-Encoding\"], ignoreCase = true)) {\n writeHeaders(socket.sink, response.trailers)\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":891,"symbol":"writeHeaders","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun writeHeaders(\n sink: BufferedSink,\n headers: Headers,\n ) {\n for ((name, value) in headers) {\n sink.writeUtf8(name)\n sink.writeUtf8(\": \")\n sink.writeUtf8(value)\n sink.writeUtf8(\"\\r\\n\")\n }\n sink.writeUtf8(\"\\r\\n\")\n sink.flush()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":907,"symbol":"withThrottlingAndSocketEffect","kind":"function","lang":"kotlin","doc":"Returns a sink that applies throttling and disconnecting.","code":"private fun Sink.withThrottlingAndSocketEffect(\n policy: MockResponse,\n socketEffect: SocketEffect?,\n expectedByteCount: Long,\n socket: MockWebServerSocket,\n stream: Http2Stream? = null,\n ): Sink {\n var result: Sink = this\n\n if (policy.throttlePeriodNanos > 0L) {\n result =\n ThrottledSink(\n socket = socket,\n delegate = result,\n bytesPerPeriod = policy.throttleBytesPerPeriod,\n periodDelayNanos = policy.throttlePeriodNanos,\n )\n }\n\n if (socketEffect != null) {\n val halfwayByteCount =\n when {\n expectedByteCount != -1L -> expectedByteCount / 2\n else -> 0L\n }\n result =\n TriggerSink(\n delegate = result,\n triggerByteCount = halfwayByteCount,\n ) {\n result.flush()\n handleSocketEffect(socketEffect, socket, stream)\n }\n }\n\n return result\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":946,"symbol":"handleSocketEffect","kind":"function","lang":"kotlin","doc":"Returns true if processing this exchange is complete.","code":"private fun handleSocketEffect(\n effect: SocketEffect?,\n socket: MockWebServerSocket,\n stream: Http2Stream? = null,\n ): Boolean {\n if (effect == null) return false\n\n when (effect) {\n is CloseStream -> {\n if (stream != null) {\n stream.close(ErrorCode.fromHttp2(effect.http2ErrorCode)!!, null)\n } else {\n socket.close()\n }\n }\n\n ShutdownConnection -> {\n if (stream != null) {\n stream.connection.shutdown(ErrorCode.NO_ERROR)\n } else {\n socket.close()\n }\n }\n\n is CloseSocket -> {\n if (effect.shutdownInput) socket.shutdownInput()\n if (effect.shutdownOutput) socket.shutdownOutput()\n if (effect.closeSocket) socket.close()\n }\n\n Stall -> {\n // Sleep until the socket is closed.\n socket.sleepWhileOpen(TimeUnit.MINUTES.toNanos(60))\n error(\"expected timeout\")\n }\n }\n\n return true\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":986,"symbol":"readEmptyLine","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readEmptyLine(source: BufferedSource) {\n val line = source.readUtf8LineStrict()\n check(line.isEmpty()) { \"Expected empty but was: $line\" }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":992,"symbol":"toString","kind":"function","lang":"kotlin","code":"public override fun toString(): String {\n val socketAddress = socketAddress_\n return when {\n closed -> \"MockWebServer{closed}\"\n socketAddress != null -> \"MockWebServer{port=${socketAddress.port}}\"\n else -> \"MockWebServer{new}\"\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1002,"symbol":"TruncatingBuffer","kind":"class","lang":"kotlin","doc":"A buffer wrapper that drops data after [bodyLimit] bytes.","code":"private class TruncatingBuffer(\n private var remainingByteCount: Long,\n ) : Sink {\n val buffer = Buffer()\n var receivedByteCount = 0L\n\n @Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n val toRead = minOf(remainingByteCount, byteCount)\n if (toRead > 0L) {\n source.read(buffer, toRead)\n }\n val toSkip = byteCount - toRead\n if (toSkip > 0L) {\n source.skip(toSkip)\n }\n remainingByteCount -= toRead\n receivedByteCount += byteCount\n }\n\n @Throws(IOException::class)\n override fun flush() {\n }\n\n override fun timeout(): Timeout = Timeout.NONE\n\n @Throws(IOException::class)\n override fun close() {\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1008,"symbol":"write","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n val toRead = minOf(remainingByteCount, byteCount)\n if (toRead > 0L) {\n source.read(buffer, toRead)\n }\n val toSkip = byteCount - toRead\n if (toSkip > 0L) {\n source.skip(toSkip)\n }\n remainingByteCount -= toRead\n receivedByteCount += byteCount\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1025,"symbol":"flush","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun flush() {\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1029,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = Timeout.NONE"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1031,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1037,"symbol":"Http2SocketHandler","kind":"class","lang":"kotlin","doc":"Processes HTTP requests layered over HTTP/2.","code":"private inner class Http2SocketHandler(\n private val connectionIndex: Int,\n private val socket: MockWebServerSocket,\n private val protocol: Protocol,\n ) : Http2Connection.Listener() {\n private val nextExchangeIndex = AtomicInteger()\n\n @Throws(IOException::class)\n override fun onStream(stream: Http2Stream) {\n val peek = dispatcher.peek()\n if (handleSocketEffect(peek.onRequestStart, socket, stream)) {\n dispatchBookkeepingRequest(\n connectionIndex = connectionIndex,\n exchangeIndex = nextExchangeIndex.getAndIncrement(),\n socket = socket,\n requestLine = DEFAULT_REQUEST_LINE_HTTP_2,\n )\n return\n }\n\n val request = readRequest(stream)\n atomicRequestCount.incrementAndGet()\n requestQueue.add(request)\n if (request.failure != null) {\n return // Nothing to respond to.\n }\n\n val response = dispatcher.dispatch(request)\n\n try {\n if (handleSocketEffect(peek.onResponseStart, socket, stream)) {\n return\n }\n\n writeResponse(stream, request, response)\n if (logger.isLoggable(Level.FINE)) {\n logger.fine(\n \"${this@MockWebS"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1044,"symbol":"onStream","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onStream(stream: Http2Stream) {\n val peek = dispatcher.peek()\n if (handleSocketEffect(peek.onRequestStart, socket, stream)) {\n dispatchBookkeepingRequest(\n connectionIndex = connectionIndex,\n exchangeIndex = nextExchangeIndex.getAndIncrement(),\n socket = socket,\n requestLine = DEFAULT_REQUEST_LINE_HTTP_2,\n )\n return\n }\n\n val request = readRequest(stream)\n atomicRequestCount.incrementAndGet()\n requestQueue.add(request)\n if (request.failure != null) {\n return // Nothing to respond to.\n }\n\n val response = dispatcher.dispatch(request)\n\n try {\n if (handleSocketEffect(peek.onResponseStart, socket, stream)) {\n return\n }\n\n writeResponse(stream, request, response)\n if (logger.isLoggable(Level.FINE)) {\n logger.fine(\n \"${this@MockWebServer} received request: $request \" +\n \"and responded: $response protocol is $protocol\",\n )\n }\n\n handleSocketEffect(peek.onResponseEnd, socket, stream)\n } finally {\n if (response.shutdownServer) {\n "} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1087,"symbol":"readRequest","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readRequest(stream: Http2Stream): RecordedRequest {\n val streamHeaders = stream.takeHeaders()\n val httpHeaders = Headers.Builder()\n var method = \"<:method omitted>\"\n var path = \"<:path omitted>\"\n var readBody = true\n for ((name, value) in streamHeaders) {\n if (name == Header.TARGET_METHOD_UTF8) {\n method = value\n } else if (name == Header.TARGET_PATH_UTF8) {\n path = value\n } else if (protocol === Protocol.HTTP_2 || protocol === Protocol.H2_PRIOR_KNOWLEDGE) {\n httpHeaders.add(name, value)\n } else {\n throw IllegalStateException()\n }\n if (name == \"expect\" && value.equals(\"100-continue\", ignoreCase = true)) {\n // Don't read the body unless we've invited the client to send it.\n readBody = false\n }\n }\n val headers = httpHeaders.build()\n\n val peek = dispatcher.peek()\n for (response in peek.informationalResponses) {\n socket.sleepWhileOpen(response.headersDelayNanos)\n stream.writeHeaders(response.toHttp2Headers(), outFinished = false, flushHeaders = true)\n if (response.code =="} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1168,"symbol":"toHttp2Headers","kind":"function","lang":"kotlin","code":"private fun MockResponse.toHttp2Headers(): List
{\n val result = mutableListOf
()\n result += Header(Header.RESPONSE_STATUS, code.toString())\n for ((name, value) in headers) {\n result += Header(name, value)\n }\n return result\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1177,"symbol":"writeResponse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun writeResponse(\n stream: Http2Stream,\n request: RecordedRequest,\n response: MockResponse,\n ) {\n val settings = response.settings\n stream.connection.setSettings(settings)\n\n val bodyDelayNanos = response.bodyDelayNanos\n val trailers = response.trailers\n val body = response.body\n val socketHandler = response.socketHandler\n val outFinished = (\n body == null &&\n response.pushPromises.isEmpty() &&\n socketHandler == null\n )\n val flushHeaders = body == null || bodyDelayNanos != 0L\n require(!outFinished || trailers.size == 0) {\n \"unsupported: no body and non-empty trailers $trailers\"\n }\n\n socket.sleepWhileOpen(response.headersDelayNanos)\n stream.writeHeaders(response.toHttp2Headers(), outFinished, flushHeaders)\n\n if (trailers.size > 0) {\n stream.enqueueTrailers(trailers)\n }\n pushPromises(stream, request, response.pushPromises)\n if (body != null) {\n socket.sleepWhileOpen(bodyDelayNanos)\n val responseBodySink =\n stream\n .sink\n .withThrottlingAndSocketEffect(\n "} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1236,"symbol":"pushPromises","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun pushPromises(\n stream: Http2Stream,\n request: RecordedRequest,\n promises: List,\n ) {\n for (pushPromise in promises) {\n val pushedHeaders = mutableListOf
()\n pushedHeaders.add(Header(Header.TARGET_AUTHORITY, url(pushPromise.path).host))\n pushedHeaders.add(Header(Header.TARGET_METHOD, pushPromise.method))\n pushedHeaders.add(Header(Header.TARGET_PATH, pushPromise.path))\n val pushPromiseHeaders = pushPromise.headers\n for ((name, value) in pushPromiseHeaders) {\n pushedHeaders.add(Header(name, value))\n }\n val requestLine =\n RequestLine(\n method = pushPromise.method,\n target = pushPromise.path,\n version = \"HTTP/2\",\n )\n requestQueue.add(\n RecordedRequest(\n requestLine = requestLine,\n headers = pushPromise.headers,\n chunkSizes = null, // No chunked encoding for HTTP/2.\n bodySize = 0,\n body = null,\n connectionIndex = connectionIndex,\n exchangeIndex = nextExchangeIndex.getAndIncrement(),\n so"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1283,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"@Throws(CertificateException::class)\n override fun checkClientTrusted(\n chain: Array,\n authType: String,\n ) = throw CertificateException()"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1289,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n chain: Array,\n authType: String,\n ) = throw AssertionError()"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/MockWebServer.kt","line":1294,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = throw AssertionError()"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt","line":28,"symbol":"QueueDispatcher","kind":"class","lang":"kotlin","doc":"Default dispatcher that processes a script of responses. Populate the script by calling [enqueue].","code":"public open class QueueDispatcher : Dispatcher() {\n protected val responseQueue: BlockingQueue = LinkedBlockingQueue()\n private var failFastResponse: MockResponse? = null\n\n @Throws(InterruptedException::class)\n override fun dispatch(request: RecordedRequest): MockResponse {\n // To permit interactive/browser testing, ignore requests for favicons.\n val requestLine = request.requestLine\n if (requestLine == \"GET /favicon.ico HTTP/1.1\") {\n logger.info(\"served $requestLine\")\n return MockResponse(code = HttpURLConnection.HTTP_NOT_FOUND)\n }\n\n if (failFastResponse != null && responseQueue.peek() == null) {\n // Fail fast if there's no response queued up.\n return failFastResponse!!\n }\n\n val result = responseQueue.take()\n\n // If take() returned because we're shutting down, then enqueue another dead letter so that any\n // other threads waiting on take() will also return.\n if (result == DEAD_LETTER) responseQueue.add(DEAD_LETTER)\n\n return result\n }\n\n public override fun peek(): MockResponse = responseQueue.peek() ?: failFastResponse ?: super.peek()\n\n public open fun enqueue(response: MockResponse) {\n responseQueue.add(r"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt","line":32,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"@Throws(InterruptedException::class)\n override fun dispatch(request: RecordedRequest): MockResponse {\n // To permit interactive/browser testing, ignore requests for favicons.\n val requestLine = request.requestLine\n if (requestLine == \"GET /favicon.ico HTTP/1.1\") {\n logger.info(\"served $requestLine\")\n return MockResponse(code = HttpURLConnection.HTTP_NOT_FOUND)\n }\n\n if (failFastResponse != null && responseQueue.peek() == null) {\n // Fail fast if there's no response queued up.\n return failFastResponse!!\n }\n\n val result = responseQueue.take()\n\n // If take() returned because we're shutting down, then enqueue another dead letter so that any\n // other threads waiting on take() will also return.\n if (result == DEAD_LETTER) responseQueue.add(DEAD_LETTER)\n\n return result\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt","line":55,"symbol":"peek","kind":"function","lang":"kotlin","code":"public override fun peek(): MockResponse = responseQueue.peek() ?: failFastResponse ?: super.peek()"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt","line":57,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"public open fun enqueue(response: MockResponse) {\n responseQueue.add(response)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt","line":61,"symbol":"clear","kind":"function","lang":"kotlin","code":"public open fun clear() {\n responseQueue.clear()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt","line":65,"symbol":"close","kind":"function","lang":"kotlin","code":"public override fun close() {\n responseQueue.add(DEAD_LETTER)\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt","line":69,"symbol":"setFailFast","kind":"function","lang":"kotlin","code":"public open fun setFailFast(failFast: Boolean) {\n setFailFast(\n failFastResponse =\n when {\n failFast -> MockResponse(code = HttpURLConnection.HTTP_NOT_FOUND)\n else -> null\n },\n )\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/QueueDispatcher.kt","line":79,"symbol":"setFailFast","kind":"function","lang":"kotlin","code":"public open fun setFailFast(failFastResponse: MockResponse?) {\n this.failFastResponse = failFastResponse\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt","line":26,"symbol":"RecordedRequest","kind":"class","lang":"kotlin","doc":"An HTTP request that came into the mock web server.","code":"public class RecordedRequest(\n /**\n * The index of the socket connection that carried this request. If two recorded requests share a\n * connection index, they also shared a socket connection.\n */\n public val connectionIndex: Int,\n /**\n * The index of this exchange on its HTTP connection. A request is uniquely identified by the\n * (connection index, exchange index) pair.\n */\n public val exchangeIndex: Int,\n /**\n * The TLS handshake of the connection that carried this request, or null if the request was\n * received without TLS.\n */\n public val handshake: Handshake?,\n /**\n * Returns the name of the server the client requested via the SNI (Server Name Indication)\n * attribute in the TLS handshake. Unlike the rest of the HTTP exchange, this name is sent in\n * cleartext and may be monitored or blocked by a proxy or other middlebox.\n */\n public val handshakeServerNames: List,\n /** A string like `GET` or `POST`. */\n public val method: String,\n /**\n * The request target from the original HTTP request.\n *\n * For origin-form requests this is a path like `/index.html`, that is combined with the `Host`\n * header to create the request URL.\n "} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/RecordedRequest.kt","line":87,"symbol":"toString","kind":"function","lang":"kotlin","code":"public override fun toString(): String = requestLine"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/SocketEffect.kt","line":21,"symbol":"SocketEffect","kind":"interface","lang":"kotlin","doc":"An adverse action to take on a socket, intended to exercise failure modes in the calling code.","code":"public sealed interface SocketEffect {\n /**\n * Close the TCP socket that carries this request.\n *\n * Using this as [MockResponse.onResponseEnd] is the default for HTTP/1.0.\n */\n public class CloseSocket(\n public val closeSocket: Boolean = true,\n public val shutdownInput: Boolean = false,\n public val shutdownOutput: Boolean = false,\n ) : SocketEffect\n\n /**\n * On HTTP/2, send a [GOAWAY frame](https://tools.ietf.org/html/rfc7540#section-6.8) immediately\n * after the response and will close the connection when the client's socket is exhausted.\n *\n * On HTTP/1 this closes the socket.\n */\n public object ShutdownConnection : SocketEffect\n\n /**\n * On HTTP/2 this will send the error code on the stream.\n *\n * On HTTP/1 this closes the socket.\n */\n public class CloseStream(\n public val http2ErrorCode: Int = 0,\n ) : SocketEffect\n\n /** Stop processing this. */\n public object Stall : SocketEffect\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/SocketEffect.kt","line":39,"symbol":"ShutdownConnection","kind":"object","lang":"kotlin","doc":"On HTTP/2, send a [GOAWAY frame](https://tools.ietf.org/html/rfc7540#section-6.8) immediately after the response and will close the connection when the client's socket is exhausted. On HTTP/1 this closes the socket.","code":"public object ShutdownConnection : SocketEffect"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/SocketEffect.kt","line":51,"symbol":"Stall","kind":"object","lang":"kotlin","doc":"Stop processing this.","code":"public object Stall : SocketEffect"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/SocketHandler.kt","line":26,"symbol":"SocketHandler","kind":"interface","lang":"kotlin","doc":"Handles a call's request and response streams directly. Use this instead of [MockResponseBody] to begin sending response data before all request data has been received. See [okhttp3.RequestBody.isDuplex].","code":"public interface SocketHandler {\n public fun handle(socket: Socket)\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/SocketHandler.kt","line":27,"symbol":"handle","kind":"function","lang":"kotlin","code":"public fun handle(socket: Socket)"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/BufferMockResponseBody.kt","line":25,"symbol":"toMockResponseBody","kind":"function","lang":"kotlin","code":"internal fun Buffer.toMockResponseBody(): MockResponseBody {\n val defensiveCopy = clone()\n return BufferMockResponseBody(defensiveCopy)\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/BufferMockResponseBody.kt","line":30,"symbol":"BufferMockResponseBody","kind":"class","lang":"kotlin","code":"internal class BufferMockResponseBody(\n val buffer: Buffer,\n) : MockResponseBody {\n override val contentLength = buffer.size\n\n override fun writeTo(sink: BufferedSink) {\n buffer.copyTo(sink.buffer)\n sink.emitCompleteSegments()\n }\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/BufferMockResponseBody.kt","line":35,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n buffer.copyTo(sink.buffer)\n sink.emitCompleteSegments()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":41,"symbol":"MockWebServerSocket","kind":"class","lang":"kotlin","doc":"Adapts a [java.net.Socket] to MockWebServer's needs. Note that [asOkioSocket] returns a socket that closes the underlying [java.net.Socket] when both of its component streams are closed. This class takes advantage of that.","code":"internal class MockWebServerSocket(\n val javaNetSocket: Socket,\n) : Closeable,\n BufferedSocket {\n private val delegate = javaNetSocket.asOkioSocket()\n private val closedLatch = CountDownLatch(2)\n\n override val source: BufferedSource =\n object : ForwardingSource(delegate.source) {\n private var closed = false\n\n override fun close() {\n if (closed) return\n try {\n super.close()\n } finally {\n closedLatch.countDown()\n }\n }\n }.buffer()\n\n override val sink: BufferedSink =\n object : ForwardingSink(delegate.sink) {\n private var closed = false\n\n override fun close() {\n if (closed) return\n try {\n super.close()\n } finally {\n closedLatch.countDown()\n }\n }\n }.buffer()\n\n val localAddress: InetAddress\n get() = javaNetSocket.localAddress\n\n val localPort: Int\n get() = javaNetSocket.localPort\n\n val scheme: String\n get() =\n when (javaNetSocket) {\n is SSLSocket -> \"https\"\n else -> \"http\"\n }\n\n val handshake: Handshake?\n get() = (javaNetSocket as? SSLSocket)?.session?.handshake()\n\n val handshakeServerNames: List\n get("} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":52,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n if (closed) return\n try {\n super.close()\n } finally {\n closedLatch.countDown()\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":66,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n if (closed) return\n try {\n super.close()\n } finally {\n closedLatch.countDown()\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":98,"symbol":"shutdownInput","kind":"function","lang":"kotlin","code":"fun shutdownInput() {\n javaNetSocket.shutdownInput()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":102,"symbol":"shutdownOutput","kind":"function","lang":"kotlin","code":"fun shutdownOutput() {\n javaNetSocket.shutdownOutput()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":107,"symbol":"sleepWhileOpen","kind":"function","lang":"kotlin","doc":"Sleeps [nanos], throwing if the socket is closed before that period has elapsed.","code":"fun sleepWhileOpen(nanos: Long) {\n var ms = nanos / 1_000_000L\n val ns = nanos - (ms * 1_000_000L)\n\n while (ms > 100) {\n Thread.sleep(100)\n if (javaNetSocket.isClosed) throw InterruptedIOException(\"socket closed\")\n ms -= 100L\n }\n\n if (ms > 0L || ns > 0) {\n Thread.sleep(ms, ns.toInt())\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":122,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n delegate.cancel()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":126,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n javaNetSocket.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/MockWebServerSocket.kt","line":130,"symbol":"awaitClosed","kind":"function","lang":"kotlin","code":"fun awaitClosed() {\n closedLatch.await()\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/RecordedRequestFactory.kt","line":28,"symbol":"RecordedRequest","kind":"function","lang":"kotlin","code":"internal fun RecordedRequest(\n requestLine: RequestLine,\n headers: Headers,\n chunkSizes: List?,\n bodySize: Long,\n body: ByteString?,\n connectionIndex: Int,\n exchangeIndex: Int,\n socket: MockWebServerSocket,\n failure: IOException? = null,\n): RecordedRequest {\n val requestUrl =\n when (requestLine.method) {\n \"CONNECT\" -> \"${socket.scheme}://${requestLine.target}/\".toHttpUrlOrNull()\n else -> null\n }\n ?: requestLine.target.toHttpUrlOrNull()\n ?: requestUrl(socket, requestLine, headers)\n\n return RecordedRequest(\n connectionIndex = connectionIndex,\n exchangeIndex = exchangeIndex,\n handshake = socket.handshake,\n handshakeServerNames = socket.handshakeServerNames,\n method = requestLine.method,\n target = requestLine.target,\n version = requestLine.version,\n url = requestUrl,\n headers = headers,\n body = body,\n bodySize = bodySize,\n chunkSizes = chunkSizes,\n failure = failure,\n )\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/RecordedRequestFactory.kt","line":64,"symbol":"decodeRequestLine","kind":"function","lang":"kotlin","code":"internal fun decodeRequestLine(requestLine: String?): RequestLine {\n val parts =\n when {\n requestLine != null -> requestLine.split(' ', limit = 3)\n else -> return DEFAULT_REQUEST_LINE_HTTP_1\n }\n\n if (parts.size != 3) {\n throw ProtocolException(\"unexpected request line: $requestLine\")\n }\n\n return RequestLine(\n method = parts[0],\n target = parts[1],\n version = parts[2],\n )\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/RecordedRequestFactory.kt","line":82,"symbol":"RequestLine","kind":"class","lang":"kotlin","code":"internal class RequestLine(\n val method: String,\n val target: String,\n val version: String,\n) {\n override fun toString() = \"$method $target $version\"\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/RecordedRequestFactory.kt","line":87,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"$method $target $version\""} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/RecordedRequestFactory.kt","line":104,"symbol":"requestUrl","kind":"function","lang":"kotlin","code":"private fun requestUrl(\n socket: MockWebServerSocket,\n requestLine: RequestLine,\n headers: Headers,\n): HttpUrl {\n val hostAndPort =\n headers[\":authority\"]\n ?: headers[\"Host\"]\n ?: when (val inetAddress = socket.localAddress) {\n is Inet6Address -> \"[${inetAddress.hostAddress}]:${socket.localPort}\"\n else -> \"${inetAddress.hostAddress}:${socket.localPort}\"\n }\n\n // For OPTIONS, the request target may be a '*', like 'OPTIONS * HTTP/1.1'.\n val path =\n when {\n requestLine.method == \"OPTIONS\" && requestLine.target == \"*\" -> \"/\"\n else -> requestLine.target\n }\n\n return \"${socket.scheme}://$hostAndPort$path\".toHttpUrl()\n}"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/ThrottledSink.kt","line":34,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n var bytesLeft = byteCount\n\n while (bytesLeft > 0) {\n if (bytesWrittenSinceLastDelay == bytesPerPeriod) {\n flush()\n socket.sleepWhileOpen(periodDelayNanos)\n bytesWrittenSinceLastDelay = 0\n }\n\n val toWrite = minOf(bytesLeft, bytesPerPeriod - bytesWrittenSinceLastDelay)\n bytesWrittenSinceLastDelay += toWrite\n bytesLeft -= toWrite\n delegate.write(source, toWrite)\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/main/kotlin/mockwebserver3/internal/TriggerSink.kt","line":33,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n if (byteCount == 0L) return // Avoid double-triggering.\n\n if (bytesWritten == triggerByteCount) {\n source.skip(byteCount)\n return\n }\n\n val toWrite = minOf(byteCount, triggerByteCount - bytesWritten)\n bytesWritten += toWrite\n\n delegate.write(source, toWrite)\n\n if (bytesWritten == triggerByteCount) {\n trigger()\n }\n\n source.skip(byteCount - toWrite)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/CustomDispatcherTest.kt","line":28,"symbol":"CustomDispatcherTest","kind":"class","lang":"kotlin","code":"@Timeout(30)\nclass CustomDispatcherTest {\n @StartStop private val mockWebServer = MockWebServer()\n\n @Test\n fun simpleDispatch() {\n val requestsMade = mutableListOf()\n val dispatcher: Dispatcher =\n object : Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse {\n requestsMade.add(request)\n return MockResponse()\n }\n }\n assertThat(requestsMade.size).isEqualTo(0)\n mockWebServer.dispatcher = dispatcher\n val url = mockWebServer.url(\"/\").toUrl()\n val conn = url.openConnection() as HttpURLConnection\n conn.responseCode // Force the connection to hit the \"server\".\n // Make sure our dispatcher got the request.\n assertThat(requestsMade.size).isEqualTo(1)\n }\n\n @Test\n fun outOfOrderResponses() {\n val firstResponseCode = AtomicInteger()\n val secondResponseCode = AtomicInteger()\n val secondRequest = \"/bar\"\n val firstRequest = \"/foo\"\n val latch = CountDownLatch(1)\n val dispatcher: Dispatcher =\n object : Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse {\n if (request.url.encodedPath == firstRequest) {\n latch"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/CustomDispatcherTest.kt","line":32,"symbol":"simpleDispatch","kind":"function","lang":"kotlin","code":"@Test\n fun simpleDispatch() {\n val requestsMade = mutableListOf()\n val dispatcher: Dispatcher =\n object : Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse {\n requestsMade.add(request)\n return MockResponse()\n }\n }\n assertThat(requestsMade.size).isEqualTo(0)\n mockWebServer.dispatcher = dispatcher\n val url = mockWebServer.url(\"/\").toUrl()\n val conn = url.openConnection() as HttpURLConnection\n conn.responseCode // Force the connection to hit the \"server\".\n // Make sure our dispatcher got the request.\n assertThat(requestsMade.size).isEqualTo(1)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/CustomDispatcherTest.kt","line":37,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"override fun dispatch(request: RecordedRequest): MockResponse {\n requestsMade.add(request)\n return MockResponse()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/CustomDispatcherTest.kt","line":51,"symbol":"outOfOrderResponses","kind":"function","lang":"kotlin","code":"@Test\n fun outOfOrderResponses() {\n val firstResponseCode = AtomicInteger()\n val secondResponseCode = AtomicInteger()\n val secondRequest = \"/bar\"\n val firstRequest = \"/foo\"\n val latch = CountDownLatch(1)\n val dispatcher: Dispatcher =\n object : Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse {\n if (request.url.encodedPath == firstRequest) {\n latch.await()\n }\n return MockResponse()\n }\n }\n mockWebServer.dispatcher = dispatcher\n val startsFirst = buildRequestThread(firstRequest, firstResponseCode)\n startsFirst.start()\n val endsFirst = buildRequestThread(secondRequest, secondResponseCode)\n endsFirst.start()\n endsFirst.join()\n // First response is still waiting.\n assertThat(firstResponseCode.get()).isEqualTo(0)\n // Second response is done.\n assertThat(secondResponseCode.get()).isEqualTo(200)\n latch.countDown()\n startsFirst.join()\n // And now it's done!\n assertThat(firstResponseCode.get()).isEqualTo(200)\n // (Still done).\n assertThat(secondResponseCode.get()).isEqualTo(200)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/CustomDispatcherTest.kt","line":60,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"override fun dispatch(request: RecordedRequest): MockResponse {\n if (request.url.encodedPath == firstRequest) {\n latch.await()\n }\n return MockResponse()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/CustomDispatcherTest.kt","line":85,"symbol":"buildRequestThread","kind":"function","lang":"kotlin","code":"private fun buildRequestThread(\n path: String,\n responseCode: AtomicInteger,\n ): Thread =\n Thread {\n val url = mockWebServer.url(path).toUrl()\n val conn: HttpURLConnection\n try {\n conn = url.openConnection() as HttpURLConnection\n responseCode.set(conn.responseCode) // Force the connection to hit the \"server\".\n } catch (ignored: IOException) {\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockResponseSniTest.kt","line":36,"symbol":"MockResponseSniTest","kind":"class","lang":"kotlin","code":"class MockResponseSniTest {\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @RegisterExtension\n val platform = PlatformRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @Test\n fun clientSendsServerNameAndServerReceivesIt() {\n // java.net.ConnectException: Connection refused\n platform.assumeNotConscrypt()\n\n val handshakeCertificates = localhost()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n\n val dns =\n Dns {\n Dns.SYSTEM.lookup(server.hostName)\n }\n\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).dns(dns)\n .build()\n\n server.enqueue(MockResponse())\n\n val url =\n server\n .url(\"/\")\n .newBuilder()\n .host(\"localhost.localdomain\")\n .build()\n val call = client.newCall(Request(url = url))\n val response = call.execute()\n assertThat(response.isSuccessful).isTrue()\n\n val recordedRequest = server.takeRequest()\n // https://github.com/bcgit/bc-java/issues/1773\n if (!platform.isBouncyCastle()) {\n ass"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockResponseSniTest.kt","line":46,"symbol":"clientSendsServerNameAndServerReceivesIt","kind":"function","lang":"kotlin","code":"@Test\n fun clientSendsServerNameAndServerReceivesIt() {\n // java.net.ConnectException: Connection refused\n platform.assumeNotConscrypt()\n\n val handshakeCertificates = localhost()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n\n val dns =\n Dns {\n Dns.SYSTEM.lookup(server.hostName)\n }\n\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).dns(dns)\n .build()\n\n server.enqueue(MockResponse())\n\n val url =\n server\n .url(\"/\")\n .newBuilder()\n .host(\"localhost.localdomain\")\n .build()\n val call = client.newCall(Request(url = url))\n val response = call.execute()\n assertThat(response.isSuccessful).isTrue()\n\n val recordedRequest = server.takeRequest()\n // https://github.com/bcgit/bc-java/issues/1773\n if (!platform.isBouncyCastle()) {\n assertThat(recordedRequest.handshakeServerNames).containsExactly(url.host)\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockResponseSniTest.kt","line":91,"symbol":"domainFronting","kind":"function","lang":"kotlin","doc":"Use different hostnames for the TLS handshake (including SNI) and the HTTP request (in the Host header).","code":"@Test\n fun domainFronting() {\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"server name\")\n .addSubjectAlternativeName(\"url-host.com\")\n .build()\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .heldCertificate(heldCertificate)\n .addTrustedCertificate(heldCertificate.certificate)\n .build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n\n val dns =\n Dns {\n Dns.SYSTEM.lookup(server.hostName)\n }\n\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).dns(dns)\n .build()\n\n server.enqueue(MockResponse())\n\n val call =\n client.newCall(\n Request(\n url = \"https://url-host.com:${server.port}/\".toHttpUrl(),\n headers = headersOf(\"Host\", \"header-host\"),\n ),\n )\n val response = call.execute()\n assertThat(response.isSuccessful).isTrue()\n\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.url.host).isEqualTo(\"header-host\")\n\n /"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockResponseSniTest.kt","line":143,"symbol":"ipv6","kind":"function","lang":"kotlin","doc":"No SNI for literal IPv6 addresses.","code":"@Test\n fun ipv6() {\n val recordedRequest = requestToHostnameViaProxy(\"2607:f8b0:400b:804::200e\")\n assertThat(recordedRequest.url.host).isEqualTo(\"2607:f8b0:400b:804::200e\")\n assertThat(recordedRequest.handshakeServerNames).isEmpty()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockResponseSniTest.kt","line":151,"symbol":"ipv4","kind":"function","lang":"kotlin","doc":"No SNI for literal IPv4 addresses.","code":"@Test\n fun ipv4() {\n val recordedRequest = requestToHostnameViaProxy(\"76.223.91.57\")\n assertThat(recordedRequest.url.host).isEqualTo(\"76.223.91.57\")\n assertThat(recordedRequest.handshakeServerNames).isEmpty()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockResponseSniTest.kt","line":158,"symbol":"regularHostname","kind":"function","lang":"kotlin","code":"@Test\n fun regularHostname() {\n val recordedRequest = requestToHostnameViaProxy(\"cash.app\")\n assertThat(recordedRequest.url.host).isEqualTo(\"cash.app\")\n // https://github.com/bcgit/bc-java/issues/1773\n if (!platform.isBouncyCastle()) {\n assertThat(recordedRequest.handshakeServerNames).containsExactly(\"cash.app\")\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockResponseSniTest.kt","line":172,"symbol":"requestToHostnameViaProxy","kind":"function","lang":"kotlin","doc":"Connect to [hostnameOrIpAddress] and return what was received. To fake an arbitrary hostname we tell MockWebServer to act as a proxy.","code":"private fun requestToHostnameViaProxy(hostnameOrIpAddress: String): RecordedRequest {\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"server name\")\n .addSubjectAlternativeName(hostnameOrIpAddress)\n .build()\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .heldCertificate(heldCertificate)\n .addTrustedCertificate(heldCertificate.certificate)\n .build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).proxy(server.proxyAddress)\n .build()\n\n server.enqueue(\n MockResponse\n .Builder()\n .inTunnel()\n .build(),\n )\n server.enqueue(MockResponse())\n\n val call =\n client.newCall(\n Request(\n url =\n server\n .url(\"/\")\n .newBuilder()\n .host(hostnameOrIpAddress)\n .build(),\n ),\n )\n val response = call.execute()\n assertThat(response.isSuccessfu"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":67,"symbol":"MockWebServerTest","kind":"class","lang":"kotlin","code":"@Suppress(\"deprecation\")\n@Timeout(30)\n@Tag(\"Slow\")\nclass MockWebServerTest {\n @RegisterExtension\n var platform = PlatformRule()\n\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n server.start()\n }\n\n @AfterEach\n fun tearDown() {\n server.close()\n }\n\n @Test\n fun defaultMockResponse() {\n val builder = MockResponse.Builder()\n assertThat(headersToList(builder)).containsExactly(\"Content-Length: 0\")\n assertThat(builder.status).isEqualTo(\"HTTP/1.1 200 OK\")\n }\n\n @Test\n fun setResponseMockReason() {\n val reasons =\n arrayOf(\n \"Mock Response\",\n \"Informational\",\n \"OK\",\n \"Redirection\",\n \"Client Error\",\n \"Server Error\",\n \"Mock Response\",\n )\n for (i in 0..599) {\n val builder = MockResponse.Builder().code(i)\n val expectedReason = reasons[i / 100]\n assertThat(builder.status).isEqualTo(\"HTTP/1.1 $i $expectedReason\")\n assertThat(headersToList(builder)).containsExactly(\"Content-Length: 0\")\n }\n }\n\n @Test\n fun setStatusControlsWholeStatusLine() {\n val builder = MockResponse.Builder().status(\"HTTP/1.1 202 That'll do pig\")\n assertThat(headersToList(builder)"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":76,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n server.start()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":81,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n server.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":86,"symbol":"defaultMockResponse","kind":"function","lang":"kotlin","code":"@Test\n fun defaultMockResponse() {\n val builder = MockResponse.Builder()\n assertThat(headersToList(builder)).containsExactly(\"Content-Length: 0\")\n assertThat(builder.status).isEqualTo(\"HTTP/1.1 200 OK\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":93,"symbol":"setResponseMockReason","kind":"function","lang":"kotlin","code":"@Test\n fun setResponseMockReason() {\n val reasons =\n arrayOf(\n \"Mock Response\",\n \"Informational\",\n \"OK\",\n \"Redirection\",\n \"Client Error\",\n \"Server Error\",\n \"Mock Response\",\n )\n for (i in 0..599) {\n val builder = MockResponse.Builder().code(i)\n val expectedReason = reasons[i / 100]\n assertThat(builder.status).isEqualTo(\"HTTP/1.1 $i $expectedReason\")\n assertThat(headersToList(builder)).containsExactly(\"Content-Length: 0\")\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":113,"symbol":"setStatusControlsWholeStatusLine","kind":"function","lang":"kotlin","code":"@Test\n fun setStatusControlsWholeStatusLine() {\n val builder = MockResponse.Builder().status(\"HTTP/1.1 202 That'll do pig\")\n assertThat(headersToList(builder)).containsExactly(\"Content-Length: 0\")\n assertThat(builder.status).isEqualTo(\"HTTP/1.1 202 That'll do pig\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":120,"symbol":"setBodyAdjustsHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun setBodyAdjustsHeaders() {\n val builder = MockResponse.Builder().body(\"ABC\")\n assertThat(headersToList(builder)).containsExactly(\"Content-Length: 3\")\n val response = builder.build()\n val body = Buffer()\n response.body!!.writeTo(body)\n assertThat(body.readUtf8()).isEqualTo(\"ABC\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":130,"symbol":"mockResponseAddHeader","kind":"function","lang":"kotlin","code":"@Test\n fun mockResponseAddHeader() {\n val builder =\n MockResponse\n .Builder()\n .clearHeaders()\n .addHeader(\"Cookie: s=square\")\n .addHeader(\"Cookie\", \"a=android\")\n assertThat(headersToList(builder)).containsExactly(\"Cookie: s=square\", \"Cookie: a=android\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":141,"symbol":"mockResponseSetHeader","kind":"function","lang":"kotlin","code":"@Test\n fun mockResponseSetHeader() {\n val builder =\n MockResponse\n .Builder()\n .clearHeaders()\n .addHeader(\"Cookie: s=square\")\n .addHeader(\"Cookie: a=android\")\n .addHeader(\"Cookies: delicious\")\n builder.setHeader(\"cookie\", \"r=robot\")\n assertThat(headersToList(builder)).containsExactly(\"Cookies: delicious\", \"cookie: r=robot\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":154,"symbol":"mockResponseSetHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun mockResponseSetHeaders() {\n val builder =\n MockResponse\n .Builder()\n .clearHeaders()\n .addHeader(\"Cookie: s=square\")\n .addHeader(\"Cookies: delicious\")\n builder.headers(Headers.Builder().add(\"Cookie\", \"a=android\").build())\n assertThat(headersToList(builder)).containsExactly(\"Cookie: a=android\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":166,"symbol":"regularResponse","kind":"function","lang":"kotlin","code":"@Test\n fun regularResponse() {\n server.enqueue(MockResponse.Builder().body(\"hello world\").build())\n val url = server.url(\"/\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n connection.setRequestProperty(\"Accept-Language\", \"en-US\")\n val reader = BufferedReader(InputStreamReader(connection.inputStream, UTF_8))\n assertThat(connection.responseCode).isEqualTo(HttpURLConnection.HTTP_OK)\n assertThat(reader.readLine()).isEqualTo(\"hello world\")\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"GET / HTTP/1.1\")\n assertThat(request.headers[\"Accept-Language\"]).isEqualTo(\"en-US\")\n\n // Server has no more requests.\n assertThat(server.takeRequest(100, TimeUnit.MILLISECONDS)).isNull()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":183,"symbol":"redirect","kind":"function","lang":"kotlin","code":"@Test\n fun redirect() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_MOVED_TEMP)\n .addHeader(\"Location: \" + server.url(\"/new-path\"))\n .body(\"This page has moved!\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"This is the new location!\")\n .build(),\n )\n val connection = server.url(\"/\").toUrl().openConnection()\n val reader = BufferedReader(InputStreamReader(connection!!.getInputStream(), UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"This is the new location!\")\n val first = server.takeRequest()\n assertThat(first.requestLine).isEqualTo(\"GET / HTTP/1.1\")\n val redirect = server.takeRequest()\n assertThat(redirect.requestLine).isEqualTo(\"GET /new-path HTTP/1.1\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":212,"symbol":"dispatchBlocksWaitingForEnqueue","kind":"function","lang":"kotlin","doc":"Test that MockWebServer blocks for a call to enqueue() if a request is made before a mock response is ready.","code":"@Test\n fun dispatchBlocksWaitingForEnqueue() {\n Thread {\n try {\n Thread.sleep(1000)\n } catch (ignored: InterruptedException) {\n }\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"enqueued in the background\")\n .build(),\n )\n }.start()\n val connection = server.url(\"/\").toUrl().openConnection()\n val reader = BufferedReader(InputStreamReader(connection!!.getInputStream(), UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"enqueued in the background\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":231,"symbol":"nonHexadecimalChunkSize","kind":"function","lang":"kotlin","code":"@Test\n fun nonHexadecimalChunkSize() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"G\\r\\nxxxxxxxxxxxxxxxx\\r\\n0\\r\\n\\r\\n\")\n .clearHeaders()\n .addHeader(\"Transfer-encoding: chunked\")\n .build(),\n )\n val connection = server.url(\"/\").toUrl().openConnection()\n try {\n connection.getInputStream().read()\n fail()\n } catch (expected: IOException) {\n // Expected.\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":250,"symbol":"responseTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun responseTimeout() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"ABC\")\n .clearHeaders()\n .addHeader(\"Content-Length: 4\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"DEF\")\n .build(),\n )\n val urlConnection = server.url(\"/\").toUrl().openConnection()\n urlConnection!!.readTimeout = 1000\n val inputStream = urlConnection.getInputStream()\n assertThat(inputStream!!.read()).isEqualTo('A'.code)\n assertThat(inputStream.read()).isEqualTo('B'.code)\n assertThat(inputStream.read()).isEqualTo('C'.code)\n try {\n inputStream.read() // if Content-Length was accurate, this would return -1 immediately\n fail()\n } catch (expected: SocketTimeoutException) {\n // Expected.\n }\n val urlConnection2 = server.url(\"/\").toUrl().openConnection()\n val in2 = urlConnection2!!.getInputStream()\n assertThat(in2!!.read()).isEqualTo('D'.code)\n assertThat(in2.read()).isEqualTo('E'.code)\n assertThat(in2.read()).isEqualTo('F'.code)\n assertThat(in2.read()).isEqualTo(-1)\n val c0e0 = server.takeRequest()\n assertThat(c0e0.connectionIndex).isEqual"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":292,"symbol":"disconnectAtStart","kind":"function","lang":"kotlin","code":"@Disabled(\"Not actually failing where expected\")\n @Test\n fun disconnectAtStart() {\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseSocket())\n .build(),\n )\n server.enqueue(MockResponse()) // The jdk's HttpUrlConnection is a bastard.\n server.enqueue(MockResponse())\n try {\n server\n .url(\"/a\")\n .toUrl()\n .openConnection()\n .getInputStream()\n fail()\n } catch (expected: IOException) {\n // Expected.\n }\n server\n .url(\"/b\")\n .toUrl()\n .openConnection()\n .getInputStream() // Should succeed.\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":320,"symbol":"clearDispatcherQueue","kind":"function","lang":"kotlin","code":"@Test\n fun clearDispatcherQueue() {\n server.enqueue(MockResponse(body = \"A\"))\n (server.dispatcher as QueueDispatcher).clear()\n server.enqueue(MockResponse(body = \"B\"))\n val inputStream =\n server\n .url(\"/a\")\n .toUrl()\n .openConnection()\n .getInputStream()\n assertThat(inputStream!!.read()).isEqualTo('B'.code)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":338,"symbol":"throttleRequest","kind":"function","lang":"kotlin","doc":"Throttle the request body by sleeping 500ms after every 3 bytes. With a 6-byte request, this should yield one sleep for a total delay of 500ms.","code":"@Test\n fun throttleRequest() {\n assumeNotWindows()\n server.enqueue(\n MockResponse\n .Builder()\n .throttleBody(3, 500, TimeUnit.MILLISECONDS)\n .build(),\n )\n val startNanos = System.nanoTime()\n val connection = server.url(\"/\").toUrl().openConnection()\n connection.doOutput = true\n connection.getOutputStream().write(\"ABCDEF\".toByteArray(UTF_8))\n val inputStream = connection.getInputStream()\n assertThat(inputStream.read()).isEqualTo(-1)\n val elapsedNanos = System.nanoTime() - startNanos\n val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos)\n assertThat(elapsedMillis).isBetween(500L, 1000L)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":362,"symbol":"throttleResponse","kind":"function","lang":"kotlin","doc":"Throttle the response body by sleeping 500ms after every 3 bytes. With a 6-byte response, this should yield one sleep for a total delay of 500ms.","code":"@Test\n fun throttleResponse() {\n assumeNotWindows()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"ABCDEF\")\n .throttleBody(3, 500, TimeUnit.MILLISECONDS)\n .build(),\n )\n val startNanos = System.nanoTime()\n val connection = server.url(\"/\").toUrl().openConnection()\n val inputStream = connection!!.getInputStream()\n assertThat(inputStream!!.read()).isEqualTo('A'.code)\n assertThat(inputStream.read()).isEqualTo('B'.code)\n assertThat(inputStream.read()).isEqualTo('C'.code)\n assertThat(inputStream.read()).isEqualTo('D'.code)\n assertThat(inputStream.read()).isEqualTo('E'.code)\n assertThat(inputStream.read()).isEqualTo('F'.code)\n assertThat(inputStream.read()).isEqualTo(-1)\n val elapsedNanos = System.nanoTime() - startNanos\n val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos)\n assertThat(elapsedMillis).isBetween(500L, 1000L)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":388,"symbol":"delayResponse","kind":"function","lang":"kotlin","doc":"Delay the response body by sleeping 1s.","code":"@Test\n fun delayResponse() {\n assumeNotWindows()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"ABCDEF\")\n .bodyDelay(1, TimeUnit.SECONDS)\n .build(),\n )\n val startNanos = System.nanoTime()\n val connection = server.url(\"/\").toUrl().openConnection()\n val inputStream = connection!!.getInputStream()\n assertThat(inputStream!!.read()).isEqualTo('A'.code)\n val elapsedNanos = System.nanoTime() - startNanos\n val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos)\n assertThat(elapsedMillis).isGreaterThanOrEqualTo(1000L)\n inputStream.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":408,"symbol":"disconnectRequestHalfway","kind":"function","lang":"kotlin","code":"@Test\n fun disconnectRequestHalfway() {\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestBody(CloseSocket())\n .build(),\n )\n // Limit the size of the request body that the server holds in memory to an arbitrary\n // 3.5 MBytes so this test can pass on devices with little memory.\n server.bodyLimit = 7 * 512 * 1024\n val connection = server.url(\"/\").toUrl().openConnection() as HttpURLConnection\n connection.requestMethod = \"POST\"\n connection.doOutput = true\n connection.setFixedLengthStreamingMode(1024 * 1024 * 1024) // 1 GB\n connection.connect()\n val out = connection.outputStream\n val data = ByteArray(1024 * 1024)\n var i = 0\n while (i < 1024) {\n try {\n out!!.write(data)\n out.flush()\n if (i == 513) {\n // pause slightly after half way to make result more predictable\n Thread.sleep(100)\n }\n } catch (e: IOException) {\n break\n }\n i++\n }\n // Halfway +/- 0.5%\n assertThat(i.toFloat()).isCloseTo(512f, 5f)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":444,"symbol":"disconnectResponseHalfway","kind":"function","lang":"kotlin","code":"@Test\n fun disconnectResponseHalfway() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"ab\")\n .onResponseBody(CloseSocket())\n .build(),\n )\n val connection = server.url(\"/\").toUrl().openConnection()\n assertThat(connection!!.contentLength).isEqualTo(2)\n val inputStream = connection.getInputStream()\n assertThat(inputStream!!.read()).isEqualTo('a'.code)\n try {\n val byteRead = inputStream.read()\n // OpenJDK behavior: end of stream.\n assertThat(byteRead).isEqualTo(-1)\n } catch (e: ProtocolException) {\n // On Android, HttpURLConnection is implemented by OkHttp v2. OkHttp\n // treats an incomplete response body as a ProtocolException.\n } catch (ioe: IOException) {\n // Change in https://bugs.openjdk.org/browse/JDK-8335135\n assertThat(ioe.message).isEqualTo(\"Premature EOF\")\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":470,"symbol":"headersToList","kind":"function","lang":"kotlin","code":"private fun headersToList(response: MockResponse.Builder): List {\n val headers = response.build().headers\n return headers.map { (key, value) -> \"$key: $value\" }.toList()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":475,"symbol":"closeWithoutStart","kind":"function","lang":"kotlin","code":"@Test\n fun closeWithoutStart() {\n val server = MockWebServer()\n server.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":481,"symbol":"closeViaClosable","kind":"function","lang":"kotlin","code":"@Test\n fun closeViaClosable() {\n val server: Closeable = MockWebServer()\n server.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":487,"symbol":"closeWithoutEnqueue","kind":"function","lang":"kotlin","code":"@Test\n fun closeWithoutEnqueue() {\n val server = MockWebServer()\n server.start()\n server.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":494,"symbol":"portValidAfterStart","kind":"function","lang":"kotlin","code":"@Test\n fun portValidAfterStart() {\n assertThat(server.port).isGreaterThan(0)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":499,"symbol":"hostNameValidAfterStart","kind":"function","lang":"kotlin","code":"@Test\n fun hostNameValidAfterStart() {\n assertThat(server.hostName).isNotNull()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":504,"symbol":"proxyAddressValidAfterStart","kind":"function","lang":"kotlin","code":"@Test\n fun proxyAddressValidAfterStart() {\n assertThat(server.proxyAddress).isNotNull()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":509,"symbol":"differentInstancesGetDifferentPorts","kind":"function","lang":"kotlin","code":"@Test\n fun differentInstancesGetDifferentPorts() {\n val other = MockWebServer()\n other.use {\n other.start()\n assertThat(other.port).isNotEqualTo(server.port)\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":518,"symbol":"cannotAccessAddressBeforeStart","kind":"function","lang":"kotlin","code":"@Test\n fun cannotAccessAddressBeforeStart() {\n val other = MockWebServer()\n assertFailsWith {\n other.socketAddress\n }\n assertFailsWith {\n other.hostName\n }\n assertFailsWith {\n other.port\n }\n assertFailsWith {\n other.proxyAddress\n }\n other.use {\n other.start()\n assertThat(other.socketAddress).isNotNull()\n assertThat(other.hostName).isNotNull()\n assertThat(other.port).isNotNull()\n assertThat(other.proxyAddress).isNotNull()\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":542,"symbol":"startIsIdempotentIfAddressIsConsistent","kind":"function","lang":"kotlin","code":"@Test\n fun startIsIdempotentIfAddressIsConsistent() {\n val other = MockWebServer()\n val addressA = InetAddress.getByAddress(\"localhost\", byteArrayOf(127, 0, 0, 1))\n val addressB = InetAddress.getByAddress(\"localhost\", byteArrayOf(127, 0, 0, 2))\n other.use {\n other.start(addressA, 0)\n\n // Same address is okay.\n other.start(addressA, 0)\n\n // Same address with bound port is okay.\n other.start(addressA, other.port)\n\n // Different address is not okay.\n assertFailsWith {\n other.start(addressB, 0)\n }\n\n // Different port is not okay.\n assertFailsWith {\n other.start(addressA, other.port - 1)\n }\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":568,"symbol":"toStringIncludesLifecycleState","kind":"function","lang":"kotlin","code":"@Test\n fun toStringIncludesLifecycleState() {\n val other = MockWebServer()\n assertThat(other.toString()).isEqualTo(\"MockWebServer{new}\")\n other.use {\n other.start()\n assertThat(other.toString()).isEqualTo(\"MockWebServer{port=${other.port}}\")\n }\n assertThat(other.toString()).isEqualTo(\"MockWebServer{closed}\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":579,"symbol":"closeWhileBlockedDispatching","kind":"function","lang":"kotlin","code":"@Test\n fun closeWhileBlockedDispatching() {\n // Enqueue a request that'll cause MockWebServer to hang on QueueDispatcher.dispatch().\n val connection = server.url(\"/\").toUrl().openConnection() as HttpURLConnection\n connection.readTimeout = 500\n assertFailsWith {\n connection.responseCode\n }\n\n // Closing the server should unblock the dispatcher.\n server.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":592,"symbol":"requestUrlReconstructed","kind":"function","lang":"kotlin","code":"@Test\n fun requestUrlReconstructed() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"hello world\")\n .build(),\n )\n val url = server.url(\"/a/deep/path?key=foo%20bar\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n val inputStream = connection.inputStream\n val reader = BufferedReader(InputStreamReader(inputStream, UTF_8))\n assertThat(connection.responseCode).isEqualTo(HttpURLConnection.HTTP_OK)\n assertThat(reader.readLine()).isEqualTo(\"hello world\")\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\n \"GET /a/deep/path?key=foo%20bar HTTP/1.1\",\n )\n val requestUrl = request.url\n assertThat(requestUrl.scheme).isEqualTo(\"http\")\n assertThat(requestUrl.host).isEqualTo(server.hostName)\n assertThat(requestUrl.port).isEqualTo(server.port)\n assertThat(requestUrl.encodedPath).isEqualTo(\"/a/deep/path\")\n assertThat(requestUrl.queryParameter(\"key\")).isEqualTo(\"foo bar\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":618,"symbol":"shutdownServerAfterRequest","kind":"function","lang":"kotlin","code":"@Test\n fun shutdownServerAfterRequest() {\n server.enqueue(\n MockResponse\n .Builder()\n .shutdownServer(true)\n .build(),\n )\n val url = server.url(\"/\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n assertThat(connection.responseCode).isEqualTo(HttpURLConnection.HTTP_OK)\n val refusedConnection = url.openConnection() as HttpURLConnection\n assertFailsWith {\n refusedConnection.responseCode\n }.also { expected ->\n assertThat(expected.message!!).contains(\"refused\")\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":637,"symbol":"http100Continue","kind":"function","lang":"kotlin","code":"@Test\n fun http100Continue() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"response\")\n .build(),\n )\n val url = server.url(\"/\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n connection.doOutput = true\n connection.setRequestProperty(\"Expect\", \"100-Continue\")\n connection.outputStream.write(\"request\".toByteArray(UTF_8))\n val inputStream = connection.inputStream\n val reader = BufferedReader(InputStreamReader(inputStream, UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"response\")\n val request = server.takeRequest()\n assertThat(request.body?.utf8()).isEqualTo(\"request\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":657,"symbol":"http100ContinueChunkedStreaming","kind":"function","lang":"kotlin","code":"@Test\n fun http100ContinueChunkedStreaming() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"response\")\n .add100Continue()\n .build(),\n )\n val url = server.url(\"/\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n connection.doOutput = true\n connection.setRequestProperty(\"Expect\", \"100-Continue\")\n connection.setChunkedStreamingMode(0)\n connection.outputStream.write(\"request\".toByteArray(UTF_8))\n val inputStream = connection.inputStream\n val reader = BufferedReader(InputStreamReader(inputStream, UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"response\")\n val request = server.takeRequest()\n assertThat(request.body?.utf8()).isEqualTo(\"request\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":679,"symbol":"multiple1xxResponses","kind":"function","lang":"kotlin","code":"@Test\n fun multiple1xxResponses() {\n server.enqueue(\n MockResponse\n .Builder()\n .add100Continue()\n .add100Continue()\n .body(\"response\")\n .build(),\n )\n val url = server.url(\"/\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n connection.doOutput = true\n connection.outputStream.write(\"request\".toByteArray(UTF_8))\n val inputStream = connection.inputStream\n val reader = BufferedReader(InputStreamReader(inputStream, UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"response\")\n val request = server.takeRequest()\n assertThat(request.body?.utf8()).isEqualTo(\"request\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":700,"symbol":"testH2PriorKnowledgeServerFallback","kind":"function","lang":"kotlin","code":"@Test\n fun testH2PriorKnowledgeServerFallback() {\n try {\n server.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)\n fail()\n } catch (expected: IllegalArgumentException) {\n assertThat(expected.message).isEqualTo(\n \"protocols containing h2_prior_knowledge cannot use other protocols: \" +\n \"[h2_prior_knowledge, http/1.1]\",\n )\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":713,"symbol":"testH2PriorKnowledgeServerDuplicates","kind":"function","lang":"kotlin","code":"@Test\n fun testH2PriorKnowledgeServerDuplicates() {\n try {\n // Treating this use case as user error\n server.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)\n fail()\n } catch (expected: IllegalArgumentException) {\n assertThat(expected.message).isEqualTo(\n \"protocols containing h2_prior_knowledge cannot use other protocols: \" +\n \"[h2_prior_knowledge, h2_prior_knowledge]\",\n )\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":727,"symbol":"testMockWebServerH2PriorKnowledgeProtocol","kind":"function","lang":"kotlin","code":"@Test\n fun testMockWebServerH2PriorKnowledgeProtocol() {\n server.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE)\n assertThat(server.protocols.size).isEqualTo(1)\n assertThat(server.protocols[0]).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":734,"symbol":"https","kind":"function","lang":"kotlin","code":"@Test\n fun https() {\n val handshakeCertificates = platform.localhostHandshakeCertificates()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val url = server.url(\"/\")\n val connection = url.toUrl().openConnection() as HttpsURLConnection\n connection.sslSocketFactory = handshakeCertificates.sslSocketFactory()\n connection.hostnameVerifier = RecordingHostnameVerifier()\n assertThat(connection.responseCode).isEqualTo(HttpURLConnection.HTTP_OK)\n val reader = BufferedReader(InputStreamReader(connection.inputStream, UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"abc\")\n val request = server.takeRequest()\n assertThat(request.url.scheme).isEqualTo(\"https\")\n val handshake = request.handshake\n assertThat(handshake!!.tlsVersion).isNotNull()\n assertThat(handshake.cipherSuite).isNotNull()\n assertThat(handshake.localPrincipal).isNotNull()\n assertThat(handshake.localCertificates.size).isEqualTo(1)\n assertThat(handshake.peerPrincipal).isNull()\n assertThat(handshake.peerCertificates.size).isEqualTo(0)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":762,"symbol":"httpsWithClientAuth","kind":"function","lang":"kotlin","code":"@Test\n fun httpsWithClientAuth() {\n platform.assumeNotBouncyCastle()\n platform.assumeNotConscrypt()\n\n val clientCa =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .build()\n val serverCa =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .build()\n val serverCertificate =\n HeldCertificate\n .Builder()\n .signedBy(serverCa)\n .addSubjectAlternativeName(server.hostName)\n .build()\n val serverHandshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(clientCa.certificate)\n .heldCertificate(serverCertificate)\n .build()\n server.useHttps(serverHandshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n server.requestClientAuth()\n val clientCertificate =\n HeldCertificate\n .Builder()\n .signedBy(clientCa)\n .build()\n val clientHandshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(serverCa.certificate)\n .heldCertificate(clientCertificate)\n ."} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":826,"symbol":"proxiedRequestGetsCorrectRequestUrl","kind":"function","lang":"kotlin","code":"@Test\n fun proxiedRequestGetsCorrectRequestUrl() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Result\")\n .build(),\n )\n val proxiedClient =\n OkHttpClient\n .Builder()\n .proxy(server.proxyAddress)\n .readTimeout(Duration.ofMillis(100))\n .build()\n val request = Request.Builder().url(\"http://android.com/\").build()\n proxiedClient.newCall(request).execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"Result\")\n }\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.url).isEqualTo(\"http://android.com/\".toHttpUrl())\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":848,"symbol":"startTwice","kind":"function","lang":"kotlin","code":"@Test\n fun startTwice() {\n val server2 = MockWebServer()\n server2.start()\n server2.start()\n server2.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":856,"symbol":"closeTwice","kind":"function","lang":"kotlin","code":"@Test\n fun closeTwice() {\n val server2 = MockWebServer()\n server2.start()\n server2.close()\n assertFailsWith {\n server2.start()\n }\n server2.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":867,"symbol":"recordedBodyIsNullForGetRequests","kind":"function","lang":"kotlin","code":"@Test\n fun recordedBodyIsNullForGetRequests() {\n server.enqueue(MockResponse())\n val client = OkHttpClient()\n val request =\n Request(\n url = server.url(\"/\"),\n )\n client.newCall(request).execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"\")\n }\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.body).isNull()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":882,"symbol":"recordedBodyIsNullWithDoNotRead","kind":"function","lang":"kotlin","code":"@Test\n fun recordedBodyIsNullWithDoNotRead() {\n server.enqueue(\n MockResponse\n .Builder()\n .doNotReadRequestBody()\n .build(),\n )\n val client = OkHttpClient()\n val request =\n Request(\n url = server.url(\"/\"),\n body = \"hello\".toRequestBody(),\n )\n client.newCall(request).execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"\")\n }\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.body).isNull()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":903,"symbol":"recordedBodyIsEmptyForEmptyPostRequests","kind":"function","lang":"kotlin","code":"@Test\n fun recordedBodyIsEmptyForEmptyPostRequests() {\n server.enqueue(MockResponse())\n val client = OkHttpClient()\n val request =\n Request(\n url = server.url(\"/\"),\n body = \"\".toRequestBody(),\n )\n client.newCall(request).execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"\")\n }\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.body).isEqualTo(ByteString.EMPTY)\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/MockWebServerTest.kt","line":919,"symbol":"recordedBodyIsNonEmptyForNonEmptyPostRequests","kind":"function","lang":"kotlin","code":"@Test\n fun recordedBodyIsNonEmptyForNonEmptyPostRequests() {\n server.enqueue(MockResponse())\n val client = OkHttpClient()\n val request =\n Request(\n url = server.url(\"/\"),\n body = \"hello\".toRequestBody(),\n )\n client.newCall(request).execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"\")\n }\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.body).isEqualTo(\"hello\".encodeUtf8())\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":34,"symbol":"RecordedRequestTest","kind":"class","lang":"kotlin","code":"@Timeout(30)\nclass RecordedRequestTest {\n private val headers: Headers = Headers.EMPTY\n\n @Test fun testIPv4() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress = InetAddress.getByAddress(\"127.0.0.1\", byteArrayOf(127, 0, 0, 1)),\n localPort = 80,\n ),\n )\n val request = RecordedRequest(DEFAULT_REQUEST_LINE_HTTP_1, headers, emptyList(), 0, ByteString.EMPTY, 0, 0, socket)\n assertThat(request.url.toString()).isEqualTo(\"http://127.0.0.1/\")\n }\n\n @Test fun testAuthorityForm() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress = InetAddress.getByAddress(\"127.0.0.1\", byteArrayOf(127, 0, 0, 1)),\n localPort = 80,\n ),\n )\n val requestLine = decodeRequestLine(\"CONNECT example.com:8080 HTTP/1.1\")\n val request = RecordedRequest(requestLine, headers, emptyList(), 0, ByteString.EMPTY, 0, 0, socket)\n assertThat(request.target).isEqualTo(\"example.com:8080\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com:8080/\")\n }\n\n @Test fun testAbsoluteForm() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress = InetAddress"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":38,"symbol":"testIPv4","kind":"function","lang":"kotlin","code":"@Test fun testIPv4() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress = InetAddress.getByAddress(\"127.0.0.1\", byteArrayOf(127, 0, 0, 1)),\n localPort = 80,\n ),\n )\n val request = RecordedRequest(DEFAULT_REQUEST_LINE_HTTP_1, headers, emptyList(), 0, ByteString.EMPTY, 0, 0, socket)\n assertThat(request.url.toString()).isEqualTo(\"http://127.0.0.1/\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":50,"symbol":"testAuthorityForm","kind":"function","lang":"kotlin","code":"@Test fun testAuthorityForm() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress = InetAddress.getByAddress(\"127.0.0.1\", byteArrayOf(127, 0, 0, 1)),\n localPort = 80,\n ),\n )\n val requestLine = decodeRequestLine(\"CONNECT example.com:8080 HTTP/1.1\")\n val request = RecordedRequest(requestLine, headers, emptyList(), 0, ByteString.EMPTY, 0, 0, socket)\n assertThat(request.target).isEqualTo(\"example.com:8080\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com:8080/\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":64,"symbol":"testAbsoluteForm","kind":"function","lang":"kotlin","code":"@Test fun testAbsoluteForm() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress = InetAddress.getByAddress(\"127.0.0.1\", byteArrayOf(127, 0, 0, 1)),\n localPort = 80,\n ),\n )\n val requestLine = decodeRequestLine(\"GET http://example.com:8080/index.html HTTP/1.1\")\n val request = RecordedRequest(requestLine, headers, emptyList(), 0, ByteString.EMPTY, 0, 0, socket)\n assertThat(request.target).isEqualTo(\"http://example.com:8080/index.html\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com:8080/index.html\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":78,"symbol":"testAsteriskForm","kind":"function","lang":"kotlin","code":"@Test fun testAsteriskForm() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress = InetAddress.getByAddress(\"127.0.0.1\", byteArrayOf(127, 0, 0, 1)),\n localPort = 80,\n ),\n )\n val requestLine = decodeRequestLine(\"OPTIONS * HTTP/1.1\")\n val request =\n RecordedRequest(\n requestLine,\n headers,\n emptyList(),\n 0,\n ByteString.EMPTY,\n 0,\n 0,\n socket,\n )\n assertThat(request.target).isEqualTo(\"*\")\n assertThat(request.url.toString()).isEqualTo(\"http://127.0.0.1/\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":102,"symbol":"testIpv6","kind":"function","lang":"kotlin","code":"@Test fun testIpv6() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress =\n InetAddress.getByAddress(\n \"::1\",\n byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),\n ),\n localPort = 80,\n ),\n )\n val request = RecordedRequest(DEFAULT_REQUEST_LINE_HTTP_1, headers, emptyList(), 0, ByteString.EMPTY, 0, 0, socket)\n assertThat(request.url.toString()).isEqualTo(\"http://[::1]/\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":118,"symbol":"testUsesLocal","kind":"function","lang":"kotlin","code":"@Test fun testUsesLocal() {\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress = InetAddress.getByAddress(\"127.0.0.1\", byteArrayOf(127, 0, 0, 1)),\n localPort = 80,\n ),\n )\n val request = RecordedRequest(DEFAULT_REQUEST_LINE_HTTP_1, headers, emptyList(), 0, ByteString.EMPTY, 0, 0, socket)\n assertThat(request.url.toString()).isEqualTo(\"http://127.0.0.1/\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":130,"symbol":"testHostname","kind":"function","lang":"kotlin","code":"@Test fun testHostname() {\n val headers = headersOf(\"Host\", \"host-from-header.com\")\n val socket =\n MockWebServerSocket(\n FakeSocket(\n localAddress =\n InetAddress.getByAddress(\n \"host-from-address.com\",\n byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),\n ),\n localPort = 80,\n ),\n )\n val request = RecordedRequest(DEFAULT_REQUEST_LINE_HTTP_1, headers, emptyList(), 0, ByteString.EMPTY, 0, 0, socket)\n assertThat(request.url.toString()).isEqualTo(\"http://host-from-header.com/\")\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":147,"symbol":"FakeSocket","kind":"class","lang":"kotlin","code":"private class FakeSocket(\n private val localAddress: InetAddress,\n private val localPort: Int,\n private val remoteAddress: InetAddress = localAddress,\n private val remotePort: Int = 1234,\n ) : Socket() {\n override fun getInputStream() = Buffer().inputStream()\n\n override fun getOutputStream() = Buffer().outputStream()\n\n override fun getInetAddress() = remoteAddress\n\n override fun getLocalAddress() = localAddress\n\n override fun getLocalPort() = localPort\n\n override fun getPort() = remotePort\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":153,"symbol":"getInputStream","kind":"function","lang":"kotlin","code":"override fun getInputStream() = Buffer().inputStream()"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":155,"symbol":"getOutputStream","kind":"function","lang":"kotlin","code":"override fun getOutputStream() = Buffer().outputStream()"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":157,"symbol":"getInetAddress","kind":"function","lang":"kotlin","code":"override fun getInetAddress() = remoteAddress"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":159,"symbol":"getLocalAddress","kind":"function","lang":"kotlin","code":"override fun getLocalAddress() = localAddress"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":161,"symbol":"getLocalPort","kind":"function","lang":"kotlin","code":"override fun getLocalPort() = localPort"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/RecordedRequestTest.kt","line":163,"symbol":"getPort","kind":"function","lang":"kotlin","code":"override fun getPort() = remotePort"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":42,"symbol":"Http2Server","kind":"class","lang":"kotlin","doc":"A basic HTTP/2 server that serves the contents of a local directory.","code":"class Http2Server(\n private val baseDirectory: File,\n private val sslSocketFactory: SSLSocketFactory,\n) : Http2Connection.Listener() {\n private fun run() {\n val serverSocket = ServerSocket(8888)\n serverSocket.reuseAddress = true\n while (true) {\n var socket: Socket? = null\n try {\n socket = serverSocket.accept()\n val sslSocket = doSsl(socket)\n val protocolString = Platform.get().getSelectedProtocol(sslSocket)\n val protocol = if (protocolString != null) get(protocolString) else null\n if (protocol != Protocol.HTTP_2) {\n throw ProtocolException(\"Protocol $protocol unsupported\")\n }\n val connection =\n Http2Connection\n .Builder(false, TaskRunner.INSTANCE)\n .socket(sslSocket.asBufferedSocket(), sslSocket.peerName())\n .listener(this)\n .build()\n connection.start()\n } catch (e: IOException) {\n logger.log(Level.INFO, \"Http2Server connection failure: $e\")\n socket?.closeQuietly()\n } catch (e: Exception) {\n logger.log(Level.WARNING, \"Http2Server unexpected failure\", e)\n socket?.closeQuietly()\n }\n }\n }\n\n private f"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":46,"symbol":"run","kind":"function","lang":"kotlin","code":"private fun run() {\n val serverSocket = ServerSocket(8888)\n serverSocket.reuseAddress = true\n while (true) {\n var socket: Socket? = null\n try {\n socket = serverSocket.accept()\n val sslSocket = doSsl(socket)\n val protocolString = Platform.get().getSelectedProtocol(sslSocket)\n val protocol = if (protocolString != null) get(protocolString) else null\n if (protocol != Protocol.HTTP_2) {\n throw ProtocolException(\"Protocol $protocol unsupported\")\n }\n val connection =\n Http2Connection\n .Builder(false, TaskRunner.INSTANCE)\n .socket(sslSocket.asBufferedSocket(), sslSocket.peerName())\n .listener(this)\n .build()\n connection.start()\n } catch (e: IOException) {\n logger.log(Level.INFO, \"Http2Server connection failure: $e\")\n socket?.closeQuietly()\n } catch (e: Exception) {\n logger.log(Level.WARNING, \"Http2Server unexpected failure\", e)\n socket?.closeQuietly()\n }\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":76,"symbol":"doSsl","kind":"function","lang":"kotlin","code":"private fun doSsl(socket: Socket): SSLSocket {\n val sslSocket =\n sslSocketFactory.createSocket(\n socket,\n socket.inetAddress.hostAddress,\n socket.port,\n true,\n ) as SSLSocket\n sslSocket.useClientMode = false\n Platform.get().configureTlsExtensions(\n sslSocket = sslSocket,\n hostname = null,\n protocols = listOf(Protocol.HTTP_2),\n echConfigList = null,\n )\n sslSocket.startHandshake()\n return sslSocket\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":95,"symbol":"onStream","kind":"function","lang":"kotlin","code":"override fun onStream(stream: Http2Stream) {\n try {\n val requestHeaders = stream.takeHeaders()\n var path: String? = null\n var i = 0\n val size = requestHeaders.size\n while (i < size) {\n if (requestHeaders.name(i) == Header.TARGET_PATH_UTF8) {\n path = requestHeaders.value(i)\n break\n }\n i++\n }\n if (path == null) {\n // TODO: send bad request error\n throw AssertionError()\n }\n val file = File(baseDirectory.toString() + path)\n if (file.isDirectory) {\n serveDirectory(stream, file.listFiles()!!)\n } else if (file.exists()) {\n serveFile(stream, file)\n } else {\n send404(stream, path)\n }\n } catch (e: IOException) {\n Platform.get().log(\"Failure serving Http2Stream: \" + e.message, Platform.INFO, null)\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":125,"symbol":"send404","kind":"function","lang":"kotlin","code":"private fun send404(\n stream: Http2Stream,\n path: String,\n ) {\n val responseHeaders =\n listOf(\n Header(\":status\", \"404\"),\n Header(\":version\", \"HTTP/1.1\"),\n Header(\"content-type\", \"text/plain\"),\n )\n stream.writeHeaders(\n responseHeaders = responseHeaders,\n outFinished = false,\n flushHeaders = false,\n )\n val out = stream.sink.buffer()\n out.writeUtf8(\"Not found: $path\")\n out.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":145,"symbol":"serveDirectory","kind":"function","lang":"kotlin","code":"private fun serveDirectory(\n stream: Http2Stream,\n files: Array,\n ) {\n val responseHeaders =\n listOf(\n Header(\":status\", \"200\"),\n Header(\":version\", \"HTTP/1.1\"),\n Header(\"content-type\", \"text/html; charset=UTF-8\"),\n )\n stream.writeHeaders(\n responseHeaders = responseHeaders,\n outFinished = false,\n flushHeaders = false,\n )\n val out = stream.sink.buffer()\n for (file in files) {\n val target = if (file.isDirectory) file.name + \"/\" else file.name\n out.writeUtf8(\"$target
\")\n }\n out.close()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":168,"symbol":"serveFile","kind":"function","lang":"kotlin","code":"private fun serveFile(\n stream: Http2Stream,\n file: File,\n ) {\n val responseHeaders =\n listOf(\n Header(\":status\", \"200\"),\n Header(\":version\", \"HTTP/1.1\"),\n Header(\"content-type\", contentType(file)),\n )\n stream.writeHeaders(\n responseHeaders = responseHeaders,\n outFinished = false,\n flushHeaders = false,\n )\n file.source().use { source ->\n stream.sink.buffer().use { sink ->\n sink.writeAll(source)\n }\n }\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":190,"symbol":"contentType","kind":"function","lang":"kotlin","code":"private fun contentType(file: File): String =\n when {\n file.name.endsWith(\".css\") -> \"text/css\"\n file.name.endsWith(\".gif\") -> \"image/gif\"\n file.name.endsWith(\".html\") -> \"text/html\"\n file.name.endsWith(\".jpeg\") -> \"image/jpeg\"\n file.name.endsWith(\".jpg\") -> \"image/jpeg\"\n file.name.endsWith(\".js\") -> \"application/javascript\"\n file.name.endsWith(\".png\") -> \"image/png\"\n else -> \"text/plain\"\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":202,"symbol":"peerName","kind":"function","lang":"kotlin","code":"private fun Socket.peerName(): String {\n val address = remoteSocketAddress\n return if (address is InetSocketAddress) address.hostName else address.toString()\n }"} {"repo":"okhttp","file":"mockwebserver/src/test/java/mockwebserver3/internal/http2/Http2Server.kt","line":210,"symbol":"main","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun main(args: Array) {\n if (args.size != 1 || args[0].startsWith(\"-\")) {\n println(\"Usage: Http2Server \")\n return\n }\n val server =\n Http2Server(\n File(args[0]),\n localhost().sslContext().socketFactory,\n )\n server.run()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt","line":26,"symbol":"wrap","kind":"function","lang":"kotlin","code":"internal fun Dispatcher.wrap(): mockwebserver3.Dispatcher {\n if (this is QueueDispatcher) return this.delegate\n\n val delegate = this\n return object : mockwebserver3.Dispatcher() {\n override fun dispatch(request: mockwebserver3.RecordedRequest): mockwebserver3.MockResponse = delegate.dispatch(request.unwrap()).wrap()\n\n override fun peek(): mockwebserver3.MockResponse = delegate.peek().wrap()\n\n override fun close() {\n delegate.shutdown()\n }\n }\n}"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt","line":31,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"override fun dispatch(request: mockwebserver3.RecordedRequest): mockwebserver3.MockResponse = delegate.dispatch(request.unwrap()).wrap()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt","line":33,"symbol":"peek","kind":"function","lang":"kotlin","code":"override fun peek(): mockwebserver3.MockResponse = delegate.peek().wrap()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt","line":35,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n delegate.shutdown()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt","line":41,"symbol":"wrap","kind":"function","lang":"kotlin","code":"internal fun MockResponse.wrap(): mockwebserver3.MockResponse {\n val result = mockwebserver3.MockResponse.Builder()\n val copyFromWebSocketListener = webSocketListener\n if (copyFromWebSocketListener != null) {\n result.webSocketUpgrade(copyFromWebSocketListener)\n }\n\n val body = getBody()\n if (body != null) result.body(body)\n\n for (pushPromise in pushPromises) {\n result.addPush(pushPromise.wrap())\n }\n\n result.settings(settings)\n result.status(status)\n result.headers(headers)\n result.trailers(trailers)\n\n when (socketPolicy) {\n SocketPolicy.EXPECT_CONTINUE, SocketPolicy.CONTINUE_ALWAYS -> {\n result.add100Continue()\n }\n\n SocketPolicy.UPGRADE_TO_SSL_AT_END -> {\n result.inTunnel()\n }\n\n SocketPolicy.SHUTDOWN_SERVER_AFTER_RESPONSE -> {\n result.shutdownServer(true)\n }\n\n SocketPolicy.KEEP_OPEN -> {\n Unit\n }\n\n SocketPolicy.DISCONNECT_AT_END -> {\n result.onResponseEnd(ShutdownConnection)\n }\n\n SocketPolicy.DISCONNECT_AT_START -> {\n result.onRequestStart(CloseSocket())\n }\n\n SocketPolicy.DISCONNECT_AFTER_REQUEST -> {\n result.onResponseStart(CloseSocket())\n }\n\n SocketPolicy.DISCONNECT_DURING_REQUEST_BO"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt","line":142,"symbol":"wrap","kind":"function","lang":"kotlin","code":"private fun PushPromise.wrap(): mockwebserver3.PushPromise =\n mockwebserver3.PushPromise(\n method = method,\n path = path,\n headers = headers,\n response = response.wrap(),\n )"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/DeprecationBridge.kt","line":150,"symbol":"unwrap","kind":"function","lang":"kotlin","code":"internal fun mockwebserver3.RecordedRequest.unwrap(): RecordedRequest =\n RecordedRequest(\n requestLine = requestLine,\n headers = headers,\n chunkSizes = chunkSizes ?: listOf(),\n bodySize = bodySize,\n body = Buffer().write(body ?: ByteString.EMPTY),\n sequenceNumber = exchangeIndex,\n failure = failure,\n method = method,\n path = target,\n handshake = handshake,\n requestUrl = url,\n )"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/Dispatcher.kt","line":18,"symbol":"Dispatcher","kind":"class","lang":"kotlin","code":"abstract class Dispatcher {\n @Throws(InterruptedException::class)\n abstract fun dispatch(request: RecordedRequest): MockResponse\n\n open fun peek(): MockResponse = MockResponse().apply { this.socketPolicy = SocketPolicy.KEEP_OPEN }\n\n open fun shutdown() {}\n}"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/Dispatcher.kt","line":19,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"@Throws(InterruptedException::class)\n abstract fun dispatch(request: RecordedRequest): MockResponse"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/Dispatcher.kt","line":22,"symbol":"peek","kind":"function","lang":"kotlin","code":"open fun peek(): MockResponse = MockResponse().apply { this.socketPolicy = SocketPolicy.KEEP_OPEN }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/Dispatcher.kt","line":24,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"open fun shutdown() {}"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":26,"symbol":"MockResponse","kind":"class","lang":"kotlin","code":"class MockResponse : Cloneable {\n @set:JvmName(\"status\")\n var status: String = \"\"\n\n private var headersBuilder = Headers.Builder()\n private var trailersBuilder = Headers.Builder()\n\n @set:JvmName(\"headers\")\n var headers: Headers\n get() = headersBuilder.build()\n set(value) {\n this.headersBuilder = value.newBuilder()\n }\n\n @set:JvmName(\"trailers\")\n var trailers: Headers\n get() = trailersBuilder.build()\n set(value) {\n this.trailersBuilder = value.newBuilder()\n }\n\n private var body: Buffer? = null\n\n var throttleBytesPerPeriod: Long = Long.MAX_VALUE\n private set\n private var throttlePeriodAmount = 1L\n private var throttlePeriodUnit = TimeUnit.SECONDS\n\n @set:JvmName(\"socketPolicy\")\n var socketPolicy: SocketPolicy = SocketPolicy.KEEP_OPEN\n\n @set:JvmName(\"http2ErrorCode\")\n var http2ErrorCode: Int = -1\n\n private var bodyDelayAmount = 0L\n private var bodyDelayUnit = TimeUnit.MILLISECONDS\n\n private var headersDelayAmount = 0L\n private var headersDelayUnit = TimeUnit.MILLISECONDS\n\n private var promises = mutableListOf()\n var settings: Settings = Settings()\n private set\n var webSocketListener: WebSocketListener? = null\n priv"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":80,"symbol":"clone","kind":"function","lang":"kotlin","code":"public override fun clone(): MockResponse {\n val result = super.clone() as MockResponse\n result.headersBuilder = headersBuilder.build().newBuilder()\n result.promises = promises.toMutableList()\n return result\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":87,"symbol":"getStatus","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_getStatus\")\n @Deprecated(\n message = \"moved to var\",\n replaceWith = ReplaceWith(expression = \"status\"),\n level = DeprecationLevel.ERROR,\n )\n fun getStatus(): String = status"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":95,"symbol":"setStatus","kind":"function","lang":"kotlin","code":"fun setStatus(status: String) =\n apply {\n this.status = status\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":100,"symbol":"setResponseCode","kind":"function","lang":"kotlin","code":"fun setResponseCode(code: Int): MockResponse {\n val reason =\n when (code) {\n in 100..199 -> \"Informational\"\n in 200..299 -> \"OK\"\n in 300..399 -> \"Redirection\"\n in 400..499 -> \"Client Error\"\n in 500..599 -> \"Server Error\"\n else -> \"Mock Response\"\n }\n return apply { status = \"HTTP/1.1 $code $reason\" }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":113,"symbol":"clearHeaders","kind":"function","lang":"kotlin","code":"fun clearHeaders() =\n apply {\n headersBuilder = Headers.Builder()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":118,"symbol":"addHeader","kind":"function","lang":"kotlin","code":"fun addHeader(header: String) =\n apply {\n headersBuilder.add(header)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":123,"symbol":"addHeader","kind":"function","lang":"kotlin","code":"fun addHeader(\n name: String,\n value: Any,\n ) = apply {\n headersBuilder.add(name, value.toString())\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":130,"symbol":"addHeaderLenient","kind":"function","lang":"kotlin","code":"fun addHeaderLenient(\n name: String,\n value: Any,\n ) = apply {\n addHeaderLenient(headersBuilder, name, value.toString())\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":137,"symbol":"setHeader","kind":"function","lang":"kotlin","code":"fun setHeader(\n name: String,\n value: Any,\n ) = apply {\n removeHeader(name)\n addHeader(name, value)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":145,"symbol":"removeHeader","kind":"function","lang":"kotlin","code":"fun removeHeader(name: String) =\n apply {\n headersBuilder.removeAll(name)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":150,"symbol":"getBody","kind":"function","lang":"kotlin","code":"fun getBody(): Buffer? = body?.clone()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":152,"symbol":"setBody","kind":"function","lang":"kotlin","code":"fun setBody(body: Buffer) =\n apply {\n setHeader(\"Content-Length\", body.size)\n this.body = body.clone() // Defensive copy.\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":158,"symbol":"setBody","kind":"function","lang":"kotlin","code":"fun setBody(body: String): MockResponse = setBody(Buffer().writeUtf8(body))"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":160,"symbol":"setChunkedBody","kind":"function","lang":"kotlin","code":"fun setChunkedBody(\n body: Buffer,\n maxChunkSize: Int,\n ) = apply {\n removeHeader(\"Content-Length\")\n headersBuilder.add(CHUNKED_BODY_HEADER)\n\n val bytesOut = Buffer()\n while (!body.exhausted()) {\n val chunkSize = minOf(body.size, maxChunkSize.toLong())\n bytesOut.writeHexadecimalUnsignedLong(chunkSize)\n bytesOut.writeUtf8(\"\\r\\n\")\n bytesOut.write(body, chunkSize)\n bytesOut.writeUtf8(\"\\r\\n\")\n }\n bytesOut.writeUtf8(\"0\\r\\n\") // Last chunk. Trailers follow!\n this.body = bytesOut\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":179,"symbol":"setChunkedBody","kind":"function","lang":"kotlin","code":"fun setChunkedBody(\n body: String,\n maxChunkSize: Int,\n ): MockResponse = setChunkedBody(Buffer().writeUtf8(body), maxChunkSize)"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":184,"symbol":"getHeaders","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_getHeaders\")\n @Deprecated(\n message = \"moved to var\",\n replaceWith = ReplaceWith(expression = \"headers\"),\n level = DeprecationLevel.ERROR,\n )\n fun getHeaders(): Headers = headers"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":192,"symbol":"setHeaders","kind":"function","lang":"kotlin","code":"fun setHeaders(headers: Headers) = apply { this.headers = headers }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":194,"symbol":"getTrailers","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_getTrailers\")\n @Deprecated(\n message = \"moved to var\",\n replaceWith = ReplaceWith(expression = \"trailers\"),\n level = DeprecationLevel.ERROR,\n )\n fun getTrailers(): Headers = trailers"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":202,"symbol":"setTrailers","kind":"function","lang":"kotlin","code":"fun setTrailers(trailers: Headers) = apply { this.trailers = trailers }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":204,"symbol":"getSocketPolicy","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_getSocketPolicy\")\n @Deprecated(\n message = \"moved to var\",\n replaceWith = ReplaceWith(expression = \"socketPolicy\"),\n level = DeprecationLevel.ERROR,\n )\n fun getSocketPolicy(): SocketPolicy = socketPolicy"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":212,"symbol":"setSocketPolicy","kind":"function","lang":"kotlin","code":"fun setSocketPolicy(socketPolicy: SocketPolicy) =\n apply {\n this.socketPolicy = socketPolicy\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":217,"symbol":"getHttp2ErrorCode","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_getHttp2ErrorCode\")\n @Deprecated(\n message = \"moved to var\",\n replaceWith = ReplaceWith(expression = \"http2ErrorCode\"),\n level = DeprecationLevel.ERROR,\n )\n fun getHttp2ErrorCode(): Int = http2ErrorCode"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":225,"symbol":"setHttp2ErrorCode","kind":"function","lang":"kotlin","code":"fun setHttp2ErrorCode(http2ErrorCode: Int) =\n apply {\n this.http2ErrorCode = http2ErrorCode\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":230,"symbol":"throttleBody","kind":"function","lang":"kotlin","code":"fun throttleBody(\n bytesPerPeriod: Long,\n period: Long,\n unit: TimeUnit,\n ) = apply {\n throttleBytesPerPeriod = bytesPerPeriod\n throttlePeriodAmount = period\n throttlePeriodUnit = unit\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":240,"symbol":"getThrottlePeriod","kind":"function","lang":"kotlin","code":"fun getThrottlePeriod(unit: TimeUnit): Long = unit.convert(throttlePeriodAmount, throttlePeriodUnit)"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":242,"symbol":"setBodyDelay","kind":"function","lang":"kotlin","code":"fun setBodyDelay(\n delay: Long,\n unit: TimeUnit,\n ) = apply {\n bodyDelayAmount = delay\n bodyDelayUnit = unit\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":250,"symbol":"getBodyDelay","kind":"function","lang":"kotlin","code":"fun getBodyDelay(unit: TimeUnit): Long = unit.convert(bodyDelayAmount, bodyDelayUnit)"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":252,"symbol":"setHeadersDelay","kind":"function","lang":"kotlin","code":"fun setHeadersDelay(\n delay: Long,\n unit: TimeUnit,\n ) = apply {\n headersDelayAmount = delay\n headersDelayUnit = unit\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":260,"symbol":"getHeadersDelay","kind":"function","lang":"kotlin","code":"fun getHeadersDelay(unit: TimeUnit): Long = unit.convert(headersDelayAmount, headersDelayUnit)"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":262,"symbol":"withPush","kind":"function","lang":"kotlin","code":"fun withPush(promise: PushPromise) =\n apply {\n promises.add(promise)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":267,"symbol":"withSettings","kind":"function","lang":"kotlin","code":"fun withSettings(settings: Settings) =\n apply {\n this.settings = settings\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":272,"symbol":"withWebSocketUpgrade","kind":"function","lang":"kotlin","code":"fun withWebSocketUpgrade(listener: WebSocketListener) =\n apply {\n status = \"HTTP/1.1 101 Switching Protocols\"\n setHeader(\"Connection\", \"Upgrade\")\n setHeader(\"Upgrade\", \"websocket\")\n body = null\n webSocketListener = listener\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockResponse.kt","line":281,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = status"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":31,"symbol":"MockWebServer","kind":"class","lang":"kotlin","code":"class MockWebServer :\n ExternalResource(),\n Closeable {\n val delegate = mockwebserver3.MockWebServer()\n\n val requestCount: Int by delegate::requestCount\n\n var bodyLimit: Long by delegate::bodyLimit\n\n var serverSocketFactory: ServerSocketFactory? by delegate::serverSocketFactory\n\n var dispatcher: Dispatcher = QueueDispatcher()\n set(value) {\n field = value\n delegate.dispatcher = value.wrap()\n }\n\n val port: Int\n get() {\n before() // This implicitly starts the delegate.\n return delegate.port\n }\n\n val hostName: String\n get() {\n before() // This implicitly starts the delegate.\n return delegate.hostName\n }\n\n var protocolNegotiationEnabled: Boolean by delegate::protocolNegotiationEnabled\n\n @get:JvmName(\"protocols\")\n var protocols: List by delegate::protocols\n\n init {\n delegate.dispatcher = dispatcher.wrap()\n }\n\n private var started: Boolean = false\n\n @Synchronized override fun before() {\n if (started) return\n try {\n start()\n } catch (e: IOException) {\n throw RuntimeException(e)\n }\n }\n\n @JvmName(\"-deprecated_port\")\n fun getPort(): Int = port\n\n fun toProxyAddress(): Proxy {\n before() // "} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":71,"symbol":"before","kind":"function","lang":"kotlin","code":"@Synchronized override fun before() {\n if (started) return\n try {\n start()\n } catch (e: IOException) {\n throw RuntimeException(e)\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":80,"symbol":"getPort","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_port\")\n fun getPort(): Int = port"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":83,"symbol":"toProxyAddress","kind":"function","lang":"kotlin","code":"fun toProxyAddress(): Proxy {\n before() // This implicitly starts the delegate.\n return delegate.proxyAddress\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":88,"symbol":"setServerSocketFactory","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_serverSocketFactory\")\n fun setServerSocketFactory(serverSocketFactory: ServerSocketFactory) {\n delegate.serverSocketFactory = serverSocketFactory\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":93,"symbol":"url","kind":"function","lang":"kotlin","code":"fun url(path: String): HttpUrl {\n before() // This implicitly starts the delegate.\n return delegate.url(path)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":98,"symbol":"setBodyLimit","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_bodyLimit\")\n fun setBodyLimit(bodyLimit: Long) {\n delegate.bodyLimit = bodyLimit\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":103,"symbol":"setProtocolNegotiationEnabled","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_protocolNegotiationEnabled\")\n fun setProtocolNegotiationEnabled(protocolNegotiationEnabled: Boolean) {\n delegate.protocolNegotiationEnabled = protocolNegotiationEnabled\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":108,"symbol":"setProtocols","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_protocols\")\n fun setProtocols(protocols: List) {\n delegate.protocols = protocols\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":113,"symbol":"protocols","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_protocols\")\n fun protocols(): List = delegate.protocols"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":116,"symbol":"useHttps","kind":"function","lang":"kotlin","code":"fun useHttps(\n sslSocketFactory: SSLSocketFactory,\n tunnelProxy: Boolean,\n ) {\n delegate.useHttps(sslSocketFactory)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":123,"symbol":"noClientAuth","kind":"function","lang":"kotlin","code":"fun noClientAuth() {\n delegate.noClientAuth()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":127,"symbol":"requestClientAuth","kind":"function","lang":"kotlin","code":"fun requestClientAuth() {\n delegate.requestClientAuth()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":131,"symbol":"requireClientAuth","kind":"function","lang":"kotlin","code":"fun requireClientAuth() {\n delegate.requireClientAuth()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":135,"symbol":"takeRequest","kind":"function","lang":"kotlin","code":"@Throws(InterruptedException::class)\n fun takeRequest(): RecordedRequest = delegate.takeRequest().unwrap()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":138,"symbol":"takeRequest","kind":"function","lang":"kotlin","code":"@Throws(InterruptedException::class)\n fun takeRequest(\n timeout: Long,\n unit: TimeUnit,\n ): RecordedRequest? = delegate.takeRequest(timeout, unit)?.unwrap()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":144,"symbol":"getRequestCount","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_requestCount\")\n fun getRequestCount(): Int = delegate.requestCount"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":147,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"fun enqueue(response: MockResponse) {\n delegate.enqueue(response.wrap())\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":151,"symbol":"start","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n @JvmOverloads\n fun start(port: Int = 0) {\n started = true\n delegate.start(port)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":158,"symbol":"start","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun start(\n inetAddress: InetAddress,\n port: Int,\n ) {\n started = true\n delegate.start(inetAddress, port)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":167,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"@Synchronized\n @Throws(IOException::class)\n fun shutdown() {\n delegate.close()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":173,"symbol":"after","kind":"function","lang":"kotlin","code":"@Synchronized override fun after() {\n try {\n shutdown()\n } catch (e: IOException) {\n logger.log(Level.WARNING, \"MockWebServer shutdown failed\", e)\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":181,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = delegate.toString()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/MockWebServer.kt","line":183,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() = delegate.close()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/PushPromise.kt","line":20,"symbol":"PushPromise","kind":"class","lang":"kotlin","code":"class PushPromise(\n @get:JvmName(\"method\") val method: String,\n @get:JvmName(\"path\") val path: String,\n @get:JvmName(\"headers\") val headers: Headers,\n @get:JvmName(\"response\") val response: MockResponse,\n) {\n @JvmName(\"-deprecated_method\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"method\"),\n level = DeprecationLevel.ERROR,\n )\n fun method(): String = method\n\n @JvmName(\"-deprecated_path\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"path\"),\n level = DeprecationLevel.ERROR,\n )\n fun path(): String = path\n\n @JvmName(\"-deprecated_headers\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"headers\"),\n level = DeprecationLevel.ERROR,\n )\n fun headers(): Headers = headers\n\n @JvmName(\"-deprecated_response\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"response\"),\n level = DeprecationLevel.ERROR,\n )\n fun response(): MockResponse = response\n}"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/PushPromise.kt","line":26,"symbol":"method","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_method\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"method\"),\n level = DeprecationLevel.ERROR,\n )\n fun method(): String = method"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/PushPromise.kt","line":34,"symbol":"path","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_path\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"path\"),\n level = DeprecationLevel.ERROR,\n )\n fun path(): String = path"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/PushPromise.kt","line":42,"symbol":"headers","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_headers\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"headers\"),\n level = DeprecationLevel.ERROR,\n )\n fun headers(): Headers = headers"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/PushPromise.kt","line":50,"symbol":"response","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_response\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"response\"),\n level = DeprecationLevel.ERROR,\n )\n fun response(): MockResponse = response"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt","line":20,"symbol":"QueueDispatcher","kind":"class","lang":"kotlin","code":"class QueueDispatcher : Dispatcher() {\n internal val delegate = QueueDispatcher()\n\n @Throws(InterruptedException::class)\n override fun dispatch(request: RecordedRequest): MockResponse = throw UnsupportedOperationException(\"unexpected call\")\n\n override fun peek(): MockResponse = throw UnsupportedOperationException(\"unexpected call\")\n\n fun enqueueResponse(response: MockResponse) {\n delegate.enqueue(response.wrap())\n }\n\n override fun shutdown() {\n delegate.close()\n }\n\n fun setFailFast(failFast: Boolean) {\n delegate.setFailFast(failFast)\n }\n\n fun setFailFast(failFastResponse: MockResponse?) {\n delegate.setFailFast(failFastResponse?.wrap())\n }\n}"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt","line":23,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"@Throws(InterruptedException::class)\n override fun dispatch(request: RecordedRequest): MockResponse = throw UnsupportedOperationException(\"unexpected call\")"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt","line":26,"symbol":"peek","kind":"function","lang":"kotlin","code":"override fun peek(): MockResponse = throw UnsupportedOperationException(\"unexpected call\")"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt","line":28,"symbol":"enqueueResponse","kind":"function","lang":"kotlin","code":"fun enqueueResponse(response: MockResponse) {\n delegate.enqueue(response.wrap())\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt","line":32,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"override fun shutdown() {\n delegate.close()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt","line":36,"symbol":"setFailFast","kind":"function","lang":"kotlin","code":"fun setFailFast(failFast: Boolean) {\n delegate.setFailFast(failFast)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/QueueDispatcher.kt","line":40,"symbol":"setFailFast","kind":"function","lang":"kotlin","code":"fun setFailFast(failFastResponse: MockResponse?) {\n delegate.setFailFast(failFastResponse?.wrap())\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/RecordedRequest.kt","line":30,"symbol":"RecordedRequest","kind":"class","lang":"kotlin","code":"class RecordedRequest {\n val requestLine: String\n val headers: Headers\n val chunkSizes: List\n val bodySize: Long\n val body: Buffer\n val sequenceNumber: Int\n val failure: IOException?\n val method: String?\n val path: String?\n val handshake: Handshake?\n val requestUrl: HttpUrl?\n\n @get:JvmName(\"-deprecated_utf8Body\")\n @Deprecated(\n message = \"Use body.readUtf8()\",\n replaceWith = ReplaceWith(\"body.readUtf8()\"),\n level = DeprecationLevel.ERROR,\n )\n val utf8Body: String\n get() = body.readUtf8()\n\n val tlsVersion: TlsVersion?\n get() = handshake?.tlsVersion\n\n internal constructor(\n requestLine: String,\n headers: Headers,\n chunkSizes: List,\n bodySize: Long,\n body: Buffer,\n sequenceNumber: Int,\n failure: IOException?,\n method: String?,\n path: String?,\n handshake: Handshake?,\n requestUrl: HttpUrl?,\n ) {\n this.requestLine = requestLine\n this.headers = headers\n this.chunkSizes = chunkSizes\n this.bodySize = bodySize\n this.body = body\n this.sequenceNumber = sequenceNumber\n this.failure = failure\n this.method = method\n this.path = path\n this.handshake = handshake\n this.requestUrl = requestUrl"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/RecordedRequest.kt","line":142,"symbol":"getUtf8Body","kind":"function","lang":"kotlin","code":"@Deprecated(\n message = \"Use body.readUtf8()\",\n replaceWith = ReplaceWith(\"body.readUtf8()\"),\n level = DeprecationLevel.WARNING,\n )\n fun getUtf8Body(): String = body.readUtf8()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/RecordedRequest.kt","line":149,"symbol":"getHeader","kind":"function","lang":"kotlin","code":"fun getHeader(name: String): String? = headers.values(name).firstOrNull()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/RecordedRequest.kt","line":151,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = requestLine"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":18,"symbol":"SocketPolicy","kind":"enum","lang":"kotlin","code":"enum class SocketPolicy {\n SHUTDOWN_SERVER_AFTER_RESPONSE,\n KEEP_OPEN,\n DISCONNECT_AT_END,\n UPGRADE_TO_SSL_AT_END,\n DISCONNECT_AT_START,\n DISCONNECT_AFTER_REQUEST,\n DISCONNECT_DURING_REQUEST_BODY,\n DISCONNECT_DURING_RESPONSE_BODY,\n DO_NOT_READ_REQUEST_BODY,\n FAIL_HANDSHAKE,\n SHUTDOWN_INPUT_AT_END,\n SHUTDOWN_OUTPUT_AT_END,\n STALL_SOCKET_AT_START,\n NO_RESPONSE,\n RESET_STREAM_AT_START,\n EXPECT_CONTINUE,\n CONTINUE_ALWAYS,\n}"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":19,"symbol":"SHUTDOWN_SERVER_AFTER_RESPONSE","kind":"enum_member","lang":"kotlin","code":"SHUTDOWN_SERVER_AFTER_RESPONSE"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":20,"symbol":"KEEP_OPEN","kind":"enum_member","lang":"kotlin","code":"KEEP_OPEN"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":21,"symbol":"DISCONNECT_AT_END","kind":"enum_member","lang":"kotlin","code":"DISCONNECT_AT_END"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":22,"symbol":"UPGRADE_TO_SSL_AT_END","kind":"enum_member","lang":"kotlin","code":"UPGRADE_TO_SSL_AT_END"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":23,"symbol":"DISCONNECT_AT_START","kind":"enum_member","lang":"kotlin","code":"DISCONNECT_AT_START"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":24,"symbol":"DISCONNECT_AFTER_REQUEST","kind":"enum_member","lang":"kotlin","code":"DISCONNECT_AFTER_REQUEST"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":25,"symbol":"DISCONNECT_DURING_REQUEST_BODY","kind":"enum_member","lang":"kotlin","code":"DISCONNECT_DURING_REQUEST_BODY"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":26,"symbol":"DISCONNECT_DURING_RESPONSE_BODY","kind":"enum_member","lang":"kotlin","code":"DISCONNECT_DURING_RESPONSE_BODY"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":27,"symbol":"DO_NOT_READ_REQUEST_BODY","kind":"enum_member","lang":"kotlin","code":"DO_NOT_READ_REQUEST_BODY"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":28,"symbol":"FAIL_HANDSHAKE","kind":"enum_member","lang":"kotlin","code":"FAIL_HANDSHAKE"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":29,"symbol":"SHUTDOWN_INPUT_AT_END","kind":"enum_member","lang":"kotlin","code":"SHUTDOWN_INPUT_AT_END"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":30,"symbol":"SHUTDOWN_OUTPUT_AT_END","kind":"enum_member","lang":"kotlin","code":"SHUTDOWN_OUTPUT_AT_END"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":31,"symbol":"STALL_SOCKET_AT_START","kind":"enum_member","lang":"kotlin","code":"STALL_SOCKET_AT_START"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":32,"symbol":"NO_RESPONSE","kind":"enum_member","lang":"kotlin","code":"NO_RESPONSE"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":33,"symbol":"RESET_STREAM_AT_START","kind":"enum_member","lang":"kotlin","code":"RESET_STREAM_AT_START"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":34,"symbol":"EXPECT_CONTINUE","kind":"enum_member","lang":"kotlin","code":"EXPECT_CONTINUE"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/main/kotlin/okhttp3/mockwebserver/SocketPolicy.kt","line":35,"symbol":"CONTINUE_ALWAYS","kind":"enum_member","lang":"kotlin","code":"CONTINUE_ALWAYS"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":40,"symbol":"KotlinSourceModernTest","kind":"class","lang":"kotlin","doc":"Access every type, function, and property from Kotlin to defend against unexpected regressions in modern 4.0.x kotlin source-compatibility.","code":"@Suppress(\n \"ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE\",\n \"UNUSED_ANONYMOUS_PARAMETER\",\n \"UNUSED_VALUE\",\n \"UNUSED_VARIABLE\",\n \"VARIABLE_WITH_REDUNDANT_INITIALIZER\",\n \"RedundantLambdaArrow\",\n \"RedundantExplicitType\",\n \"IMPLICIT_NOTHING_AS_TYPE_PARAMETER\",\n)\nclass KotlinSourceModernTest {\n @Test @Ignore\n fun dispatcherFromMockWebServer() {\n val dispatcher =\n object : Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse = TODO()\n\n override fun peek(): MockResponse = TODO()\n\n override fun shutdown() = TODO()\n }\n }\n\n @Test @Ignore\n fun mockResponse() {\n var mockResponse: MockResponse = MockResponse()\n var status: String = mockResponse.status\n status = mockResponse.status\n mockResponse.status = \"\"\n mockResponse = mockResponse.setResponseCode(0)\n var headers: Headers = mockResponse.headers\n var trailers: Headers = mockResponse.trailers\n mockResponse = mockResponse.clearHeaders()\n mockResponse = mockResponse.addHeader(\"\")\n mockResponse = mockResponse.addHeader(\"\", \"\")\n mockResponse = mockResponse.addHeaderLenient(\"\", Any())\n mockResponse = mockResponse.setHeader(\"\", Any())\n mockRespons"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":51,"symbol":"dispatcherFromMockWebServer","kind":"function","lang":"kotlin","code":"@Test @Ignore\n fun dispatcherFromMockWebServer() {\n val dispatcher =\n object : Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse = TODO()\n\n override fun peek(): MockResponse = TODO()\n\n override fun shutdown() = TODO()\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":55,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"override fun dispatch(request: RecordedRequest): MockResponse = TODO()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":57,"symbol":"peek","kind":"function","lang":"kotlin","code":"override fun peek(): MockResponse = TODO()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":59,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"override fun shutdown() = TODO()"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":63,"symbol":"mockResponse","kind":"function","lang":"kotlin","code":"@Test @Ignore\n fun mockResponse() {\n var mockResponse: MockResponse = MockResponse()\n var status: String = mockResponse.status\n status = mockResponse.status\n mockResponse.status = \"\"\n mockResponse = mockResponse.setResponseCode(0)\n var headers: Headers = mockResponse.headers\n var trailers: Headers = mockResponse.trailers\n mockResponse = mockResponse.clearHeaders()\n mockResponse = mockResponse.addHeader(\"\")\n mockResponse = mockResponse.addHeader(\"\", \"\")\n mockResponse = mockResponse.addHeaderLenient(\"\", Any())\n mockResponse = mockResponse.setHeader(\"\", Any())\n mockResponse.headers = headersOf()\n mockResponse.trailers = headersOf()\n mockResponse = mockResponse.removeHeader(\"\")\n var body: Buffer? = mockResponse.getBody()\n mockResponse = mockResponse.setBody(Buffer())\n mockResponse = mockResponse.setChunkedBody(Buffer(), 0)\n mockResponse = mockResponse.setChunkedBody(\"\", 0)\n var socketPolicy: SocketPolicy = mockResponse.socketPolicy\n mockResponse.socketPolicy = SocketPolicy.KEEP_OPEN\n var http2ErrorCode: Int = mockResponse.http2ErrorCode\n mockResponse.http2ErrorCode = 0\n mockResponse = mockResponse.throttleBody(0L,"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":111,"symbol":"mockWebServer","kind":"function","lang":"kotlin","code":"@Test @Ignore\n fun mockWebServer() {\n val mockWebServer: MockWebServer = MockWebServer()\n var port: Int = mockWebServer.port\n var hostName: String = mockWebServer.hostName\n hostName = mockWebServer.hostName\n val toProxyAddress: Proxy = mockWebServer.toProxyAddress()\n mockWebServer.serverSocketFactory = ServerSocketFactory.getDefault()\n val url: HttpUrl = mockWebServer.url(\"\")\n mockWebServer.bodyLimit = 0L\n mockWebServer.protocolNegotiationEnabled = false\n mockWebServer.protocols = listOf()\n val protocols: List = mockWebServer.protocols\n mockWebServer.useHttps(SSLSocketFactory.getDefault() as SSLSocketFactory, false)\n mockWebServer.noClientAuth()\n mockWebServer.requestClientAuth()\n mockWebServer.requireClientAuth()\n val request: RecordedRequest = mockWebServer.takeRequest()\n val nullableRequest: RecordedRequest? = mockWebServer.takeRequest(0L, TimeUnit.SECONDS)\n var requestCount: Int = mockWebServer.requestCount\n mockWebServer.enqueue(MockResponse())\n mockWebServer.start()\n mockWebServer.start(0)\n mockWebServer.start(InetAddress.getLocalHost(), 0)\n mockWebServer.shutdown()\n var dispatcher: Dispatcher "} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":143,"symbol":"pushPromise","kind":"function","lang":"kotlin","code":"@Test @Ignore\n fun pushPromise() {\n val pushPromise: PushPromise = PushPromise(\"\", \"\", headersOf(), MockResponse())\n val method: String = pushPromise.method\n val path: String = pushPromise.path\n val headers: Headers = pushPromise.headers\n val response: MockResponse = pushPromise.response\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":152,"symbol":"queueDispatcher","kind":"function","lang":"kotlin","code":"@Test @Ignore\n fun queueDispatcher() {\n val queueDispatcher: QueueDispatcher = QueueDispatcher()\n var mockResponse: MockResponse =\n queueDispatcher.dispatch(\n RecordedRequest(\"\", headersOf(), listOf(), 0L, Buffer(), 0, Socket()),\n )\n mockResponse = queueDispatcher.peek()\n queueDispatcher.enqueueResponse(MockResponse())\n queueDispatcher.shutdown()\n queueDispatcher.setFailFast(false)\n queueDispatcher.setFailFast(MockResponse())\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":166,"symbol":"recordedRequest","kind":"function","lang":"kotlin","code":"@Test @Ignore\n fun recordedRequest() {\n var recordedRequest: RecordedRequest =\n RecordedRequest(\n \"\",\n headersOf(),\n listOf(),\n 0L,\n Buffer(),\n 0,\n Socket(),\n )\n recordedRequest = RecordedRequest(\"\", headersOf(), listOf(), 0L, Buffer(), 0, Socket())\n var requestUrl: HttpUrl? = recordedRequest.requestUrl\n var requestLine: String = recordedRequest.requestLine\n var method: String? = recordedRequest.method\n var path: String? = recordedRequest.path\n var headers: Headers = recordedRequest.headers\n val header: String? = recordedRequest.getHeader(\"\")\n var chunkSizes: List = recordedRequest.chunkSizes\n var bodySize: Long = recordedRequest.bodySize\n var body: Buffer = recordedRequest.body\n var utf8Body: String = recordedRequest.body.readUtf8()\n var sequenceNumber: Int = recordedRequest.sequenceNumber\n var tlsVersion: TlsVersion? = recordedRequest.tlsVersion\n var handshake: Handshake? = recordedRequest.handshake\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/KotlinSourceModernTest.kt","line":194,"symbol":"socketPolicy","kind":"function","lang":"kotlin","code":"@Test @Ignore\n fun socketPolicy() {\n val socketPolicy: SocketPolicy = SocketPolicy.KEEP_OPEN\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":62,"symbol":"MockWebServerTest","kind":"class","lang":"kotlin","code":"@Suppress(\"deprecation\")\n@Timeout(30)\n@Tag(\"Slow\")\nclass MockWebServerTest {\n @RegisterExtension\n var platform = PlatformRule()\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n server.start()\n }\n\n @AfterEach\n fun tearDown() {\n server.shutdown()\n }\n\n @Test\n fun defaultMockResponse() {\n val response = MockResponse()\n assertThat(headersToList(response)).containsExactly(\"Content-Length: 0\")\n assertThat(response.status).isEqualTo(\"HTTP/1.1 200 OK\")\n }\n\n @Test\n fun setResponseMockReason() {\n val reasons =\n arrayOf(\n \"Mock Response\",\n \"Informational\",\n \"OK\",\n \"Redirection\",\n \"Client Error\",\n \"Server Error\",\n \"Mock Response\",\n )\n for (i in 0..599) {\n val response = MockResponse().setResponseCode(i)\n val expectedReason = reasons[i / 100]\n assertThat(response.status).isEqualTo(\"HTTP/1.1 $i $expectedReason\")\n assertThat(headersToList(response)).containsExactly(\"Content-Length: 0\")\n }\n }\n\n @Test\n fun setStatusControlsWholeStatusLine() {\n val response = MockResponse().setStatus(\"HTTP/1.1 202 That'll do pig\")\n assertThat(headersToList(response)).contain"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":70,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n server.start()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":75,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n server.shutdown()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":80,"symbol":"defaultMockResponse","kind":"function","lang":"kotlin","code":"@Test\n fun defaultMockResponse() {\n val response = MockResponse()\n assertThat(headersToList(response)).containsExactly(\"Content-Length: 0\")\n assertThat(response.status).isEqualTo(\"HTTP/1.1 200 OK\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":87,"symbol":"setResponseMockReason","kind":"function","lang":"kotlin","code":"@Test\n fun setResponseMockReason() {\n val reasons =\n arrayOf(\n \"Mock Response\",\n \"Informational\",\n \"OK\",\n \"Redirection\",\n \"Client Error\",\n \"Server Error\",\n \"Mock Response\",\n )\n for (i in 0..599) {\n val response = MockResponse().setResponseCode(i)\n val expectedReason = reasons[i / 100]\n assertThat(response.status).isEqualTo(\"HTTP/1.1 $i $expectedReason\")\n assertThat(headersToList(response)).containsExactly(\"Content-Length: 0\")\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":107,"symbol":"setStatusControlsWholeStatusLine","kind":"function","lang":"kotlin","code":"@Test\n fun setStatusControlsWholeStatusLine() {\n val response = MockResponse().setStatus(\"HTTP/1.1 202 That'll do pig\")\n assertThat(headersToList(response)).containsExactly(\"Content-Length: 0\")\n assertThat(response.status).isEqualTo(\"HTTP/1.1 202 That'll do pig\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":114,"symbol":"setBodyAdjustsHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun setBodyAdjustsHeaders() {\n val response = MockResponse().setBody(\"ABC\")\n assertThat(headersToList(response)).containsExactly(\"Content-Length: 3\")\n assertThat(response.getBody()!!.readUtf8()).isEqualTo(\"ABC\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":121,"symbol":"mockResponseAddHeader","kind":"function","lang":"kotlin","code":"@Test\n fun mockResponseAddHeader() {\n val response =\n MockResponse()\n .clearHeaders()\n .addHeader(\"Cookie: s=square\")\n .addHeader(\"Cookie\", \"a=android\")\n assertThat(headersToList(response))\n .containsExactly(\"Cookie: s=square\", \"Cookie: a=android\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":132,"symbol":"mockResponseSetHeader","kind":"function","lang":"kotlin","code":"@Test\n fun mockResponseSetHeader() {\n val response =\n MockResponse()\n .clearHeaders()\n .addHeader(\"Cookie: s=square\")\n .addHeader(\"Cookie: a=android\")\n .addHeader(\"Cookies: delicious\")\n response.setHeader(\"cookie\", \"r=robot\")\n assertThat(headersToList(response))\n .containsExactly(\"Cookies: delicious\", \"cookie: r=robot\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":145,"symbol":"mockResponseSetHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun mockResponseSetHeaders() {\n val response =\n MockResponse()\n .clearHeaders()\n .addHeader(\"Cookie: s=square\")\n .addHeader(\"Cookies: delicious\")\n response.setHeaders(Headers.Builder().add(\"Cookie\", \"a=android\").build())\n assertThat(headersToList(response)).containsExactly(\"Cookie: a=android\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":156,"symbol":"regularResponse","kind":"function","lang":"kotlin","code":"@Test\n fun regularResponse() {\n server.enqueue(MockResponse().setBody(\"hello world\"))\n val url = server.url(\"/\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n connection.setRequestProperty(\"Accept-Language\", \"en-US\")\n val inputStream = connection.inputStream\n val reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))\n assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK)\n assertThat(reader.readLine()).isEqualTo(\"hello world\")\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"GET / HTTP/1.1\")\n assertThat(request.getHeader(\"Accept-Language\")).isEqualTo(\"en-US\")\n\n // Server has no more requests.\n assertThat(server.takeRequest(100, TimeUnit.MILLISECONDS)).isNull()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":174,"symbol":"redirect","kind":"function","lang":"kotlin","code":"@Test\n fun redirect() {\n server.enqueue(\n MockResponse()\n .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)\n .addHeader(\"Location: \" + server.url(\"/new-path\"))\n .setBody(\"This page has moved!\"),\n )\n server.enqueue(MockResponse().setBody(\"This is the new location!\"))\n val connection = server.url(\"/\").toUrl().openConnection()\n val inputStream = connection.getInputStream()\n val reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"This is the new location!\")\n val first = server.takeRequest()\n assertThat(first.requestLine).isEqualTo(\"GET / HTTP/1.1\")\n val redirect = server.takeRequest()\n assertThat(redirect.requestLine).isEqualTo(\"GET /new-path HTTP/1.1\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":197,"symbol":"dispatchBlocksWaitingForEnqueue","kind":"function","lang":"kotlin","doc":"Test that MockWebServer blocks for a call to enqueue() if a request is made before a mock response is ready.","code":"@Test\n fun dispatchBlocksWaitingForEnqueue() {\n Thread {\n try {\n Thread.sleep(1000)\n } catch (ignored: InterruptedException) {\n }\n server.enqueue(MockResponse().setBody(\"enqueued in the background\"))\n }.start()\n val connection = server.url(\"/\").toUrl().openConnection()\n val inputStream = connection.getInputStream()\n val reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"enqueued in the background\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":212,"symbol":"nonHexadecimalChunkSize","kind":"function","lang":"kotlin","code":"@Test\n fun nonHexadecimalChunkSize() {\n server.enqueue(\n MockResponse()\n .setBody(\"G\\r\\nxxxxxxxxxxxxxxxx\\r\\n0\\r\\n\\r\\n\")\n .clearHeaders()\n .addHeader(\"Transfer-encoding: chunked\"),\n )\n val connection = server.url(\"/\").toUrl().openConnection()\n val inputStream = connection.getInputStream()\n try {\n inputStream.read()\n fail()\n } catch (expected: IOException) {\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":229,"symbol":"responseTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun responseTimeout() {\n server.enqueue(\n MockResponse()\n .setBody(\"ABC\")\n .clearHeaders()\n .addHeader(\"Content-Length: 4\"),\n )\n server.enqueue(MockResponse().setBody(\"DEF\"))\n val urlConnection = server.url(\"/\").toUrl().openConnection()\n urlConnection.setReadTimeout(1000)\n val inputStream = urlConnection.getInputStream()\n assertThat(inputStream.read()).isEqualTo('A'.code)\n assertThat(inputStream.read()).isEqualTo('B'.code)\n assertThat(inputStream.read()).isEqualTo('C'.code)\n try {\n inputStream.read() // if Content-Length was accurate, this would return -1 immediately\n fail()\n } catch (expected: SocketTimeoutException) {\n }\n val urlConnection2 = server.url(\"/\").toUrl().openConnection()\n val in2 = urlConnection2.getInputStream()\n assertThat(in2.read()).isEqualTo('D'.code)\n assertThat(in2.read()).isEqualTo('E'.code)\n assertThat(in2.read()).isEqualTo('F'.code)\n assertThat(in2.read()).isEqualTo(-1)\n assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)\n assertThat(server.takeRequest().sequenceNumber).isEqualTo(0)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":259,"symbol":"disconnectAtStart","kind":"function","lang":"kotlin","code":"@Disabled(\"Not actually failing where expected\")\n @Test\n fun disconnectAtStart() {\n server.enqueue(\n MockResponse()\n .setSocketPolicy(SocketPolicy.DISCONNECT_AT_START),\n )\n server.enqueue(MockResponse()) // The jdk's HttpUrlConnection is a bastard.\n server.enqueue(MockResponse())\n try {\n server\n .url(\"/a\")\n .toUrl()\n .openConnection()\n .getInputStream()\n fail()\n } catch (expected: IOException) {\n }\n server\n .url(\"/b\")\n .toUrl()\n .openConnection()\n .getInputStream() // Should succeed.\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":288,"symbol":"throttleRequest","kind":"function","lang":"kotlin","doc":"Throttle the request body by sleeping 500ms after every 3 bytes. With a 6-byte request, this should yield one sleep for a total delay of 500ms.","code":"@Test\n fun throttleRequest() {\n assumeNotWindows()\n server.enqueue(\n MockResponse()\n .throttleBody(3, 500, TimeUnit.MILLISECONDS),\n )\n val startNanos = System.nanoTime()\n val connection = server.url(\"/\").toUrl().openConnection()\n connection.setDoOutput(true)\n connection.getOutputStream().write(\"ABCDEF\".toByteArray(StandardCharsets.UTF_8))\n val inputStream = connection.getInputStream()\n assertThat(inputStream.read()).isEqualTo(-1)\n val elapsedNanos = System.nanoTime() - startNanos\n val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos)\n assertThat(elapsedMillis).isBetween(500L, 1000L)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":310,"symbol":"throttleResponse","kind":"function","lang":"kotlin","doc":"Throttle the response body by sleeping 500ms after every 3 bytes. With a 6-byte response, this should yield one sleep for a total delay of 500ms.","code":"@Test\n fun throttleResponse() {\n assumeNotWindows()\n server.enqueue(\n MockResponse()\n .setBody(\"ABCDEF\")\n .throttleBody(3, 500, TimeUnit.MILLISECONDS),\n )\n val startNanos = System.nanoTime()\n val connection = server.url(\"/\").toUrl().openConnection()\n val inputStream = connection.getInputStream()\n assertThat(inputStream.read()).isEqualTo('A'.code)\n assertThat(inputStream.read()).isEqualTo('B'.code)\n assertThat(inputStream.read()).isEqualTo('C'.code)\n assertThat(inputStream.read()).isEqualTo('D'.code)\n assertThat(inputStream.read()).isEqualTo('E'.code)\n assertThat(inputStream.read()).isEqualTo('F'.code)\n assertThat(inputStream.read()).isEqualTo(-1)\n val elapsedNanos = System.nanoTime() - startNanos\n val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos)\n assertThat(elapsedMillis).isBetween(500L, 1000L)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":334,"symbol":"delayResponse","kind":"function","lang":"kotlin","doc":"Delay the response body by sleeping 1s.","code":"@Test\n fun delayResponse() {\n assumeNotWindows()\n server.enqueue(\n MockResponse()\n .setBody(\"ABCDEF\")\n .setBodyDelay(1, TimeUnit.SECONDS),\n )\n val startNanos = System.nanoTime()\n val connection = server.url(\"/\").toUrl().openConnection()\n val inputStream = connection.getInputStream()\n assertThat(inputStream.read()).isEqualTo('A'.code)\n val elapsedNanos = System.nanoTime() - startNanos\n val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos)\n assertThat(elapsedMillis).isGreaterThanOrEqualTo(1000L)\n inputStream.close()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":352,"symbol":"disconnectRequestHalfway","kind":"function","lang":"kotlin","code":"@Test\n fun disconnectRequestHalfway() {\n server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_DURING_REQUEST_BODY))\n // Limit the size of the request body that the server holds in memory to an arbitrary\n // 3.5 MBytes so this test can pass on devices with little memory.\n server.bodyLimit = 7 * 512 * 1024\n val connection = server.url(\"/\").toUrl().openConnection() as HttpURLConnection\n connection.setRequestMethod(\"POST\")\n connection.setDoOutput(true)\n connection.setFixedLengthStreamingMode(1024 * 1024 * 1024) // 1 GB\n connection.connect()\n val out = connection.outputStream\n val data = ByteArray(1024 * 1024)\n var i = 0\n while (i < 1024) {\n try {\n out.write(data)\n out.flush()\n if (i == 513) {\n // pause slightly after halfway to make result more predictable\n Thread.sleep(100)\n }\n } catch (e: IOException) {\n break\n }\n i++\n }\n // Halfway +/- 0.5%\n assertThat(i.toFloat()).isCloseTo(512f, 5f)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":383,"symbol":"disconnectResponseHalfway","kind":"function","lang":"kotlin","code":"@Test\n fun disconnectResponseHalfway() {\n server.enqueue(\n MockResponse()\n .setBody(\"ab\")\n .setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY),\n )\n val connection = server.url(\"/\").toUrl().openConnection()\n assertThat(connection.getContentLength()).isEqualTo(2)\n val inputStream = connection.getInputStream()\n assertThat(inputStream.read()).isEqualTo('a'.code)\n try {\n val byteRead = inputStream.read()\n // OpenJDK behavior: end of stream.\n assertThat(byteRead).isEqualTo(-1)\n } catch (e: ProtocolException) {\n // On Android, HttpURLConnection is implemented by OkHttp v2. OkHttp\n // treats an incomplete response body as a ProtocolException.\n } catch (ioe: IOException) {\n // Change in https://bugs.openjdk.org/browse/JDK-8335135\n assertThat(ioe.message).isEqualTo(\"Premature EOF\")\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":407,"symbol":"headersToList","kind":"function","lang":"kotlin","code":"private fun headersToList(response: MockResponse): List {\n val headers = response.headers\n val size = headers.size\n val headerList: MutableList = ArrayList(size)\n for (i in 0 until size) {\n headerList.add(headers.name(i) + \": \" + headers.value(i))\n }\n return headerList\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":417,"symbol":"shutdownWithoutStart","kind":"function","lang":"kotlin","code":"@Test\n fun shutdownWithoutStart() {\n val server = MockWebServer()\n server.shutdown()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":423,"symbol":"closeViaClosable","kind":"function","lang":"kotlin","code":"@Test\n fun closeViaClosable() {\n val server: Closeable = MockWebServer()\n server.close()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":429,"symbol":"shutdownWithoutEnqueue","kind":"function","lang":"kotlin","code":"@Test\n fun shutdownWithoutEnqueue() {\n val server = MockWebServer()\n server.start()\n server.shutdown()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":436,"symbol":"portImplicitlyStarts","kind":"function","lang":"kotlin","code":"@Test\n fun portImplicitlyStarts() {\n assertThat(server.port).isGreaterThan(0)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":441,"symbol":"hostnameImplicitlyStarts","kind":"function","lang":"kotlin","code":"@Test\n fun hostnameImplicitlyStarts() {\n assertThat(server.hostName).isNotNull()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":446,"symbol":"toProxyAddressImplicitlyStarts","kind":"function","lang":"kotlin","code":"@Test\n fun toProxyAddressImplicitlyStarts() {\n assertThat(server.toProxyAddress()).isNotNull()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":451,"symbol":"differentInstancesGetDifferentPorts","kind":"function","lang":"kotlin","code":"@Test\n fun differentInstancesGetDifferentPorts() {\n val other = MockWebServer()\n assertThat(other.port).isNotEqualTo(server.port)\n other.shutdown()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":458,"symbol":"statementStartsAndStops","kind":"function","lang":"kotlin","code":"@Test\n fun statementStartsAndStops() {\n val called = AtomicBoolean()\n val statement =\n server.apply(\n object : Statement() {\n override fun evaluate() {\n called.set(true)\n server\n .url(\"/\")\n .toUrl()\n .openConnection()\n .connect()\n }\n },\n Description.EMPTY,\n )\n statement.evaluate()\n assertThat(called.get()).isTrue()\n try {\n server\n .url(\"/\")\n .toUrl()\n .openConnection()\n .connect()\n fail()\n } catch (expected: ConnectException) {\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":464,"symbol":"evaluate","kind":"function","lang":"kotlin","code":"override fun evaluate() {\n called.set(true)\n server\n .url(\"/\")\n .toUrl()\n .openConnection()\n .connect()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":488,"symbol":"shutdownWhileBlockedDispatching","kind":"function","lang":"kotlin","code":"@Test\n fun shutdownWhileBlockedDispatching() {\n // Enqueue a request that'll cause MockWebServer to hang on QueueDispatcher.dispatch().\n val connection = server.url(\"/\").toUrl().openConnection() as HttpURLConnection\n connection.setReadTimeout(500)\n try {\n connection.getResponseCode()\n fail()\n } catch (expected: SocketTimeoutException) {\n }\n\n // Shutting down the server should unblock the dispatcher.\n server.shutdown()\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":503,"symbol":"requestUrlReconstructed","kind":"function","lang":"kotlin","code":"@Test\n fun requestUrlReconstructed() {\n server.enqueue(MockResponse().setBody(\"hello world\"))\n val url = server.url(\"/a/deep/path?key=foo%20bar\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n val inputStream = connection.inputStream\n val reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))\n assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK)\n assertThat(reader.readLine()).isEqualTo(\"hello world\")\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\n \"GET /a/deep/path?key=foo%20bar HTTP/1.1\",\n )\n assertThat(request.path).isEqualTo(\"/a/deep/path?key=foo%20bar\")\n val requestUrl = request.requestUrl\n assertThat(requestUrl!!.scheme).isEqualTo(\"http\")\n assertThat(requestUrl.host).isEqualTo(server.hostName)\n assertThat(requestUrl.port).isEqualTo(server.port)\n assertThat(requestUrl.encodedPath).isEqualTo(\"/a/deep/path\")\n assertThat(requestUrl.queryParameter(\"key\")).isEqualTo(\"foo bar\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":525,"symbol":"shutdownServerAfterRequest","kind":"function","lang":"kotlin","code":"@Test\n fun shutdownServerAfterRequest() {\n server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.SHUTDOWN_SERVER_AFTER_RESPONSE))\n val url = server.url(\"/\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK)\n val refusedConnection = url.openConnection() as HttpURLConnection\n assertFailsWith {\n refusedConnection.getResponseCode()\n }.also { expected ->\n assertThat(expected.message!!).contains(\"refused\")\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":539,"symbol":"http100Continue","kind":"function","lang":"kotlin","code":"@Test\n fun http100Continue() {\n server.enqueue(MockResponse().setBody(\"response\"))\n val url = server.url(\"/\").toUrl()\n val connection = url.openConnection() as HttpURLConnection\n connection.setDoOutput(true)\n connection.setRequestProperty(\"Expect\", \"100-Continue\")\n connection.outputStream.write(\"request\".toByteArray(StandardCharsets.UTF_8))\n val inputStream = connection.inputStream\n val reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"response\")\n val request = server.takeRequest()\n assertThat(request.body.readUtf8()).isEqualTo(\"request\")\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":554,"symbol":"testH2PriorKnowledgeServerFallback","kind":"function","lang":"kotlin","code":"@Test\n fun testH2PriorKnowledgeServerFallback() {\n try {\n server.protocols = Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1)\n fail()\n } catch (expected: IllegalArgumentException) {\n assertThat(expected.message).isEqualTo(\n \"protocols containing h2_prior_knowledge cannot use other protocols: \" +\n \"[h2_prior_knowledge, http/1.1]\",\n )\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":567,"symbol":"testH2PriorKnowledgeServerDuplicates","kind":"function","lang":"kotlin","code":"@Test\n fun testH2PriorKnowledgeServerDuplicates() {\n try {\n // Treating this use case as user error\n server.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE)\n fail()\n } catch (expected: IllegalArgumentException) {\n assertThat(expected.message).isEqualTo(\n \"protocols containing h2_prior_knowledge cannot use other protocols: \" +\n \"[h2_prior_knowledge, h2_prior_knowledge]\",\n )\n }\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":581,"symbol":"testMockWebServerH2PriorKnowledgeProtocol","kind":"function","lang":"kotlin","code":"@Test\n fun testMockWebServerH2PriorKnowledgeProtocol() {\n server.protocols = Arrays.asList(Protocol.H2_PRIOR_KNOWLEDGE)\n assertThat(server.protocols.size).isEqualTo(1)\n assertThat(server.protocols[0]).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":588,"symbol":"https","kind":"function","lang":"kotlin","code":"@Test\n fun https() {\n val handshakeCertificates = platform.localhostHandshakeCertificates()\n server.useHttps(handshakeCertificates.sslSocketFactory(), false)\n server.enqueue(MockResponse().setBody(\"abc\"))\n val url = server.url(\"/\")\n val connection = url.toUrl().openConnection() as HttpsURLConnection\n connection.setSSLSocketFactory(handshakeCertificates.sslSocketFactory())\n connection.setHostnameVerifier(RecordingHostnameVerifier())\n assertThat(connection.getResponseCode()).isEqualTo(HttpURLConnection.HTTP_OK)\n val reader = BufferedReader(InputStreamReader(connection.inputStream, StandardCharsets.UTF_8))\n assertThat(reader.readLine()).isEqualTo(\"abc\")\n val request = server.takeRequest()\n assertThat(request.requestUrl!!.scheme).isEqualTo(\"https\")\n val handshake = request.handshake\n assertThat(handshake!!.tlsVersion).isNotNull()\n assertThat(handshake.cipherSuite).isNotNull()\n assertThat(handshake.localPrincipal).isNotNull()\n assertThat(handshake.localCertificates.size).isEqualTo(1)\n assertThat(handshake.peerPrincipal).isNull()\n assertThat(handshake.peerCertificates.size).isEqualTo(0)\n }"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":611,"symbol":"httpsWithClientAuth","kind":"function","lang":"kotlin","code":"@Test\n fun httpsWithClientAuth() {\n platform.assumeNotBouncyCastle()\n platform.assumeNotConscrypt()\n val clientCa =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .build()\n val serverCa =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .build()\n val serverCertificate =\n HeldCertificate\n .Builder()\n .signedBy(serverCa)\n .addSubjectAlternativeName(server.hostName)\n .build()\n val serverHandshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(clientCa.certificate)\n .heldCertificate(serverCertificate)\n .build()\n server.useHttps(serverHandshakeCertificates.sslSocketFactory(), false)\n server.enqueue(MockResponse().setBody(\"abc\"))\n server.requestClientAuth()\n val clientCertificate =\n HeldCertificate\n .Builder()\n .signedBy(clientCa)\n .build()\n val clientHandshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(serverCa.certificate)\n .heldCertificate(clientCertificate)\n .build()\n val url = server.url(\"/\")\n val c"} {"repo":"okhttp","file":"mockwebserver-deprecated/src/test/java/okhttp3/mockwebserver/MockWebServerTest.kt","line":670,"symbol":"shutdownTwice","kind":"function","lang":"kotlin","code":"@Test\n fun shutdownTwice() {\n val server2 = MockWebServer()\n server2.start()\n server2.shutdown()\n try {\n server2.start()\n fail()\n } catch (expected: IllegalStateException) {\n // expected\n }\n server2.shutdown()\n }"} {"repo":"okhttp","file":"mockwebserver-junit4/src/main/kotlin/mockwebserver3/junit4/MockWebServerRule.kt","line":38,"symbol":"MockWebServerRule","kind":"class","lang":"kotlin","doc":"For Kotlin the `@JvmField` annotation is also necessary: ```kotlin @JvmField @Rule val serverRule = MockWebServerRule() ```","code":"class MockWebServerRule : ExternalResource() {\n val server: MockWebServer = MockWebServer()\n\n override fun before() {\n try {\n server.start()\n } catch (e: IOException) {\n throw RuntimeException(e)\n }\n }\n\n override fun after() {\n server.close()\n }\n}"} {"repo":"okhttp","file":"mockwebserver-junit4/src/main/kotlin/mockwebserver3/junit4/MockWebServerRule.kt","line":41,"symbol":"before","kind":"function","lang":"kotlin","code":"override fun before() {\n try {\n server.start()\n } catch (e: IOException) {\n throw RuntimeException(e)\n }\n }"} {"repo":"okhttp","file":"mockwebserver-junit4/src/main/kotlin/mockwebserver3/junit4/MockWebServerRule.kt","line":49,"symbol":"after","kind":"function","lang":"kotlin","code":"override fun after() {\n server.close()\n }"} {"repo":"okhttp","file":"mockwebserver-junit4/src/test/java/mockwebserver3/junit4/MockWebServerRuleTest.kt","line":27,"symbol":"MockWebServerRuleTest","kind":"class","lang":"kotlin","code":"class MockWebServerRuleTest {\n @Test fun statementStartsAndStops() {\n val rule = MockWebServerRule()\n val called = AtomicBoolean()\n val statement: Statement =\n rule.apply(\n object : Statement() {\n override fun evaluate() {\n called.set(true)\n rule.server\n .url(\"/\")\n .toUrl()\n .openConnection()\n .connect()\n }\n },\n Description.EMPTY,\n )\n statement.evaluate()\n assertThat(called.get()).isTrue()\n try {\n rule.server\n .url(\"/\")\n .toUrl()\n .openConnection()\n .connect()\n fail()\n } catch (expected: ConnectException) {\n }\n }\n}"} {"repo":"okhttp","file":"mockwebserver-junit4/src/test/java/mockwebserver3/junit4/MockWebServerRuleTest.kt","line":28,"symbol":"statementStartsAndStops","kind":"function","lang":"kotlin","code":"@Test fun statementStartsAndStops() {\n val rule = MockWebServerRule()\n val called = AtomicBoolean()\n val statement: Statement =\n rule.apply(\n object : Statement() {\n override fun evaluate() {\n called.set(true)\n rule.server\n .url(\"/\")\n .toUrl()\n .openConnection()\n .connect()\n }\n },\n Description.EMPTY,\n )\n statement.evaluate()\n assertThat(called.get()).isTrue()\n try {\n rule.server\n .url(\"/\")\n .toUrl()\n .openConnection()\n .connect()\n fail()\n } catch (expected: ConnectException) {\n }\n }"} {"repo":"okhttp","file":"mockwebserver-junit4/src/test/java/mockwebserver3/junit4/MockWebServerRuleTest.kt","line":34,"symbol":"evaluate","kind":"function","lang":"kotlin","code":"override fun evaluate() {\n called.set(true)\n rule.server\n .url(\"/\")\n .toUrl()\n .openConnection()\n .connect()\n }"} {"repo":"okhttp","file":"mockwebserver-junit5/src/main/kotlin/mockwebserver3/junit5/internal/StartStopExtension.kt","line":29,"symbol":"StartStopExtension","kind":"class","lang":"kotlin","doc":"Implements the policy specified by [StartStop].","code":"@SuppressSignatureCheck\ninternal class StartStopExtension :\n BeforeEachCallback,\n BeforeAllCallback {\n override fun beforeAll(context: ExtensionContext) {\n val store = context.getStore(Namespace.create(StartStop::class.java))\n\n val staticFields =\n findAnnotatedFields(\n context.requiredTestClass,\n StartStop::class.java,\n ) { Modifier.isStatic(it.modifiers) }\n\n for (field in staticFields) {\n field.setAccessible(true)\n val server = field.get(null) as? MockWebServer ?: continue\n\n // Put the instance in the store, so JUnit closes it for us in afterAll.\n store.put(field, server)\n\n server.start()\n }\n }\n\n override fun beforeEach(context: ExtensionContext) {\n val store = context.getStore(Namespace.create(StartStop::class.java))\n\n // A @Nested test declares its @StartStop fields on an enclosing instance, so walk every\n // instance in the hierarchy instead of just the innermost one from context.testInstance.\n for (testInstance in context.requiredTestInstances.allInstances) {\n val instanceFields =\n findAnnotatedFields(\n testInstance.javaClass,\n StartStop::class.java,\n ) { !Modifie"} {"repo":"okhttp","file":"mockwebserver-junit5/src/main/kotlin/mockwebserver3/junit5/internal/StartStopExtension.kt","line":33,"symbol":"beforeAll","kind":"function","lang":"kotlin","code":"override fun beforeAll(context: ExtensionContext) {\n val store = context.getStore(Namespace.create(StartStop::class.java))\n\n val staticFields =\n findAnnotatedFields(\n context.requiredTestClass,\n StartStop::class.java,\n ) { Modifier.isStatic(it.modifiers) }\n\n for (field in staticFields) {\n field.setAccessible(true)\n val server = field.get(null) as? MockWebServer ?: continue\n\n // Put the instance in the store, so JUnit closes it for us in afterAll.\n store.put(field, server)\n\n server.start()\n }\n }"} {"repo":"okhttp","file":"mockwebserver-junit5/src/main/kotlin/mockwebserver3/junit5/internal/StartStopExtension.kt","line":53,"symbol":"beforeEach","kind":"function","lang":"kotlin","code":"override fun beforeEach(context: ExtensionContext) {\n val store = context.getStore(Namespace.create(StartStop::class.java))\n\n // A @Nested test declares its @StartStop fields on an enclosing instance, so walk every\n // instance in the hierarchy instead of just the innermost one from context.testInstance.\n for (testInstance in context.requiredTestInstances.allInstances) {\n val instanceFields =\n findAnnotatedFields(\n testInstance.javaClass,\n StartStop::class.java,\n ) { !Modifier.isStatic(it.modifiers) }\n\n for (field in instanceFields) {\n field.setAccessible(true)\n val server = field.get(testInstance) as? MockWebServer ?: continue\n\n // Put the instance in the store, so JUnit closes it for us in afterEach.\n store.put(field, server)\n\n server.start()\n }\n }\n }"} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/NestedStartStopTest.kt","line":24,"symbol":"NestedStartStopTest","kind":"class","lang":"kotlin","code":"class NestedStartStopTest {\n @StartStop val outerServer = MockWebServer()\n\n @Test\n fun outerServerStartsForOuterTest() {\n assertThat(outerServer.started).isTrue()\n }\n\n @Nested\n inner class Group {\n @StartStop val nestedServer = MockWebServer()\n\n @Test\n fun outerServerStartsForNestedTest() {\n // Before the fix the outer @StartStop field was never started for @Nested tests.\n assertThat(outerServer.started).isTrue()\n assertThat(nestedServer.started).isTrue()\n }\n }\n}"} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/NestedStartStopTest.kt","line":27,"symbol":"outerServerStartsForOuterTest","kind":"function","lang":"kotlin","code":"@Test\n fun outerServerStartsForOuterTest() {\n assertThat(outerServer.started).isTrue()\n }"} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/NestedStartStopTest.kt","line":32,"symbol":"Group","kind":"class","lang":"kotlin","code":"@Nested\n inner class Group {\n @StartStop val nestedServer = MockWebServer()\n\n @Test\n fun outerServerStartsForNestedTest() {\n // Before the fix the outer @StartStop field was never started for @Nested tests.\n assertThat(outerServer.started).isTrue()\n assertThat(nestedServer.started).isTrue()\n }\n }"} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/NestedStartStopTest.kt","line":36,"symbol":"outerServerStartsForNestedTest","kind":"function","lang":"kotlin","code":"@Test\n fun outerServerStartsForNestedTest() {\n // Before the fix the outer @StartStop field was never started for @Nested tests.\n assertThat(outerServer.started).isTrue()\n assertThat(nestedServer.started).isTrue()\n }"} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/StartStopTest.kt","line":30,"symbol":"StartStopTest","kind":"class","lang":"kotlin","code":"class StartStopTest {\n private val dispatcherA = ClosableDispatcher()\n\n @StartStop val serverA =\n MockWebServer().apply {\n dispatcher = dispatcherA\n }\n\n private val dispatcherB = ClosableDispatcher()\n\n @StartStop val serverB =\n MockWebServer().apply {\n dispatcher = dispatcherB\n }\n\n /** This one won't start because it isn't annotated. */\n private val dispatcherC = ClosableDispatcher()\n val serverC =\n MockWebServer().apply {\n dispatcher = dispatcherC\n }\n\n @Test\n fun happyPath() {\n testInstances += this\n\n assertThat(serverA.started).isTrue()\n assertThat(serverB.started).isTrue()\n assertThat(serverC.started).isFalse()\n\n assertThat(serverD.started).isTrue()\n assertThat(serverE.started).isTrue()\n assertThat(serverF.started).isFalse()\n }\n\n private companion object {\n val testInstances = CopyOnWriteArrayList()\n\n private val dispatcherD = ClosableDispatcher()\n\n @StartStop @JvmStatic\n val serverD =\n MockWebServer().apply {\n dispatcher = dispatcherD\n }\n\n private val dispatcherE = ClosableDispatcher()\n\n @StartStop @JvmStatic\n val serverE =\n MockWebServer().apply {\n "} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/StartStopTest.kt","line":52,"symbol":"happyPath","kind":"function","lang":"kotlin","code":"@Test\n fun happyPath() {\n testInstances += this\n\n assertThat(serverA.started).isTrue()\n assertThat(serverB.started).isTrue()\n assertThat(serverC.started).isFalse()\n\n assertThat(serverD.started).isTrue()\n assertThat(serverE.started).isTrue()\n assertThat(serverF.started).isFalse()\n }"} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/StartStopTest.kt","line":112,"symbol":"ClosableDispatcher","kind":"class","lang":"kotlin","code":"class ClosableDispatcher : Dispatcher() {\n var closed = false\n\n override fun dispatch(request: RecordedRequest) = MockResponse()\n\n override fun close() {\n closed = true\n }\n }"} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/StartStopTest.kt","line":115,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"override fun dispatch(request: RecordedRequest) = MockResponse()"} {"repo":"okhttp","file":"mockwebserver-junit5/src/test/java/mockwebserver3/junit5/StartStopTest.kt","line":117,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n closed = true\n }"} {"repo":"okhttp","file":"module-tests/src/main/java/okhttp3/modules/Main.java","line":24,"symbol":"Main","kind":"class","lang":"java","code":"public class Main {\n public static void main(String[] args) throws IOException {\n Call call = OkHttpCaller.callOkHttp(HttpUrl.get(\"https://square.com/robots.txt\"));\n\n System.out.println(call.execute().body().string());\n }\n}"} {"repo":"okhttp","file":"module-tests/src/main/java/okhttp3/modules/Main.java","line":25,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String[] args) throws IOException {\n Call call = OkHttpCaller.callOkHttp(HttpUrl.get(\"https://square.com/robots.txt\"));\n\n System.out.println(call.execute().body().string());\n }"} {"repo":"okhttp","file":"module-tests/src/main/java/okhttp3/modules/OkHttpCaller.java","line":29,"symbol":"OkHttpCaller","kind":"class","lang":"java","doc":"Just checking compilation works","code":"public class OkHttpCaller {\n public static Call callOkHttp(HttpUrl url) {\n OkHttpClient client = new OkHttpClient\n .Builder()\n .eventListenerFactory(new LoggingEventListener.Factory(HttpLoggingInterceptor.Logger.DEFAULT))\n .build();\n return client.newCall(new Request.Builder().url(url).build());\n }\n}"} {"repo":"okhttp","file":"module-tests/src/main/java/okhttp3/modules/OkHttpCaller.java","line":30,"symbol":"callOkHttp","kind":"method","lang":"java","code":"public static Call callOkHttp(HttpUrl url) {\n OkHttpClient client = new OkHttpClient\n .Builder()\n .eventListenerFactory(new LoggingEventListener.Factory(HttpLoggingInterceptor.Logger.DEFAULT))\n .build();\n return client.newCall(new Request.Builder().url(url).build());\n }"} {"repo":"okhttp","file":"module-tests/src/test/java/okhttp3/modules/test/JavaModuleTest.java","line":35,"symbol":"JavaModuleTest","kind":"class","lang":"java","code":"class JavaModuleTest {\n @Test\n public void testVisibility() {\n // Just check we can run code that depends on OkHttp types\n OkHttpCaller.callOkHttp(HttpUrl.get(\"https://square.com/robots.txt\"));\n }\n\n @Test\n public void testMockWebServer() throws IOException {\n MockWebServer server = new MockWebServer();\n server.enqueue(new MockResponse(200, Headers.of(), \"Hello, Java9!\"));\n server.start();\n\n // Just check we can run code that depends on OkHttp types\n Call call = OkHttpCaller.callOkHttp(server.url(\"/\"));\n\n try (Response response = call.execute();) {\n System.out.println(response.body().string());\n }\n }\n\n @Test\n public void testModules() {\n Module okHttpModule = OkHttpClient.class.getModule();\n assertEquals(\"okhttp3\", okHttpModule.getName());\n assertTrue(okHttpModule.getPackages().contains(\"okhttp3\"));\n\n Module loggingInterceptorModule = HttpLoggingInterceptor.class.getModule();\n assertEquals(\"okhttp3.logging\", loggingInterceptorModule.getName());\n assertTrue(loggingInterceptorModule.getPackages().contains(\"okhttp3.logging\"));\n }\n}"} {"repo":"okhttp","file":"module-tests/src/test/java/okhttp3/modules/test/JavaModuleTest.java","line":36,"symbol":"testVisibility","kind":"method","lang":"java","code":"@Test\n public void testVisibility() {\n // Just check we can run code that depends on OkHttp types\n OkHttpCaller.callOkHttp(HttpUrl.get(\"https://square.com/robots.txt\"));\n }"} {"repo":"okhttp","file":"module-tests/src/test/java/okhttp3/modules/test/JavaModuleTest.java","line":42,"symbol":"testMockWebServer","kind":"method","lang":"java","code":"@Test\n public void testMockWebServer() throws IOException {\n MockWebServer server = new MockWebServer();\n server.enqueue(new MockResponse(200, Headers.of(), \"Hello, Java9!\"));\n server.start();\n\n // Just check we can run code that depends on OkHttp types\n Call call = OkHttpCaller.callOkHttp(server.url(\"/\"));\n\n try (Response response = call.execute();) {\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"module-tests/src/test/java/okhttp3/modules/test/JavaModuleTest.java","line":56,"symbol":"testModules","kind":"method","lang":"java","code":"@Test\n public void testModules() {\n Module okHttpModule = OkHttpClient.class.getModule();\n assertEquals(\"okhttp3\", okHttpModule.getName());\n assertTrue(okHttpModule.getPackages().contains(\"okhttp3\"));\n\n Module loggingInterceptorModule = HttpLoggingInterceptor.class.getModule();\n assertEquals(\"okhttp3.logging\", loggingInterceptorModule.getName());\n assertTrue(loggingInterceptorModule.getPackages().contains(\"okhttp3.logging\"));\n }"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/PublicSuffixDatabaseTest.kt","line":23,"symbol":"PublicSuffixDatabaseTest","kind":"class","lang":"kotlin","code":"class PublicSuffixDatabaseTest {\n @Test\n fun testResourcesLoaded() {\n val url = \"https://api.twitter.com\".toHttpUrl()\n\n assertThat(url.topPrivateDomain()).isEqualTo(\"twitter.com\")\n }\n}"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/PublicSuffixDatabaseTest.kt","line":24,"symbol":"testResourcesLoaded","kind":"function","lang":"kotlin","code":"@Test\n fun testResourcesLoaded() {\n val url = \"https://api.twitter.com\".toHttpUrl()\n\n assertThat(url.topPrivateDomain()).isEqualTo(\"twitter.com\")\n }"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/SampleTest.kt","line":27,"symbol":"SampleTest","kind":"class","lang":"kotlin","code":"class SampleTest {\n private val server = MockWebServer()\n\n private val client = OkHttpClient()\n\n @Test\n fun passingTest() {\n assertThat(\"hello\").isEqualTo(\"hello\")\n }\n\n @Test\n fun testMockWebServer() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.start()\n\n client.newCall(Request(url = server.url(\"/\"))).execute().use {\n assertThat(it.body.string()).isEqualTo(\"abc\")\n }\n }\n\n @Test\n fun testExternalSite() {\n client.newCall(Request(url = \"https://google.com/robots.txt\".toHttpUrl())).execute().use {\n assertThat(it.code).isEqualTo(200)\n }\n }\n}"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/SampleTest.kt","line":32,"symbol":"passingTest","kind":"function","lang":"kotlin","code":"@Test\n fun passingTest() {\n assertThat(\"hello\").isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/SampleTest.kt","line":37,"symbol":"testMockWebServer","kind":"function","lang":"kotlin","code":"@Test\n fun testMockWebServer() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.start()\n\n client.newCall(Request(url = server.url(\"/\"))).execute().use {\n assertThat(it.body.string()).isEqualTo(\"abc\")\n }\n }"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/SampleTest.kt","line":47,"symbol":"testExternalSite","kind":"function","lang":"kotlin","code":"@Test\n fun testExternalSite() {\n client.newCall(Request(url = \"https://google.com/robots.txt\".toHttpUrl())).execute().use {\n assertThat(it.code).isEqualTo(200)\n }\n }"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/WithArgumentSourceTest.kt","line":32,"symbol":"WithArgumentSourceTest","kind":"class","lang":"kotlin","doc":"This enforces us having the params classes on the classpath to workaround https://github.com/graalvm/native-build-tools/issues/745","code":"class WithArgumentSourceTest {\n @ParameterizedTest\n @ArgumentsSource(FakeArgumentsProvider::class)\n fun passingTest(value: Int) {\n assertThat(value).isGreaterThan(0)\n }\n}"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/WithArgumentSourceTest.kt","line":33,"symbol":"passingTest","kind":"function","lang":"kotlin","code":"@ParameterizedTest\n @ArgumentsSource(FakeArgumentsProvider::class)\n fun passingTest(value: Int) {\n assertThat(value).isGreaterThan(0)\n }"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/WithArgumentSourceTest.kt","line":40,"symbol":"FakeArgumentsProvider","kind":"class","lang":"kotlin","code":"internal class FakeArgumentsProvider : ArgumentsProvider {\n override fun provideArguments(\n parameters: ParameterDeclarations?,\n context: ExtensionContext?,\n ): Stream = listOf(Arguments.of(1), Arguments.of(2)).stream()\n}"} {"repo":"okhttp","file":"native-image-tests/src/test/kotlin/okhttp3/nativeimage/WithArgumentSourceTest.kt","line":41,"symbol":"provideArguments","kind":"function","lang":"kotlin","code":"override fun provideArguments(\n parameters: ParameterDeclarations?,\n context: ExtensionContext?,\n ): Stream = listOf(Arguments.of(1), Arguments.of(2)).stream()"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":45,"symbol":"Main","kind":"class","lang":"kotlin","code":"class Main : CliktCommand(name = NAME) {\n override val printHelpOnEmptyArgs = true\n\n override fun help(context: Context): String = \"A curl for the next-generation web.\"\n\n val method: String? by option(\"-X\", \"--request\").help(\"Specify request command to use\")\n\n val data: String? by option(\"-d\", \"--data\").help(\"HTTP POST data\")\n\n val headers: List? by option(\"-H\", \"--header\").help(\"Custom header to pass to server\").multiple()\n\n val userAgent: String by option(\n \"-A\",\n \"--user-agent\",\n ).help(\n \"User-Agent to send to server\",\n ).default(NAME + \"/\" + versionString())\n\n val connectTimeout: Int by option(\n \"--connect-timeout\",\n ).help(\n \"Maximum time allowed for connection (seconds)\",\n ).int()\n .default(DEFAULT_TIMEOUT)\n\n val readTimeout: Int by option(\"--read-timeout\")\n .help(\"Maximum time allowed for reading data (seconds)\")\n .int()\n .default(DEFAULT_TIMEOUT)\n\n val callTimeout: Int by option(\n \"--call-timeout\",\n ).help(\n \"Maximum time allowed for the entire call (seconds)\",\n ).int()\n .default(DEFAULT_TIMEOUT)\n\n val followRedirects: Boolean by option(\"-L\", \"--location\").help(\"Follow redirects\").flag()\n\n val allowInsecure: Bool"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":48,"symbol":"help","kind":"function","lang":"kotlin","code":"override fun help(context: Context): String = \"A curl for the next-generation web.\""} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":100,"symbol":"run","kind":"function","lang":"kotlin","code":"override fun run() {\n LoggingUtil.configureLogging(debug = verbose, showHttp2Frames = showHttp2Frames, sslDebug = sslDebug)\n\n commonRun()\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":106,"symbol":"createRequest","kind":"function","lang":"kotlin","code":"fun createRequest(): Request = commonCreateRequest()"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":108,"symbol":"createClient","kind":"function","lang":"kotlin","code":"fun createClient(): Call.Factory {\n val builder = OkHttpClient.Builder()\n builder.followSslRedirects(followRedirects)\n if (connectTimeout != DEFAULT_TIMEOUT) {\n builder.connectTimeout(connectTimeout.toLong(), SECONDS)\n }\n if (readTimeout != DEFAULT_TIMEOUT) {\n builder.readTimeout(readTimeout.toLong(), SECONDS)\n }\n if (callTimeout != DEFAULT_TIMEOUT) {\n builder.callTimeout(callTimeout.toLong(), SECONDS)\n }\n if (allowInsecure) {\n val trustManager = createInsecureTrustManager()\n val sslSocketFactory = createInsecureSslSocketFactory(trustManager)\n builder.sslSocketFactory(sslSocketFactory, trustManager)\n builder.hostnameVerifier(createInsecureHostnameVerifier())\n }\n if (verbose) {\n val logger = HttpLoggingInterceptor.Logger(::println)\n builder.eventListenerFactory(LoggingEventListener.Factory(logger))\n }\n return builder.build()\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":133,"symbol":"close","kind":"function","lang":"kotlin","code":"fun close() {\n val okHttpClient = client as OkHttpClient\n okHttpClient.connectionPool.evictAll() // Close any persistent connections.\n okHttpClient.dispatcher.executorService.shutdownNow()\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":143,"symbol":"versionString","kind":"function","lang":"kotlin","code":"private fun versionString(): String? {\n val prop = Properties()\n Main::class.java.getResourceAsStream(\"/okcurl-version.properties\")?.use {\n prop.load(it)\n }\n return prop.getProperty(\"version\", \"dev\")\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":151,"symbol":"createInsecureTrustManager","kind":"function","lang":"kotlin","code":"@Suppress(\"TrustAllX509TrustManager\", \"CustomX509TrustManager\")\n private fun createInsecureTrustManager(): X509TrustManager =\n object : X509TrustManager {\n override fun checkClientTrusted(\n chain: Array,\n authType: String,\n ) {\n }\n\n override fun checkServerTrusted(\n chain: Array,\n authType: String,\n ) {\n }\n\n override fun getAcceptedIssuers(): Array = arrayOf()\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":154,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n chain: Array,\n authType: String,\n ) {\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":160,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n chain: Array,\n authType: String,\n ) {\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":166,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = arrayOf()"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":169,"symbol":"createInsecureSslSocketFactory","kind":"function","lang":"kotlin","code":"private fun createInsecureSslSocketFactory(trustManager: TrustManager): SSLSocketFactory =\n Platform\n .get()\n .newSSLContext()\n .apply {\n init(null, arrayOf(trustManager), null)\n }.socketFactory"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/Main.kt","line":177,"symbol":"createInsecureHostnameVerifier","kind":"function","lang":"kotlin","code":"private fun createInsecureHostnameVerifier(): HostnameVerifier = HostnameVerifier { _, _ -> true }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/MainCommandLine.kt","line":21,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main(args: Array) {\n Main().main(args)\n exitProcess(0)\n}"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/internal/-MainCommon.kt","line":29,"symbol":"commonCreateRequest","kind":"function","lang":"kotlin","code":"internal fun Main.commonCreateRequest(): Request {\n val request = Request.Builder()\n\n val requestMethod = method ?: if (data != null) \"POST\" else \"GET\"\n\n val url = url ?: throw IOException(\"No url provided\")\n\n request.url(url)\n\n data?.let {\n request.method(requestMethod, it.toRequestBody(mediaType()))\n }\n\n for (header in headers.orEmpty()) {\n val parts = header.split(':', limit = 2)\n if (!isSpecialHeader(parts[0])) {\n request.header(parts[0], parts[1])\n }\n }\n referer?.let {\n request.header(\"Referer\", it)\n }\n request.header(\"User-Agent\", userAgent)\n\n return request.build()\n}"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/internal/-MainCommon.kt","line":56,"symbol":"mediaType","kind":"function","lang":"kotlin","code":"private fun Main.mediaType(): MediaType? {\n val mimeType =\n headers?.let {\n for (header in it) {\n val parts = header.split(':', limit = 2)\n if (\"Content-Type\".equals(parts[0], ignoreCase = true)) {\n return@let parts[1].trim()\n }\n }\n return@let null\n } ?: \"application/x-www-form-urlencoded\"\n\n return mimeType.toMediaTypeOrNull()\n}"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/internal/-MainCommon.kt","line":71,"symbol":"isSpecialHeader","kind":"function","lang":"kotlin","code":"private fun isSpecialHeader(s: String): Boolean = s.equals(\"Content-Type\", ignoreCase = true)"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/internal/-MainCommon.kt","line":73,"symbol":"commonRun","kind":"function","lang":"kotlin","code":"fun Main.commonRun() {\n client = createClient()\n val request = createRequest()\n\n try {\n val response = client!!.newCall(request).execute()\n if (showHeaders) {\n println(StatusLine.get(response))\n val headers = response.headers\n for ((name, value) in headers) {\n println(\"$name: $value\")\n }\n println()\n }\n\n // Stream the response to the System.out as it is returned from the server.\n val out = System.out.sink()\n val source = response.body.source()\n while (!source.exhausted()) {\n out.write(source.buffer, source.buffer.size)\n out.flush()\n }\n\n response.body.close()\n } catch (e: IOException) {\n e.printStackTrace()\n } finally {\n close()\n }\n}"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/logging/LoggingUtil.kt","line":25,"symbol":"LoggingUtil","kind":"class","lang":"kotlin","code":"class LoggingUtil {\n companion object {\n private val activeLoggers = mutableListOf()\n\n fun configureLogging(\n debug: Boolean,\n showHttp2Frames: Boolean,\n sslDebug: Boolean,\n ) {\n if (debug || showHttp2Frames || sslDebug) {\n if (sslDebug) {\n System.setProperty(\"javax.net.debug\", \"\")\n }\n LogManager.getLogManager().reset()\n val handler =\n object : ConsoleHandler() {\n override fun publish(record: LogRecord) {\n super.publish(record)\n\n val parameters = record.parameters\n if (sslDebug && record.loggerName == \"javax.net.ssl\" && parameters != null) {\n System.err.println(parameters[0])\n }\n }\n }\n\n if (debug) {\n handler.level = Level.ALL\n handler.formatter = OneLineLogFormat()\n val activeLogger = getLogger(\"\")\n activeLogger.addHandler(handler)\n activeLogger.level = Level.ALL\n\n getLogger(\"jdk.event.security\").level = Level.INFO\n getLogger(\"org.conscrypt\").level = Level.INFO\n } else {\n if (showHttp2Frames) {\n val activeLo"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/logging/LoggingUtil.kt","line":29,"symbol":"configureLogging","kind":"function","lang":"kotlin","code":"fun configureLogging(\n debug: Boolean,\n showHttp2Frames: Boolean,\n sslDebug: Boolean,\n ) {\n if (debug || showHttp2Frames || sslDebug) {\n if (sslDebug) {\n System.setProperty(\"javax.net.debug\", \"\")\n }\n LogManager.getLogManager().reset()\n val handler =\n object : ConsoleHandler() {\n override fun publish(record: LogRecord) {\n super.publish(record)\n\n val parameters = record.parameters\n if (sslDebug && record.loggerName == \"javax.net.ssl\" && parameters != null) {\n System.err.println(parameters[0])\n }\n }\n }\n\n if (debug) {\n handler.level = Level.ALL\n handler.formatter = OneLineLogFormat()\n val activeLogger = getLogger(\"\")\n activeLogger.addHandler(handler)\n activeLogger.level = Level.ALL\n\n getLogger(\"jdk.event.security\").level = Level.INFO\n getLogger(\"org.conscrypt\").level = Level.INFO\n } else {\n if (showHttp2Frames) {\n val activeLogger = getLogger(Http2::class.java.name)\n activeLogger.level = Level.FINE\n handl"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/logging/LoggingUtil.kt","line":41,"symbol":"publish","kind":"function","lang":"kotlin","code":"override fun publish(record: LogRecord) {\n super.publish(record)\n\n val parameters = record.parameters\n if (sslDebug && record.loggerName == \"javax.net.ssl\" && parameters != null) {\n System.err.println(parameters[0])\n }\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/logging/LoggingUtil.kt","line":81,"symbol":"getLogger","kind":"function","lang":"kotlin","code":"fun getLogger(name: String): Logger {\n val logger = Logger.getLogger(name)\n activeLoggers.add(logger)\n return logger\n }"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/logging/MessageFormatter.kt","line":21,"symbol":"MessageFormatter","kind":"object","lang":"kotlin","code":"object MessageFormatter : SimpleFormatter() {\n override fun format(record: LogRecord): String = String.format(\"%s%n\", record.message)\n}"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/logging/MessageFormatter.kt","line":22,"symbol":"format","kind":"function","lang":"kotlin","code":"override fun format(record: LogRecord): String = String.format(\"%s%n\", record.message)"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/logging/OneLineLogFormat.kt","line":36,"symbol":"OneLineLogFormat","kind":"class","lang":"kotlin","doc":"Is Java8 Data and Time really this bad, or is writing this on a plane from just javadocs a bad idea? Why so much construction?","code":"class OneLineLogFormat : Formatter() {\n private val d =\n DateTimeFormatterBuilder()\n .appendValue(HOUR_OF_DAY, 2)\n .appendLiteral(':')\n .appendValue(MINUTE_OF_HOUR, 2)\n .optionalStart()\n .appendLiteral(':')\n .appendValue(SECOND_OF_MINUTE, 2)\n .optionalStart()\n .appendFraction(NANO_OF_SECOND, 3, 3, true)\n .toFormatter()\n\n private val offset = ZoneOffset.systemDefault()\n\n override fun format(record: LogRecord): String {\n val message = formatMessage(record)\n\n val time = Instant.ofEpochMilli(record.millis).atZone(offset)\n\n return if (record.thrown != null) {\n val sw = StringWriter(4096)\n val pw = PrintWriter(sw)\n record.thrown.printStackTrace(pw)\n String.format(\"%s\\t%s%n%s%n\", time.format(d), message, sw.toString())\n } else {\n String.format(\"%s\\t%s%n\", time.format(d), message)\n }\n }\n}"} {"repo":"okhttp","file":"okcurl/src/main/kotlin/okhttp3/curl/logging/OneLineLogFormat.kt","line":51,"symbol":"format","kind":"function","lang":"kotlin","code":"override fun format(record: LogRecord): String {\n val message = formatMessage(record)\n\n val time = Instant.ofEpochMilli(record.millis).atZone(offset)\n\n return if (record.thrown != null) {\n val sw = StringWriter(4096)\n val pw = PrintWriter(sw)\n record.thrown.printStackTrace(pw)\n String.format(\"%s\\t%s%n%s%n\", time.format(d), message, sw.toString())\n } else {\n String.format(\"%s\\t%s%n\", time.format(d), message)\n }\n }"} {"repo":"okhttp","file":"okcurl/src/main/resources-templates/okcurl-version.properties","line":1,"symbol":"version","kind":"field","lang":"properties","code":"version=${projectVersion}"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":28,"symbol":"MainTest","kind":"class","lang":"kotlin","code":"class MainTest {\n @Test\n fun simple() {\n val request = fromArgs(\"http://example.com\").createRequest()\n assertThat(request.method).isEqualTo(\"GET\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(request.body).isNull()\n }\n\n @Test\n @Throws(IOException::class)\n fun put() {\n val request = fromArgs(\"-X\", \"PUT\", \"-d\", \"foo\", \"http://example.com\").createRequest()\n assertThat(request.method).isEqualTo(\"PUT\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(request.body!!.contentLength()).isEqualTo(3)\n }\n\n @Test\n fun dataPost() {\n val request = fromArgs(\"-d\", \"foo\", \"http://example.com\").createRequest()\n val body = request.body\n assertThat(request.method).isEqualTo(\"POST\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(body!!.contentType().toString()).isEqualTo(\n \"application/x-www-form-urlencoded; charset=utf-8\",\n )\n assertThat(bodyAsString(body)).isEqualTo(\"foo\")\n }\n\n @Test\n fun dataPut() {\n val request = fromArgs(\"-d\", \"foo\", \"-X\", \"PUT\", \"http://example.com\").createRequest()\n val body = request.body\n assertThat(request."} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":29,"symbol":"simple","kind":"function","lang":"kotlin","code":"@Test\n fun simple() {\n val request = fromArgs(\"http://example.com\").createRequest()\n assertThat(request.method).isEqualTo(\"GET\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(request.body).isNull()\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":37,"symbol":"put","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun put() {\n val request = fromArgs(\"-X\", \"PUT\", \"-d\", \"foo\", \"http://example.com\").createRequest()\n assertThat(request.method).isEqualTo(\"PUT\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(request.body!!.contentLength()).isEqualTo(3)\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":46,"symbol":"dataPost","kind":"function","lang":"kotlin","code":"@Test\n fun dataPost() {\n val request = fromArgs(\"-d\", \"foo\", \"http://example.com\").createRequest()\n val body = request.body\n assertThat(request.method).isEqualTo(\"POST\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(body!!.contentType().toString()).isEqualTo(\n \"application/x-www-form-urlencoded; charset=utf-8\",\n )\n assertThat(bodyAsString(body)).isEqualTo(\"foo\")\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":58,"symbol":"dataPut","kind":"function","lang":"kotlin","code":"@Test\n fun dataPut() {\n val request = fromArgs(\"-d\", \"foo\", \"-X\", \"PUT\", \"http://example.com\").createRequest()\n val body = request.body\n assertThat(request.method).isEqualTo(\"PUT\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(body!!.contentType().toString()).isEqualTo(\n \"application/x-www-form-urlencoded; charset=utf-8\",\n )\n assertThat(bodyAsString(body)).isEqualTo(\"foo\")\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":70,"symbol":"contentTypeHeader","kind":"function","lang":"kotlin","code":"@Test\n fun contentTypeHeader() {\n val request =\n fromArgs(\n \"-d\",\n \"foo\",\n \"-H\",\n \"Content-Type: application/json\",\n \"http://example.com\",\n ).createRequest()\n val body = request.body\n assertThat(request.method).isEqualTo(\"POST\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(body!!.contentType().toString())\n .isEqualTo(\"application/json; charset=utf-8\")\n assertThat(bodyAsString(body)).isEqualTo(\"foo\")\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":88,"symbol":"referer","kind":"function","lang":"kotlin","code":"@Test\n fun referer() {\n val request = fromArgs(\"-e\", \"foo\", \"http://example.com\").createRequest()\n assertThat(request.method).isEqualTo(\"GET\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(request.header(\"Referer\")).isEqualTo(\"foo\")\n assertThat(request.body).isNull()\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":97,"symbol":"userAgent","kind":"function","lang":"kotlin","code":"@Test\n fun userAgent() {\n val request = fromArgs(\"-A\", \"foo\", \"http://example.com\").createRequest()\n assertThat(request.method).isEqualTo(\"GET\")\n assertThat(request.url.toString()).isEqualTo(\"http://example.com/\")\n assertThat(request.header(\"User-Agent\")).isEqualTo(\"foo\")\n assertThat(request.body).isNull()\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":106,"symbol":"defaultUserAgent","kind":"function","lang":"kotlin","code":"@Test\n fun defaultUserAgent() {\n val request = fromArgs(\"http://example.com\").createRequest()\n assertThat(request.header(\"User-Agent\")!!).startsWith(\"okcurl/\")\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":112,"symbol":"headerSplitWithDate","kind":"function","lang":"kotlin","code":"@Test\n fun headerSplitWithDate() {\n val request =\n fromArgs(\n \"-H\",\n \"If-Modified-Since: Mon, 18 Aug 2014 15:16:06 GMT\",\n \"http://example.com\",\n ).createRequest()\n assertThat(request.header(\"If-Modified-Since\")).isEqualTo(\n \"Mon, 18 Aug 2014 15:16:06 GMT\",\n )\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":126,"symbol":"fromArgs","kind":"function","lang":"kotlin","code":"fun fromArgs(vararg args: String): Main =\n Main().apply {\n parse(args.toList())\n }"} {"repo":"okhttp","file":"okcurl/src/test/kotlin/okhttp3/curl/MainTest.kt","line":131,"symbol":"bodyAsString","kind":"function","lang":"kotlin","code":"private fun bodyAsString(body: RequestBody?): String =\n try {\n val buffer = Buffer()\n body!!.writeTo(buffer)\n buffer.readString(body.contentType()!!.charset()!!)\n } catch (e: IOException) {\n throw RuntimeException(e)\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":45,"symbol":"AndroidDnsRobolectricTest","kind":"class","lang":"kotlin","code":"@SuppressLint(\"NewApi\")\n@SuppressSignatureCheck\n@RunWith(RobolectricTestRunner::class)\n@Config(\n sdk = [37],\n shadows = [\n ShadowDnsResolver::class,\n ShadowNetwork::class,\n ShadowNetworkSecurityPolicy::class,\n ],\n)\nclass AndroidDnsRobolectricTest {\n private val echConfigList = \"ech config list\".encodeUtf8()\n\n private val dnsServer =\n FakeDns().apply {\n setRecords(\n hostname = \"publicobject.com\",\n address = InetAddress.getByName(\"10.20.30.40\"),\n echConfigList = echConfigList,\n )\n }\n\n private val domainEncryptionModes =\n mutableMapOf(\n \"publicobject.com\" to DOMAIN_ENCRYPTION_MODE_ENABLED,\n )\n\n private val dnsCache = DnsCache()\n\n private val androidDns =\n AndroidDns(\n dnsResolver = ShadowDnsResolver.create(dnsServer),\n network = ShadowNetwork.create(dnsServer),\n dnsCache = dnsCache,\n includeServiceMetadata = true,\n executor = { it.run() },\n taskRunner = TaskRunner.INSTANCE,\n lazyNetworkSecurityPolicy =\n lazy {\n ShadowNetworkSecurityPolicy.create(domainEncryptionModes)\n },\n )\n\n @Test\n fun happyPath() {\n val records = androidDns.recordsFor(\"publicobject.c"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":89,"symbol":"happyPath","kind":"function","lang":"kotlin","code":"@Test\n fun happyPath() {\n val records = androidDns.recordsFor(\"publicobject.com\")\n assertThat(records.addresses()).containsExactly(InetAddress.getByName(\"10.20.30.40\"))\n assertThat(records.echConfigLists()).containsExactly(echConfigList)\n assertThat(dnsServer.takeAllRequests()).hasSize(2)\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":97,"symbol":"attrLeafUsedForNonDefaultPort","kind":"function","lang":"kotlin","code":"@Test\n fun attrLeafUsedForNonDefaultPort() {\n val customPortEchConfigList = \"this is the ECH config for port 8443\".encodeUtf8()\n dnsServer.setRecords(\n hostname = \"_8443._https.custom-port.publicobject.com\",\n address = InetAddress.getByName(\"0:0::0:1\"),\n echConfigList = customPortEchConfigList,\n )\n dnsServer.setRecords(\n hostname = \"custom-port.publicobject.com\",\n address = InetAddress.getByName(\"10.20.30.40\"),\n echConfigList = \"this ECH config should not be used!\".encodeUtf8(),\n )\n domainEncryptionModes[\"custom-port.publicobject.com\"] = DOMAIN_ENCRYPTION_MODE_ENABLED\n val records =\n androidDns.recordsFor(\n hostname = \"custom-port.publicobject.com\",\n port = 8443,\n )\n assertThat(records.addresses()).containsExactly(InetAddress.getByName(\"10.20.30.40\"))\n assertThat(records.echConfigLists()).containsExactly(customPortEchConfigList)\n assertThat(dnsServer.takeAllRequests()).hasSize(2)\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":121,"symbol":"disabledPolicySkipsHttpsMetadata","kind":"function","lang":"kotlin","code":"@Test\n fun disabledPolicySkipsHttpsMetadata() {\n domainEncryptionModes[\"publicobject.com\"] = DOMAIN_ENCRYPTION_MODE_DISABLED\n val records = androidDns.recordsFor(\"publicobject.com\")\n assertThat(records.addresses()).containsExactly(InetAddress.getByName(\"10.20.30.40\"))\n assertThat(records.echConfigLists()).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":129,"symbol":"unknownPolicySkipsHttpsMetadata","kind":"function","lang":"kotlin","code":"@Test\n fun unknownPolicySkipsHttpsMetadata() {\n domainEncryptionModes[\"publicobject.com\"] = DOMAIN_ENCRYPTION_MODE_UNKNOWN\n val records = androidDns.recordsFor(\"publicobject.com\")\n assertThat(records.addresses()).containsExactly(InetAddress.getByName(\"10.20.30.40\"))\n assertThat(records.echConfigLists()).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":137,"symbol":"opportunisticPolicyIncludesHttpsMetadata","kind":"function","lang":"kotlin","code":"@Test\n fun opportunisticPolicyIncludesHttpsMetadata() {\n domainEncryptionModes[\"publicobject.com\"] = DOMAIN_ENCRYPTION_MODE_OPPORTUNISTIC\n val records = androidDns.recordsFor(\"publicobject.com\")\n assertThat(records.addresses()).containsExactly(InetAddress.getByName(\"10.20.30.40\"))\n assertThat(records.echConfigLists()).containsExactly(echConfigList)\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":145,"symbol":"policyIsPerHost","kind":"function","lang":"kotlin","code":"@Test\n fun policyIsPerHost() {\n val deniedEchConfigList = \"denied ech config list\".encodeUtf8()\n dnsServer.setRecords(\n hostname = \"denied.example.com\",\n address = InetAddress.getByName(\"1:2::3:4\"),\n echConfigList = deniedEchConfigList,\n )\n domainEncryptionModes[\"denied.example.com\"] = DOMAIN_ENCRYPTION_MODE_DISABLED\n\n val recordsA = androidDns.recordsFor(\"publicobject.com\")\n assertThat(recordsA.addresses()).containsExactly(InetAddress.getByName(\"10.20.30.40\"))\n assertThat(recordsA.echConfigLists()).containsExactly(echConfigList)\n\n val recordsB = androidDns.recordsFor(\"denied.example.com\")\n assertThat(recordsB.addresses()).containsExactly(InetAddress.getByName(\"1:2::3:4\"))\n assertThat(recordsB.echConfigLists()).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":164,"symbol":"lookupDoesNotRequestServiceMetadata","kind":"function","lang":"kotlin","code":"@Test\n fun lookupDoesNotRequestServiceMetadata() {\n val addresses = androidDns.lookup(\"publicobject.com\")\n assertThat(addresses).containsExactly(InetAddress.getByName(\"10.20.30.40\"))\n assertThat(dnsServer.takeAllRequests()).hasSize(1)\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":171,"symbol":"recordsFor","kind":"function","lang":"kotlin","code":"private fun Dns.recordsFor(\n hostname: String,\n port: Int = -1,\n ): List = newCall(Dns.Request(hostname, port)).execute()"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":176,"symbol":"addresses","kind":"function","lang":"kotlin","code":"private fun List.addresses() = filterIsInstance().map { it.address }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":178,"symbol":"echConfigLists","kind":"function","lang":"kotlin","code":"private fun List.echConfigLists() = filterIsInstance().mapNotNull { it.echConfigList }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/AndroidDnsRobolectricTest.kt","line":182,"symbol":"setRecords","kind":"function","lang":"kotlin","doc":"Serves [address] for [hostname], plus an `HTTPS` record when [echConfigList] is non-null.","code":"private fun FakeDns.setRecords(\n hostname: String,\n address: InetAddress,\n echConfigList: ByteString? = null,\n) {\n this[hostname] =\n listOfNotNull(\n echConfigList?.let {\n ResourceRecord.Https(\n name = hostname,\n timeToLive = 5,\n echConfigList = it,\n )\n },\n ResourceRecord.IpAddress(\n name = hostname,\n timeToLive = 5,\n address = address,\n ),\n )\n}"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowDnsResolver.kt","line":32,"symbol":"ShadowDnsResolver","kind":"class","lang":"kotlin","code":"@SuppressSignatureCheck\n@Implements(DnsResolver::class)\nclass ShadowDnsResolver {\n lateinit var dns: FakeDns\n\n @Implementation\n fun rawQuery(\n network: Network?,\n domain: String,\n nsClass: Int,\n nsType: Int,\n flags: Int,\n executor: Executor,\n cancellationSignal: CancellationSignal?,\n callback: DnsResolver.Callback,\n ) {\n val response =\n dns.query(\n DnsMessage(\n id = 0,\n flags = flags,\n questions =\n listOf(\n Question(\n name = domain,\n type = nsType,\n `class` = nsClass,\n ),\n ),\n ),\n )\n\n val responseBytes =\n Buffer().run {\n DnsMessageWriter(this).write(response)\n readByteArray()\n }\n\n executor.execute {\n callback.onAnswer(responseBytes, response.responseCode)\n }\n }\n\n companion object {\n fun create(dns: FakeDns): DnsResolver {\n val result = Shadow.newInstanceOf(DnsResolver::class.java)\n val shadow = Shadow.extract(result)\n shadow.dns = dns\n return result\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowDnsResolver.kt","line":37,"symbol":"rawQuery","kind":"function","lang":"kotlin","code":"@Implementation\n fun rawQuery(\n network: Network?,\n domain: String,\n nsClass: Int,\n nsType: Int,\n flags: Int,\n executor: Executor,\n cancellationSignal: CancellationSignal?,\n callback: DnsResolver.Callback,\n ) {\n val response =\n dns.query(\n DnsMessage(\n id = 0,\n flags = flags,\n questions =\n listOf(\n Question(\n name = domain,\n type = nsType,\n `class` = nsClass,\n ),\n ),\n ),\n )\n\n val responseBytes =\n Buffer().run {\n DnsMessageWriter(this).write(response)\n readByteArray()\n }\n\n executor.execute {\n callback.onAnswer(responseBytes, response.responseCode)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowDnsResolver.kt","line":76,"symbol":"create","kind":"function","lang":"kotlin","code":"fun create(dns: FakeDns): DnsResolver {\n val result = Shadow.newInstanceOf(DnsResolver::class.java)\n val shadow = Shadow.extract(result)\n shadow.dns = dns\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowNetwork.kt","line":26,"symbol":"ShadowNetwork","kind":"class","lang":"kotlin","code":"@Implements(Network::class)\nclass ShadowNetwork {\n lateinit var dns: FakeDns\n\n @Implementation\n @Throws(UnknownHostException::class)\n fun getAllByName(host: String): Array = dns.lookup(host).toTypedArray()\n\n companion object {\n fun create(dns: FakeDns): Network {\n val result = Shadow.newInstanceOf(Network::class.java)\n Shadow.extract(result).dns = dns\n return result\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowNetwork.kt","line":30,"symbol":"getAllByName","kind":"function","lang":"kotlin","code":"@Implementation\n @Throws(UnknownHostException::class)\n fun getAllByName(host: String): Array = dns.lookup(host).toTypedArray()"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowNetwork.kt","line":35,"symbol":"create","kind":"function","lang":"kotlin","code":"fun create(dns: FakeDns): Network {\n val result = Shadow.newInstanceOf(Network::class.java)\n Shadow.extract(result).dns = dns\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowNetworkSecurityPolicy.kt","line":31,"symbol":"ShadowNetworkSecurityPolicy","kind":"class","lang":"kotlin","doc":"Gives tests a [NetworkSecurityPolicy] with domain encryption modes of their choosing. The platform constructor is private, so instances come from [create] rather than from a subclass.","code":"@SuppressSignatureCheck\n@Implements(NetworkSecurityPolicy::class)\nclass ShadowNetworkSecurityPolicy {\n lateinit var domainEncryptionModes: Map\n\n @Implementation\n fun getDomainEncryptionMode(hostname: String): Int = domainEncryptionModes[hostname] ?: DOMAIN_ENCRYPTION_MODE_UNKNOWN\n\n companion object {\n /**\n * Returns a policy that reports [domainEncryptionModes], and [DOMAIN_ENCRYPTION_MODE_UNKNOWN]\n * for other hosts.\n */\n fun create(domainEncryptionModes: Map): NetworkSecurityPolicy {\n val result = Shadow.newInstanceOf(NetworkSecurityPolicy::class.java)\n val shadow = Shadow.extract(result)\n shadow.domainEncryptionModes = domainEncryptionModes\n return result\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowNetworkSecurityPolicy.kt","line":36,"symbol":"getDomainEncryptionMode","kind":"function","lang":"kotlin","code":"@Implementation\n fun getDomainEncryptionMode(hostname: String): Int = domainEncryptionModes[hostname] ?: DOMAIN_ENCRYPTION_MODE_UNKNOWN"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/android/ShadowNetworkSecurityPolicy.kt","line":44,"symbol":"create","kind":"function","lang":"kotlin","doc":"Returns a policy that reports [domainEncryptionModes], and [DOMAIN_ENCRYPTION_MODE_UNKNOWN] for other hosts.","code":"fun create(domainEncryptionModes: Map): NetworkSecurityPolicy {\n val result = Shadow.newInstanceOf(NetworkSecurityPolicy::class.java)\n val shadow = Shadow.extract(result)\n shadow.domainEncryptionModes = domainEncryptionModes\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixTesting.android.kt","line":22,"symbol":"PublicSuffixTestRunner","kind":"type","lang":"kotlin","code":"actual typealias PublicSuffixTestRunner = RobolectricTestRunner"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixTesting.android.kt","line":24,"symbol":"beforePublicSuffixTest","kind":"function","lang":"kotlin","code":"actual fun beforePublicSuffixTest() {\n PlatformRegistry.applicationContext = ApplicationProvider.getApplicationContext()\n}"} {"repo":"okhttp","file":"okhttp/src/androidHostTest/resources/okhttp3/robolectric.properties","line":2,"symbol":"sdk","kind":"field","lang":"properties","code":"sdk=35"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/OkHttp.android.kt","line":22,"symbol":"OkHttp","kind":"object","lang":"kotlin","code":"actual object OkHttp {\n @JvmField\n actual val VERSION: String = CONST_VERSION\n\n /**\n * Configure the ApplicationContext. Not needed unless the AndroidX Startup [Initializer] is disabled, or running\n * a robolectric test.\n *\n * The functionality that will fail without a valid Context is primarily Cookies and URL Domain handling, but\n * may expand in the future.\n */\n fun initialize(applicationContext: Context) {\n if (PlatformRegistry.applicationContext == null) {\n // Make sure we aren't using an Activity or Service Context\n PlatformRegistry.applicationContext = applicationContext.applicationContext\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/OkHttp.android.kt","line":33,"symbol":"initialize","kind":"function","lang":"kotlin","doc":"Configure the ApplicationContext. Not needed unless the AndroidX Startup [Initializer] is disabled, or running a robolectric test. The functionality that will fail without a valid Context is primarily Cookies and URL Domain handling, but may expand in the future.","code":"fun initialize(applicationContext: Context) {\n if (PlatformRegistry.applicationContext == null) {\n // Make sure we aren't using an Activity or Service Context\n PlatformRegistry.applicationContext = applicationContext.applicationContext\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":56,"symbol":"AndroidDns","kind":"class","lang":"kotlin","doc":"A [Dns] backed by Android's system resolver, with Encrypted Client Hello (ECH) support from Android's [DnsResolver]. IP addresses come from the system resolver — [InetAddress.getAllByName] or [Network.getAllByName] when [network] is non-null. It makes an optional `HTTPS` query for service metadata such as ECH.","code":"@RequiresApi(29)\n@SuppressSignatureCheck\nclass AndroidDns internal constructor(\n internal val dnsResolver: DnsResolver,\n internal val network: Network?,\n dnsCache: DnsCache,\n internal val includeServiceMetadata: Boolean,\n /** Runs inline; the executor only hands off DnsResolver's callbacks. */\n internal val executor: Executor,\n private val taskRunner: TaskRunner,\n lazyNetworkSecurityPolicy: Lazy,\n) : Dns {\n constructor(\n dnsResolver: DnsResolver = DnsResolver.getInstance(),\n network: Network? = null,\n dnsCache: DnsCache = DnsCache(),\n /**\n * True to also query the `HTTPS` record for service metadata. Keep this on: it enables privacy\n * features such as Encrypted Client Hello (ECH) for the HTTPS call. Set it to false only when\n * you want to disable ECH.\n */\n includeServiceMetadata: Boolean = true,\n ) : this(\n dnsResolver = dnsResolver,\n network = network,\n dnsCache = dnsCache,\n includeServiceMetadata = includeServiceMetadata,\n executor = Executor { it.run() },\n taskRunner = TaskRunner.INSTANCE,\n lazyNetworkSecurityPolicy = lazy { NetworkSecurityPolicy.getInstance() },\n )\n\n private val networkSecu"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":100,"symbol":"lookup","kind":"function","lang":"kotlin","doc":"Resolves addresses only, for callers using the legacy blocking API. [Dns] cannot carry HTTPS/ECH metadata, so this skips that query rather than paying for it and discarding it.","code":"override fun lookup(hostname: String): List =\n call(Dns.Request(hostname), includeServiceMetadata = false)\n .execute()\n .filterIsInstance()\n .map { it.address }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":106,"symbol":"newCall","kind":"function","lang":"kotlin","code":"override fun newCall(request: Dns.Request): Dns.Call = call(request, includeServiceMetadata = includeServiceMetadata)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":108,"symbol":"call","kind":"function","lang":"kotlin","code":"private fun call(\n request: Dns.Request,\n includeServiceMetadata: Boolean,\n ) = StateMachineDnsCall(\n taskRunner = taskRunner,\n request = request,\n queryFactory = queryFactory,\n // A single `A` query stands in for both families: the system resolver returns IPv4 and\n // IPv6 addresses together, so there's no separate `AAAA` query.\n includeIPv6 = false,\n includeServiceMetadata = includeServiceMetadata && includeServiceMetadataForRequest(request),\n )"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":129,"symbol":"includeServiceMetadataForRequest","kind":"function","lang":"kotlin","doc":"so we only fetch them if they'll be useful. The main user of these records is Encrypted Client Hello (ECH). Android's HTTPS stack only supports ECH on API 37+, and only if configured via [NetworkSecurityPolicy]. If both are true, we fetch the ECH records.","code":"private fun includeServiceMetadataForRequest(request: Dns.Request): Boolean {\n if (Build.VERSION.SDK_INT < 37) return false\n\n return when (networkSecurityPolicy.getDomainEncryptionMode(request.hostname)) {\n DOMAIN_ENCRYPTION_MODE_ENABLED, DOMAIN_ENCRYPTION_MODE_OPPORTUNISTIC -> true\n else -> false\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":139,"symbol":"AndroidQuery","kind":"class","lang":"kotlin","doc":"One outstanding transport-layer query.","code":"private inner class AndroidQuery(\n private val question: Question,\n ) : DnsQuery {\n /** Only the `HTTPS` query reaches [DnsResolver], which is the API that takes a signal. */\n private val cancellationSignal = if (question.type == TYPE_HTTPS) CancellationSignal() else null\n\n override fun enqueue(callback: DnsQuery.Callback) {\n when (question.type) {\n TYPE_A -> resolveAddresses(callback)\n\n TYPE_HTTPS -> queryServiceMetadata(callback)\n\n // AndroidDns only ever issues `A` and `HTTPS` queries (includeIPv6 = false, so no `AAAA`).\n else -> error(\"unexpected query type ${question.type}\")\n }\n }\n\n /**\n * Resolves IP addresses through the system resolver. This is a blocking call, so it runs on a\n * [TaskRunner] thread. The addresses are wrapped in a synthetic [DnsMessage] because that's\n * the only shape [StateMachineDnsCall] accepts — the system resolver gives us decoded\n * addresses rather than a wire-format message.\n */\n private fun resolveAddresses(callback: DnsQuery.Callback) {\n taskRunner.newQueue().execute(\"${question.name} dns\", cancelable = false) {\n try {\n val addresses =\n "} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":145,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(callback: DnsQuery.Callback) {\n when (question.type) {\n TYPE_A -> resolveAddresses(callback)\n\n TYPE_HTTPS -> queryServiceMetadata(callback)\n\n // AndroidDns only ever issues `A` and `HTTPS` queries (includeIPv6 = false, so no `AAAA`).\n else -> error(\"unexpected query type ${question.type}\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":162,"symbol":"resolveAddresses","kind":"function","lang":"kotlin","doc":"Resolves IP addresses through the system resolver. This is a blocking call, so it runs on a [TaskRunner] thread. The addresses are wrapped in a synthetic [DnsMessage] because that's the only shape [StateMachineDnsCall] accepts — the system resolver gives us decoded addresses rather than a wire-format message.","code":"private fun resolveAddresses(callback: DnsQuery.Callback) {\n taskRunner.newQueue().execute(\"${question.name} dns\", cancelable = false) {\n try {\n val addresses =\n network?.getAllByName(question.name)\n ?: InetAddress.getAllByName(question.name)\n callback.onResponse(response(addresses))\n } catch (e: UnknownHostException) {\n callback.onFailure(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":179,"symbol":"response","kind":"function","lang":"kotlin","doc":"Wraps system-resolved [addresses] in a successful [DnsMessage] so they can flow through [DnsQuery.Callback], which only accepts wire-format responses.","code":"private fun response(addresses: Array) =\n DnsMessage.response(\n questions = listOf(question),\n answers =\n addresses.map { address ->\n ResourceRecord.IpAddress(\n name = question.name,\n timeToLive = 0,\n address = address,\n )\n },\n )"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":204,"symbol":"queryServiceMetadata","kind":"function","lang":"kotlin","doc":"an absent `HTTPS` record from a query that errored. `WrongConstant` is suppressed because OkHttp's [TYPE_HTTPS] is the DNS wire value (65), the same as the platform's `DnsResolver.TYPE_HTTPS`. We use ours so the query stays valid on API 29+; `DnsResolver.TYPE_HTTPS` was only added in API 37.","code":"@SuppressLint(\"WrongConstant\")\n @Suppress(\"ktlint:standard:comment-wrapping\")\n private fun queryServiceMetadata(callback: DnsQuery.Callback) {\n val dnsResolverCallback =\n object : DnsResolver.Callback {\n override fun onAnswer(\n answer: ByteArray,\n rcode: Int,\n ) {\n val message =\n try {\n DnsMessageReader(Buffer().write(answer)).read()\n } catch (e: IOException) {\n return callback.onFailure(e)\n }\n // The state machine turns a non-success rcode into a failure of its own.\n callback.onResponse(message)\n }\n\n override fun onError(e: DnsResolver.DnsException) {\n callback.onFailure(IOException(\"HTTPS query failed with code ${e.code}\", e))\n }\n }\n\n try {\n dnsResolver.rawQuery(\n /* network = */ network,\n /* domain = */ question.name,\n /* nsClass = */ DnsResolver.CLASS_IN,\n /* nsType = */ TYPE_HTTPS,\n /* flags = */ DnsResolver.FLAG_EMPTY,\n /* executor = */ executor,\n /* cancellationSignal = */ cancellationSign"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":209,"symbol":"onAnswer","kind":"function","lang":"kotlin","code":"override fun onAnswer(\n answer: ByteArray,\n rcode: Int,\n ) {\n val message =\n try {\n DnsMessageReader(Buffer().write(answer)).read()\n } catch (e: IOException) {\n return callback.onFailure(e)\n }\n // The state machine turns a non-success rcode into a failure of its own.\n callback.onResponse(message)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":223,"symbol":"onError","kind":"function","lang":"kotlin","code":"override fun onError(e: DnsResolver.DnsException) {\n callback.onFailure(IOException(\"HTTPS query failed with code ${e.code}\", e))\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/android/AndroidDns.kt","line":253,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"Cancels a query. Only the `HTTPS` query reaches [DnsResolver]; the address lookup runs to completion and its result is discarded by [StateMachineDnsCall], which ignores callbacks once canceled.","code":"override fun cancel() {\n cancellationSignal?.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":48,"symbol":"Android10Platform","kind":"class","lang":"kotlin","doc":"Android 10+ (API 29+).","code":"@SuppressSignatureCheck\nclass Android10Platform :\n Platform(),\n ContextAwarePlatform {\n override var applicationContext: Context? = null\n\n private val socketAdapters =\n listOfNotNull(\n Android17SocketAdapter.buildIfSupported(),\n Android10SocketAdapter.buildIfSupported(),\n DeferredSocketAdapter(AndroidSocketAdapter.playProviderFactory),\n // Delay and Defer any initialisation of Conscrypt and BouncyCastle\n DeferredSocketAdapter(ConscryptSocketAdapter.factory),\n DeferredSocketAdapter(BouncyCastleSocketAdapter.factory),\n ).filter { it.isSupported() }\n\n override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? =\n socketAdapters\n .find { it.matchesSocketFactory(sslSocketFactory) }\n ?.trustManager(sslSocketFactory)\n\n override fun newSSLContext(): SSLContext {\n StrictMode.noteSlowCall(\"newSSLContext\")\n\n return super.newSSLContext()\n }\n\n override fun buildTrustRootIndex(trustManager: X509TrustManager): TrustRootIndex {\n StrictMode.noteSlowCall(\"buildTrustRootIndex\")\n\n return super.buildTrustRootIndex(trustManager)\n }\n\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: Str"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":64,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? =\n socketAdapters\n .find { it.matchesSocketFactory(sslSocketFactory) }\n ?.trustManager(sslSocketFactory)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":69,"symbol":"newSSLContext","kind":"function","lang":"kotlin","code":"override fun newSSLContext(): SSLContext {\n StrictMode.noteSlowCall(\"newSSLContext\")\n\n return super.newSSLContext()\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":75,"symbol":"buildTrustRootIndex","kind":"function","lang":"kotlin","code":"override fun buildTrustRootIndex(trustManager: X509TrustManager): TrustRootIndex {\n StrictMode.noteSlowCall(\"buildTrustRootIndex\")\n\n return super.buildTrustRootIndex(trustManager)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":81,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n // No TLS extensions if the socket class is custom.\n socketAdapters\n .find { it.matchesSocket(sslSocket) }\n ?.configureTlsExtensions(sslSocket, hostname, protocols, echConfigList)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":93,"symbol":"echRetryPlan","kind":"function","lang":"kotlin","code":"@SuppressLint(\"NewApi\")\n override fun echRetryPlan(exception: SSLException): EchRetryPlan? {\n if (Build.VERSION.SDK_INT < 37 || exception !is EchConfigMismatchException) return null\n\n val publicName = exception.publicHostname ?: return null\n return EchRetryPlan.getOrNull(\n publicName = publicName,\n configList = exception.retryConfigList?.toBytes()?.toByteString(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":104,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n // No TLS extensions if the socket class is custom.\n socketAdapters.find { it.matchesSocket(sslSocket) }?.getSelectedProtocol(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":108,"symbol":"getStackTraceForCloseable","kind":"function","lang":"kotlin","code":"override fun getStackTraceForCloseable(closer: String): Any? =\n if (Build.VERSION.SDK_INT >= 30) {\n CloseGuard().apply { open(closer) }\n } else {\n super.getStackTraceForCloseable(closer)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":115,"symbol":"logCloseableLeak","kind":"function","lang":"kotlin","code":"override fun logCloseableLeak(\n message: String,\n stackTrace: Any?,\n ) {\n if (Build.VERSION.SDK_INT >= 30) {\n (stackTrace as CloseGuard).warnIfOpen()\n } else {\n // Unable to report via CloseGuard. As a last-ditch effort, send it to the logger.\n super.logCloseableLeak(message, stackTrace)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":127,"symbol":"isCleartextTrafficPermitted","kind":"function","lang":"kotlin","code":"@SuppressLint(\"NewApi\")\n override fun isCleartextTrafficPermitted(hostname: String): Boolean =\n NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(hostname)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":131,"symbol":"buildCertificateChainCleaner","kind":"function","lang":"kotlin","code":"override fun buildCertificateChainCleaner(trustManager: X509TrustManager): CertificateChainCleaner =\n AndroidCertificateChainCleaner.buildIfSupported(trustManager) ?: super.buildCertificateChainCleaner(trustManager)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":134,"symbol":"log","kind":"function","lang":"kotlin","code":"override fun log(\n message: String,\n level: Int,\n t: Throwable?,\n ) {\n if (level == WARN) {\n Log.w(Tag, message, t)\n } else {\n Log.i(Tag, message, t)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/Android10Platform.kt","line":149,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): Platform? = if (isSupported) Android10Platform() else null"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":48,"symbol":"AndroidPlatform","kind":"class","lang":"kotlin","doc":"Android 5 to 9 (API 21 to 28).","code":"@SuppressSignatureCheck\nclass AndroidPlatform :\n Platform(),\n ContextAwarePlatform {\n override var applicationContext: Context? = null\n\n private val socketAdapters =\n listOfNotNull(\n StandardAndroidSocketAdapter.buildIfSupported(),\n DeferredSocketAdapter(AndroidSocketAdapter.playProviderFactory),\n // Delay and Defer any initialisation of Conscrypt and BouncyCastle\n DeferredSocketAdapter(ConscryptSocketAdapter.factory),\n DeferredSocketAdapter(BouncyCastleSocketAdapter.factory),\n ).filter { it.isSupported() }\n\n @Throws(IOException::class)\n override fun connectSocket(\n socket: Socket,\n address: InetSocketAddress,\n connectTimeout: Int,\n ) {\n try {\n socket.connect(address, connectTimeout)\n } catch (e: ClassCastException) {\n // On android 8.0, socket.connect throws a ClassCastException due to a bug\n // see https://issuetracker.google.com/issues/63649622\n if (Build.VERSION.SDK_INT == 26) {\n throw IOException(\"Exception in connect\", e)\n } else {\n throw e\n }\n }\n }\n\n override fun newSSLContext(): SSLContext {\n StrictMode.noteSlowCall(\"newSSLContext\")\n\n return super.newSSLContext()\n }\n"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":63,"symbol":"connectSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun connectSocket(\n socket: Socket,\n address: InetSocketAddress,\n connectTimeout: Int,\n ) {\n try {\n socket.connect(address, connectTimeout)\n } catch (e: ClassCastException) {\n // On android 8.0, socket.connect throws a ClassCastException due to a bug\n // see https://issuetracker.google.com/issues/63649622\n if (Build.VERSION.SDK_INT == 26) {\n throw IOException(\"Exception in connect\", e)\n } else {\n throw e\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":82,"symbol":"newSSLContext","kind":"function","lang":"kotlin","code":"override fun newSSLContext(): SSLContext {\n StrictMode.noteSlowCall(\"newSSLContext\")\n\n return super.newSSLContext()\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":88,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? =\n socketAdapters\n .find { it.matchesSocketFactory(sslSocketFactory) }\n ?.trustManager(sslSocketFactory)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":93,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n // No TLS extensions if the socket class is custom.\n socketAdapters\n .find { it.matchesSocket(sslSocket) }\n ?.configureTlsExtensions(sslSocket, hostname, protocols, echConfigList)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":105,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n // No TLS extensions if the socket class is custom.\n socketAdapters.find { it.matchesSocket(sslSocket) }?.getSelectedProtocol(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":109,"symbol":"isCleartextTrafficPermitted","kind":"function","lang":"kotlin","code":"override fun isCleartextTrafficPermitted(hostname: String): Boolean =\n when {\n Build.VERSION.SDK_INT >= 24 -> NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(hostname)\n Build.VERSION.SDK_INT >= 23 -> NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted\n else -> true\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":116,"symbol":"buildCertificateChainCleaner","kind":"function","lang":"kotlin","code":"override fun buildCertificateChainCleaner(trustManager: X509TrustManager): CertificateChainCleaner =\n AndroidCertificateChainCleaner.buildIfSupported(trustManager) ?: super.buildCertificateChainCleaner(trustManager)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":119,"symbol":"buildTrustRootIndex","kind":"function","lang":"kotlin","code":"override fun buildTrustRootIndex(trustManager: X509TrustManager): TrustRootIndex =\n try {\n StrictMode.noteSlowCall(\"buildTrustRootIndex\")\n\n // From org.conscrypt.TrustManagerImpl, we want the method with this signature:\n // private TrustAnchor findTrustAnchorByIssuerAndSignature(X509Certificate lastCert);\n val method =\n trustManager.javaClass.getDeclaredMethod(\n \"findTrustAnchorByIssuerAndSignature\",\n X509Certificate::class.java,\n )\n method.isAccessible = true\n CustomTrustRootIndex(trustManager, method)\n } catch (e: NoSuchMethodException) {\n super.buildTrustRootIndex(trustManager)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":136,"symbol":"getHandshakeServerNames","kind":"function","lang":"kotlin","code":"override fun getHandshakeServerNames(sslSocket: SSLSocket): List {\n // The superclass implementation requires APIs not available until API 25+.\n if (Build.VERSION.SDK_INT <= 24) return listOf()\n return super.getHandshakeServerNames(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":142,"symbol":"log","kind":"function","lang":"kotlin","code":"override fun log(\n message: String,\n level: Int,\n t: Throwable?,\n ) {\n if (level == WARN) {\n Log.w(Tag, message, t)\n } else {\n Log.i(Tag, message, t)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":161,"symbol":"CustomTrustRootIndex","kind":"class","lang":"kotlin","doc":"A trust manager for Android applications that customize the trust manager. This class exploits knowledge of Android implementation details. This class is potentially much faster to initialize than [BasicTrustRootIndex] because it doesn't need to load and index trusted CA certificates.","code":"internal data class CustomTrustRootIndex(\n private val trustManager: X509TrustManager,\n private val findByIssuerAndSignatureMethod: Method,\n ) : TrustRootIndex {\n override fun findByIssuerAndSignature(cert: X509Certificate): X509Certificate? =\n try {\n val trustAnchor =\n findByIssuerAndSignatureMethod.invoke(\n trustManager,\n cert,\n ) as TrustAnchor\n trustAnchor.trustedCert\n } catch (e: IllegalAccessException) {\n throw AssertionError(\"unable to get issues and signature\", e)\n } catch (_: InvocationTargetException) {\n null\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":165,"symbol":"findByIssuerAndSignature","kind":"function","lang":"kotlin","code":"override fun findByIssuerAndSignature(cert: X509Certificate): X509Certificate? =\n try {\n val trustAnchor =\n findByIssuerAndSignatureMethod.invoke(\n trustManager,\n cert,\n ) as TrustAnchor\n trustAnchor.trustedCert\n } catch (e: IllegalAccessException) {\n throw AssertionError(\"unable to get issues and signature\", e)\n } catch (_: InvocationTargetException) {\n null\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/AndroidPlatform.kt","line":185,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): Platform? = if (isSupported) AndroidPlatform() else null"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/ContextAwarePlatform.kt","line":20,"symbol":"ContextAwarePlatform","kind":"interface","lang":"kotlin","code":"interface ContextAwarePlatform {\n var applicationContext: Context?\n}"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/PlatformInitializer.kt","line":24,"symbol":"PlatformInitializer","kind":"class","lang":"kotlin","doc":"Androidx Startup initializer to ensure that the AndroidPlatform has access to the application context.","code":"class PlatformInitializer : Initializer {\n override fun create(context: Context): Platform {\n PlatformRegistry.applicationContext = context\n\n return Platform.get()\n }\n\n override fun dependencies(): List>> = listOf()\n}"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/PlatformInitializer.kt","line":25,"symbol":"create","kind":"function","lang":"kotlin","code":"override fun create(context: Context): Platform {\n PlatformRegistry.applicationContext = context\n\n return Platform.get()\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/PlatformInitializer.kt","line":31,"symbol":"dependencies","kind":"function","lang":"kotlin","code":"override fun dependencies(): List>> = listOf()"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/PlatformRegistry.kt","line":23,"symbol":"PlatformRegistry","kind":"object","lang":"kotlin","code":"actual object PlatformRegistry {\n actual fun findPlatform(): Platform {\n AndroidLog.enable()\n\n val androidPlatform =\n Android10Platform.buildIfSupported()\n ?: AndroidPlatform.buildIfSupported()\n if (androidPlatform != null) return androidPlatform\n\n // If the API version is 0, assume this is the Android artifact, but running on the JVM without Robolectric.\n if (Build.VERSION.SDK_INT == 0) {\n return Jdk9Platform.buildIfSupported()\n ?: Platform()\n }\n\n throw IllegalStateException(\"Expected Android API level 21+ but was ${Build.VERSION.SDK_INT}\")\n }\n\n actual val isAndroid: Boolean\n get() = true\n\n var applicationContext: Context?\n get() = (Platform.get() as? ContextAwarePlatform)?.applicationContext\n set(value) {\n (Platform.get() as? ContextAwarePlatform)?.applicationContext = value\n }\n}"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/PlatformRegistry.kt","line":24,"symbol":"findPlatform","kind":"function","lang":"kotlin","code":"actual fun findPlatform(): Platform {\n AndroidLog.enable()\n\n val androidPlatform =\n Android10Platform.buildIfSupported()\n ?: AndroidPlatform.buildIfSupported()\n if (androidPlatform != null) return androidPlatform\n\n // If the API version is 0, assume this is the Android artifact, but running on the JVM without Robolectric.\n if (Build.VERSION.SDK_INT == 0) {\n return Jdk9Platform.buildIfSupported()\n ?: Platform()\n }\n\n throw IllegalStateException(\"Expected Android API level 21+ but was ${Build.VERSION.SDK_INT}\")\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt","line":35,"symbol":"Android10SocketAdapter","kind":"class","lang":"kotlin","doc":"Simple non-reflection SocketAdapter for Android Q+. These API assumptions make it unsuitable for use on earlier Android versions.","code":"@SuppressLint(\"NewApi\")\n@SuppressSignatureCheck\nclass Android10SocketAdapter : SocketAdapter {\n override fun matchesSocket(sslSocket: SSLSocket): Boolean = SSLSockets.isSupportedSocket(sslSocket)\n\n override fun isSupported(): Boolean = Companion.isSupported()\n\n @SuppressLint(\"NewApi\")\n override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n try {\n // SSLSocket.getApplicationProtocol returns \"\" if application protocols values will not\n // be used. Observed if you didn't specify SSLParameters.setApplicationProtocols\n when (val protocol = sslSocket.applicationProtocol) {\n null, \"\" -> null\n else -> protocol\n }\n } catch (e: UnsupportedOperationException) {\n // https://docs.oracle.com/javase/9/docs/api/javax/net/ssl/SSLSocket.html#getApplicationProtocol--\n null\n }\n\n @SuppressLint(\"NewApi\")\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n try {\n SSLSockets.setUseSessionTickets(sslSocket, true)\n\n val sslParameters = sslSocket.sslParameters\n\n // Enable ALPN.\n sslParameters.applicationProtocols"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt","line":38,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = SSLSockets.isSupportedSocket(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt","line":40,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"override fun isSupported(): Boolean = Companion.isSupported()"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt","line":42,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"@SuppressLint(\"NewApi\")\n override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n try {\n // SSLSocket.getApplicationProtocol returns \"\" if application protocols values will not\n // be used. Observed if you didn't specify SSLParameters.setApplicationProtocols\n when (val protocol = sslSocket.applicationProtocol) {\n null, \"\" -> null\n else -> protocol\n }\n } catch (e: UnsupportedOperationException) {\n // https://docs.oracle.com/javase/9/docs/api/javax/net/ssl/SSLSocket.html#getApplicationProtocol--\n null\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt","line":56,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"@SuppressLint(\"NewApi\")\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n try {\n SSLSockets.setUseSessionTickets(sslSocket, true)\n\n val sslParameters = sslSocket.sslParameters\n\n // Enable ALPN.\n sslParameters.applicationProtocols = Platform.alpnProtocolNames(protocols).toTypedArray()\n\n sslSocket.sslParameters = sslParameters\n } catch (iae: IllegalArgumentException) {\n // probably java.lang.IllegalArgumentException: Invalid input to toASCII from IDN.toASCII\n throw IOException(\"Android internal error\", iae)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt","line":80,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): SocketAdapter? = if (isSupported()) Android10SocketAdapter() else null"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android10SocketAdapter.kt","line":82,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"@androidx.annotation.ChecksSdkIntAtLeast(api = 29)\n fun isSupported() = isAndroid && Build.VERSION.SDK_INT >= 29"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android17SocketAdapter.kt","line":43,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = SSLSockets.isSupportedSocket(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android17SocketAdapter.kt","line":45,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"override fun isSupported(): Boolean = Companion.isSupported()"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android17SocketAdapter.kt","line":47,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n // SSLSocket.getApplicationProtocol returns \"\" if application protocols values will not\n // be used. Observed if you didn't specify SSLParameters.setApplicationProtocols\n when (val protocol = sslSocket.applicationProtocol) {\n null, \"\" -> null\n else -> protocol\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android17SocketAdapter.kt","line":55,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n SSLSockets.setUseSessionTickets(sslSocket, true)\n\n val sslParameters =\n try {\n sslSocket.sslParameters\n } catch (iae: IllegalArgumentException) {\n // Conscrypt's getSSLParameters() eagerly builds an SNIHostName from the peer host and\n // throws \"Invalid input to toASCII\" (via IDN.toASCII) for names that violate STD3 ASCII,\n // such as hostnames containing underscores. The JDK skips such names instead of throwing;\n // wrap it as an IOException so the call fails cleanly. Mirrors Android10SocketAdapter.\n throw IOException(\"Android internal error\", iae)\n }\n\n // Enable ALPN.\n sslParameters.applicationProtocols = Platform.alpnProtocolNames(protocols).toTypedArray()\n\n sslSocket.sslParameters = sslParameters\n\n if (hostname != null && echConfigList != null) {\n // TODO put behind Network Policy\n\n // The ECH config was resolved during DNS (RealCall.resolveAddresses); just apply it here.\n // A config we can"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android17SocketAdapter.kt","line":101,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): SocketAdapter? = if (isSupported()) Android17SocketAdapter() else null"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/Android17SocketAdapter.kt","line":103,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"@ChecksSdkIntAtLeast(api = 37)\n fun isSupported() = isAndroid && Build.VERSION.SDK_INT >= 37"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidCertificateChainCleaner.kt","line":33,"symbol":"AndroidCertificateChainCleaner","kind":"class","lang":"kotlin","doc":"Android implementation of CertificateChainCleaner using direct Android API calls. Not used if X509TrustManager doesn't implement [X509TrustManager.checkServerTrusted] with an additional host param.","code":"internal class AndroidCertificateChainCleaner(\n private val trustManager: X509TrustManager,\n private val x509TrustManagerExtensions: X509TrustManagerExtensions,\n) : CertificateChainCleaner() {\n @Suppress(\"UNCHECKED_CAST\")\n @Throws(SSLPeerUnverifiedException::class)\n @SuppressSignatureCheck\n override fun clean(\n chain: List,\n hostname: String,\n ): List {\n val certificates = (chain as List).toTypedArray()\n try {\n return x509TrustManagerExtensions.checkServerTrusted(certificates, \"RSA\", hostname)\n } catch (ce: CertificateException) {\n throw SSLPeerUnverifiedException(ce.message).apply { initCause(ce) }\n }\n }\n\n override fun equals(other: Any?): Boolean =\n other is AndroidCertificateChainCleaner &&\n other.trustManager === this.trustManager\n\n override fun hashCode(): Int = System.identityHashCode(trustManager)\n\n companion object {\n @SuppressSignatureCheck\n fun buildIfSupported(trustManager: X509TrustManager): AndroidCertificateChainCleaner? {\n val extensions =\n try {\n X509TrustManagerExtensions(trustManager)\n } catch (iae: IllegalArgumentException) {\n // X5"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidCertificateChainCleaner.kt","line":37,"symbol":"clean","kind":"function","lang":"kotlin","code":"@Suppress(\"UNCHECKED_CAST\")\n @Throws(SSLPeerUnverifiedException::class)\n @SuppressSignatureCheck\n override fun clean(\n chain: List,\n hostname: String,\n ): List {\n val certificates = (chain as List).toTypedArray()\n try {\n return x509TrustManagerExtensions.checkServerTrusted(certificates, \"RSA\", hostname)\n } catch (ce: CertificateException) {\n throw SSLPeerUnverifiedException(ce.message).apply { initCause(ce) }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidCertificateChainCleaner.kt","line":52,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other is AndroidCertificateChainCleaner &&\n other.trustManager === this.trustManager"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidCertificateChainCleaner.kt","line":56,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int = System.identityHashCode(trustManager)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidCertificateChainCleaner.kt","line":59,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"@SuppressSignatureCheck\n fun buildIfSupported(trustManager: X509TrustManager): AndroidCertificateChainCleaner? {\n val extensions =\n try {\n X509TrustManagerExtensions(trustManager)\n } catch (iae: IllegalArgumentException) {\n // X509TrustManagerExtensions checks for checkServerTrusted(X509Certificate[], String, String)\n null\n }\n\n return when {\n extensions != null -> AndroidCertificateChainCleaner(trustManager, extensions)\n else -> null\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidLog.kt","line":38,"symbol":"AndroidLogHandler","kind":"object","lang":"kotlin","code":"object AndroidLogHandler : Handler() {\n override fun publish(record: LogRecord) {\n androidLog(record.loggerName, record.androidLevel, record.message, record.thrown)\n }\n\n override fun flush() {\n }\n\n override fun close() {\n }\n}"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidLog.kt","line":39,"symbol":"publish","kind":"function","lang":"kotlin","code":"override fun publish(record: LogRecord) {\n androidLog(record.loggerName, record.androidLevel, record.message, record.thrown)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidLog.kt","line":43,"symbol":"flush","kind":"function","lang":"kotlin","code":"override fun flush() {\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidLog.kt","line":46,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidLog.kt","line":72,"symbol":"androidLog","kind":"function","lang":"kotlin","code":"internal fun androidLog(\n loggerName: String,\n logLevel: Int,\n message: String,\n t: Throwable? = null,\n ) {\n val tag = loggerTag(loggerName)\n\n if (Log.isLoggable(tag, logLevel)) {\n var logMessage = message\n if (t != null) logMessage = logMessage + '\\n'.toString() + Log.getStackTraceString(t)\n\n // Split by line, then ensure each line can fit into Log's maximum length.\n var i = 0\n val length = logMessage.length\n while (i < length) {\n var newline = logMessage.indexOf('\\n', i)\n newline = if (newline != -1) newline else length\n do {\n val end = minOf(newline, i + MAX_LOG_LENGTH)\n Log.println(logLevel, tag, logMessage.substring(i, end))\n i = end\n } while (i < newline)\n i++\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidLog.kt","line":100,"symbol":"loggerTag","kind":"function","lang":"kotlin","code":"private fun loggerTag(loggerName: String): String {\n // We need to handle long logger names before they hit Log.\n // java.lang.IllegalArgumentException: Log tag \"okhttp3.mockwebserver.MockWebServer\" exceeds limit of 23 characters\n return knownLoggers[loggerName] ?: loggerName.take(23)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidLog.kt","line":106,"symbol":"enable","kind":"function","lang":"kotlin","code":"fun enable() {\n try {\n for ((logger, tag) in knownLoggers) {\n enableLogging(logger, tag)\n }\n } catch (re: RuntimeException) {\n // Happens with non-robolectric unit tests\n System.err.println(\"Possibly running android unit test without robolectric\")\n re.printStackTrace()\n } catch (ule: UnsatisfiedLinkError) {\n // Happens with Paparazzi - with Android classes on the classpath\n System.err.println(\"Possibly running android unit test without robolectric\")\n ule.printStackTrace()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidLog.kt","line":122,"symbol":"enableLogging","kind":"function","lang":"kotlin","code":"private fun enableLogging(\n logger: String,\n tag: String,\n ) {\n val logger = Logger.getLogger(logger)\n if (configuredLoggers.add(logger)) {\n logger.useParentHandlers = false\n // log based on levels at startup to avoid logging each frame\n logger.level =\n when {\n Log.isLoggable(tag, Log.DEBUG) -> Level.FINE\n Log.isLoggable(tag, Log.INFO) -> Level.INFO\n else -> Level.WARNING\n }\n logger.addHandler(AndroidLogHandler)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":34,"symbol":"AndroidSocketAdapter","kind":"class","lang":"kotlin","doc":"Modern reflection based SocketAdapter for Conscrypt class SSLSockets. This is used directly for providers where class name is known e.g. the Google Play Provider but we can't compile directly against it, or in fact reliably know if it is registered and on classpath.","code":"open class AndroidSocketAdapter(\n private val sslSocketClass: Class,\n) : SocketAdapter {\n private val setUseSessionTickets: Method =\n sslSocketClass.getDeclaredMethod(\"setUseSessionTickets\", Boolean::class.javaPrimitiveType)\n private val setHostname = sslSocketClass.getMethod(\"setHostname\", String::class.java)\n private val getAlpnSelectedProtocol = sslSocketClass.getMethod(\"getAlpnSelectedProtocol\")\n private val setAlpnProtocols =\n sslSocketClass.getMethod(\"setAlpnProtocols\", ByteArray::class.java)\n\n override fun isSupported(): Boolean = AndroidPlatform.isSupported\n\n override fun matchesSocket(sslSocket: SSLSocket): Boolean = sslSocketClass.isInstance(sslSocket)\n\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n // No TLS extensions if the socket class is custom.\n if (matchesSocket(sslSocket)) {\n try {\n // Enable session tickets.\n setUseSessionTickets.invoke(sslSocket, true)\n\n // Assume platform support on 24+\n if (hostname != null && Build.VERSION.SDK_INT <= 23) {\n // This is SSLParameters.setServerNa"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":44,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"override fun isSupported(): Boolean = AndroidPlatform.isSupported"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":46,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = sslSocketClass.isInstance(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":48,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n // No TLS extensions if the socket class is custom.\n if (matchesSocket(sslSocket)) {\n try {\n // Enable session tickets.\n setUseSessionTickets.invoke(sslSocket, true)\n\n // Assume platform support on 24+\n if (hostname != null && Build.VERSION.SDK_INT <= 23) {\n // This is SSLParameters.setServerNames() in API 24+.\n setHostname.invoke(sslSocket, hostname)\n }\n\n // Enable ALPN.\n setAlpnProtocols.invoke(\n sslSocket,\n Platform.concatLengthPrefixed(protocols),\n )\n } catch (e: IllegalAccessException) {\n throw AssertionError(e)\n } catch (e: InvocationTargetException) {\n throw AssertionError(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":79,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? {\n // No TLS extensions if the socket class is custom.\n if (!matchesSocket(sslSocket)) {\n return null\n }\n\n return try {\n val alpnResult = getAlpnSelectedProtocol.invoke(sslSocket) as ByteArray?\n alpnResult?.toString(Charsets.UTF_8)\n } catch (e: IllegalAccessException) {\n throw AssertionError(e)\n } catch (e: InvocationTargetException) {\n // https://github.com/lysine-dev/okhttp/issues/5587\n val cause = e.cause\n when {\n cause is NullPointerException && cause.message == \"ssl == null\" -> null\n else -> throw AssertionError(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":110,"symbol":"build","kind":"function","lang":"kotlin","doc":"Builds a SocketAdapter from an observed implementation class, by grabbing the Class reference to perform reflection on at runtime. @param actualSSLSocketClass the runtime class of Conscrypt class socket.","code":"private fun build(actualSSLSocketClass: Class): AndroidSocketAdapter {\n var possibleClass: Class? = actualSSLSocketClass\n while (possibleClass != null && possibleClass.simpleName != \"OpenSSLSocketImpl\") {\n possibleClass = possibleClass.superclass\n\n if (possibleClass == null) {\n throw AssertionError(\n \"No OpenSSLSocketImpl superclass of socket of type $actualSSLSocketClass\",\n )\n }\n }\n\n return AndroidSocketAdapter(possibleClass!!)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":125,"symbol":"factory","kind":"function","lang":"kotlin","code":"fun factory(packageName: String): DeferredSocketAdapter.Factory =\n object : DeferredSocketAdapter.Factory {\n override fun matchesSocket(sslSocket: SSLSocket): Boolean = sslSocket.javaClass.name.startsWith(\"$packageName.\")\n\n override fun create(sslSocket: SSLSocket): SocketAdapter = build(sslSocket.javaClass)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":127,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = sslSocket.javaClass.name.startsWith(\"$packageName.\")"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/AndroidSocketAdapter.kt","line":129,"symbol":"create","kind":"function","lang":"kotlin","code":"override fun create(sslSocket: SSLSocket): SocketAdapter = build(sslSocket.javaClass)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/BouncyCastleSocketAdapter.kt","line":27,"symbol":"BouncyCastleSocketAdapter","kind":"class","lang":"kotlin","doc":"Simple non-reflection SocketAdapter for BouncyCastle.","code":"class BouncyCastleSocketAdapter : SocketAdapter {\n override fun matchesSocket(sslSocket: SSLSocket): Boolean = sslSocket is BCSSLSocket\n\n override fun isSupported(): Boolean = isSupported\n\n override fun getSelectedProtocol(sslSocket: SSLSocket): String? {\n val s = sslSocket as BCSSLSocket\n\n return when (val protocol = s.applicationProtocol) {\n null, \"\" -> null\n else -> protocol\n }\n }\n\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n // No TLS extensions if the socket class is custom.\n if (matchesSocket(sslSocket)) {\n val bcSocket = sslSocket as BCSSLSocket\n\n val sslParameters = bcSocket.parameters\n\n // Enable ALPN.\n sslParameters.applicationProtocols = Platform.alpnProtocolNames(protocols).toTypedArray()\n\n bcSocket.parameters = sslParameters\n }\n }\n\n companion object {\n val factory =\n object : DeferredSocketAdapter.Factory {\n override fun matchesSocket(sslSocket: SSLSocket): Boolean = isSupported && sslSocket is BCSSLSocket\n\n override fun create(sslSocket: SSLSocket): SocketAdapter = BouncyCastle"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/BouncyCastleSocketAdapter.kt","line":28,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = sslSocket is BCSSLSocket"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/BouncyCastleSocketAdapter.kt","line":30,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"override fun isSupported(): Boolean = isSupported"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/BouncyCastleSocketAdapter.kt","line":32,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? {\n val s = sslSocket as BCSSLSocket\n\n return when (val protocol = s.applicationProtocol) {\n null, \"\" -> null\n else -> protocol\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/BouncyCastleSocketAdapter.kt","line":41,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n // No TLS extensions if the socket class is custom.\n if (matchesSocket(sslSocket)) {\n val bcSocket = sslSocket as BCSSLSocket\n\n val sslParameters = bcSocket.parameters\n\n // Enable ALPN.\n sslParameters.applicationProtocols = Platform.alpnProtocolNames(protocols).toTypedArray()\n\n bcSocket.parameters = sslParameters\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/BouncyCastleSocketAdapter.kt","line":63,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = isSupported && sslSocket is BCSSLSocket"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/BouncyCastleSocketAdapter.kt","line":65,"symbol":"create","kind":"function","lang":"kotlin","code":"override fun create(sslSocket: SSLSocket): SocketAdapter = BouncyCastleSocketAdapter()"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/ConscryptSocketAdapter.kt","line":28,"symbol":"ConscryptSocketAdapter","kind":"class","lang":"kotlin","doc":"Simple non-reflection SocketAdapter for Conscrypt when included as an application dependency directly.","code":"class ConscryptSocketAdapter : SocketAdapter {\n override fun matchesSocket(sslSocket: SSLSocket): Boolean = Conscrypt.isConscrypt(sslSocket)\n\n override fun isSupported(): Boolean = isSupported\n\n override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n when {\n matchesSocket(sslSocket) -> Conscrypt.getApplicationProtocol(sslSocket)\n else -> null // No TLS extensions if the socket class is custom.\n }\n\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n // No TLS extensions if the socket class is custom.\n if (matchesSocket(sslSocket)) {\n // Enable session tickets.\n Conscrypt.setUseSessionTickets(sslSocket, true)\n\n // Enable ALPN.\n val names = Platform.alpnProtocolNames(protocols)\n Conscrypt.setApplicationProtocols(sslSocket, names.toTypedArray())\n }\n }\n\n companion object {\n val factory =\n object : DeferredSocketAdapter.Factory {\n override fun matchesSocket(sslSocket: SSLSocket): Boolean = isSupported && Conscrypt.isConscrypt(sslSocket)\n\n override fun create(sslSocket: SSLSocket): SocketAdapter = "} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/ConscryptSocketAdapter.kt","line":29,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = Conscrypt.isConscrypt(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/ConscryptSocketAdapter.kt","line":31,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"override fun isSupported(): Boolean = isSupported"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/ConscryptSocketAdapter.kt","line":33,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n when {\n matchesSocket(sslSocket) -> Conscrypt.getApplicationProtocol(sslSocket)\n else -> null // No TLS extensions if the socket class is custom.\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/ConscryptSocketAdapter.kt","line":39,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n // No TLS extensions if the socket class is custom.\n if (matchesSocket(sslSocket)) {\n // Enable session tickets.\n Conscrypt.setUseSessionTickets(sslSocket, true)\n\n // Enable ALPN.\n val names = Platform.alpnProtocolNames(protocols)\n Conscrypt.setApplicationProtocols(sslSocket, names.toTypedArray())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/ConscryptSocketAdapter.kt","line":59,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = isSupported && Conscrypt.isConscrypt(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/ConscryptSocketAdapter.kt","line":61,"symbol":"create","kind":"function","lang":"kotlin","code":"override fun create(sslSocket: SSLSocket): SocketAdapter = ConscryptSocketAdapter()"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/ConscryptSocketAdapter.kt","line":81,"symbol":"atLeastVersion","kind":"function","lang":"kotlin","code":"fun atLeastVersion(\n major: Int,\n minor: Int = 0,\n patch: Int = 0,\n ): Boolean {\n val conscryptVersion = Conscrypt.version() ?: return false\n\n if (conscryptVersion.major() != major) {\n return conscryptVersion.major() > major\n }\n\n if (conscryptVersion.minor() != minor) {\n return conscryptVersion.minor() > minor\n }\n\n return conscryptVersion.patch() >= patch\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":30,"symbol":"DeferredSocketAdapter","kind":"class","lang":"kotlin","doc":"and initializing on first use. We use this because eager classpath checks cause confusion and excessive logging in Android, and we can't rely on classnames after proguard, so are probably best served by falling through to a situation of trying our least likely noisiest options.","code":"class DeferredSocketAdapter(\n private val socketAdapterFactory: Factory,\n) : SocketAdapter {\n private var delegate: SocketAdapter? = null\n\n override fun isSupported(): Boolean = true\n\n override fun matchesSocket(sslSocket: SSLSocket): Boolean = socketAdapterFactory.matchesSocket(sslSocket)\n\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n getDelegate(sslSocket)?.configureTlsExtensions(sslSocket, hostname, protocols, echConfigList)\n }\n\n override fun getSelectedProtocol(sslSocket: SSLSocket): String? = getDelegate(sslSocket)?.getSelectedProtocol(sslSocket)\n\n @Synchronized private fun getDelegate(sslSocket: SSLSocket): SocketAdapter? {\n if (this.delegate == null && socketAdapterFactory.matchesSocket(sslSocket)) {\n this.delegate = socketAdapterFactory.create(sslSocket)\n }\n\n return delegate\n }\n\n interface Factory {\n fun matchesSocket(sslSocket: SSLSocket): Boolean\n\n fun create(sslSocket: SSLSocket): SocketAdapter\n }\n}"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":35,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"override fun isSupported(): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":37,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"override fun matchesSocket(sslSocket: SSLSocket): Boolean = socketAdapterFactory.matchesSocket(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":39,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n getDelegate(sslSocket)?.configureTlsExtensions(sslSocket, hostname, protocols, echConfigList)\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":48,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? = getDelegate(sslSocket)?.getSelectedProtocol(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":50,"symbol":"getDelegate","kind":"function","lang":"kotlin","code":"@Synchronized private fun getDelegate(sslSocket: SSLSocket): SocketAdapter? {\n if (this.delegate == null && socketAdapterFactory.matchesSocket(sslSocket)) {\n this.delegate = socketAdapterFactory.create(sslSocket)\n }\n\n return delegate\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":58,"symbol":"Factory","kind":"interface","lang":"kotlin","code":"interface Factory {\n fun matchesSocket(sslSocket: SSLSocket): Boolean\n\n fun create(sslSocket: SSLSocket): SocketAdapter\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":59,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"fun matchesSocket(sslSocket: SSLSocket): Boolean"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/DeferredSocketAdapter.kt","line":61,"symbol":"create","kind":"function","lang":"kotlin","code":"fun create(sslSocket: SSLSocket): SocketAdapter"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/SocketAdapter.kt","line":24,"symbol":"SocketAdapter","kind":"interface","lang":"kotlin","code":"interface SocketAdapter {\n fun isSupported(): Boolean\n\n fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? = null\n\n fun matchesSocket(sslSocket: SSLSocket): Boolean\n\n fun matchesSocketFactory(sslSocketFactory: SSLSocketFactory): Boolean = false\n\n fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n )\n\n fun getSelectedProtocol(sslSocket: SSLSocket): String?\n}"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/SocketAdapter.kt","line":25,"symbol":"isSupported","kind":"function","lang":"kotlin","code":"fun isSupported(): Boolean"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/SocketAdapter.kt","line":27,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? = null"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/SocketAdapter.kt","line":29,"symbol":"matchesSocket","kind":"function","lang":"kotlin","code":"fun matchesSocket(sslSocket: SSLSocket): Boolean"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/SocketAdapter.kt","line":31,"symbol":"matchesSocketFactory","kind":"function","lang":"kotlin","code":"fun matchesSocketFactory(sslSocketFactory: SSLSocketFactory): Boolean = false"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/SocketAdapter.kt","line":33,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n )"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/SocketAdapter.kt","line":40,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"fun getSelectedProtocol(sslSocket: SSLSocket): String?"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/StandardAndroidSocketAdapter.kt","line":31,"symbol":"StandardAndroidSocketAdapter","kind":"class","lang":"kotlin","doc":"Base Android reflection based SocketAdapter for the built in Android SSLSocket. It's assumed to always be present with known class names on Android devices, so we build optimistically via [buildIfSupported]. But it also doesn't assume a compile time API.","code":"class StandardAndroidSocketAdapter(\n sslSocketClass: Class,\n private val sslSocketFactoryClass: Class,\n private val paramClass: Class<*>,\n) : AndroidSocketAdapter(sslSocketClass) {\n override fun matchesSocketFactory(sslSocketFactory: SSLSocketFactory): Boolean = sslSocketFactoryClass.isInstance(sslSocketFactory)\n\n override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? {\n val context: Any? =\n readFieldOrNull(\n sslSocketFactory,\n paramClass,\n \"sslParameters\",\n )\n val x509TrustManager =\n readFieldOrNull(\n context!!,\n X509TrustManager::class.java,\n \"x509TrustManager\",\n )\n return x509TrustManager\n ?: readFieldOrNull(\n context,\n X509TrustManager::class.java,\n \"trustManager\",\n )\n }\n\n companion object {\n @Suppress(\"UNCHECKED_CAST\", \"PrivateApi\")\n fun buildIfSupported(packageName: String = \"com.android.org.conscrypt\"): SocketAdapter? =\n try {\n val sslSocketClass =\n Class.forName(\"$packageName.OpenSSLSocketImpl\") as Class\n val sslSocketFactoryClass =\n Class.forName(\"$p"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/StandardAndroidSocketAdapter.kt","line":36,"symbol":"matchesSocketFactory","kind":"function","lang":"kotlin","code":"override fun matchesSocketFactory(sslSocketFactory: SSLSocketFactory): Boolean = sslSocketFactoryClass.isInstance(sslSocketFactory)"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/StandardAndroidSocketAdapter.kt","line":38,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? {\n val context: Any? =\n readFieldOrNull(\n sslSocketFactory,\n paramClass,\n \"sslParameters\",\n )\n val x509TrustManager =\n readFieldOrNull(\n context!!,\n X509TrustManager::class.java,\n \"x509TrustManager\",\n )\n return x509TrustManager\n ?: readFieldOrNull(\n context,\n X509TrustManager::class.java,\n \"trustManager\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/platform/android/StandardAndroidSocketAdapter.kt","line":60,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"@Suppress(\"UNCHECKED_CAST\", \"PrivateApi\")\n fun buildIfSupported(packageName: String = \"com.android.org.conscrypt\"): SocketAdapter? =\n try {\n val sslSocketClass =\n Class.forName(\"$packageName.OpenSSLSocketImpl\") as Class\n val sslSocketFactoryClass =\n Class.forName(\"$packageName.OpenSSLSocketFactoryImpl\") as\n Class\n val paramsClass = Class.forName(\"$packageName.SSLParametersImpl\")\n\n StandardAndroidSocketAdapter(sslSocketClass, sslSocketFactoryClass, paramsClass)\n } catch (e: Exception) {\n AndroidLog.androidLog(\n loggerName = OkHttpClient::class.java.name,\n logLevel = Platform.WARN,\n message = \"unable to load android socket classes\",\n t = e,\n )\n null\n }"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/publicsuffix/AssetPublicSuffixList.kt","line":24,"symbol":"AssetPublicSuffixList","kind":"class","lang":"kotlin","code":"internal class AssetPublicSuffixList(\n override val path: String = PUBLIC_SUFFIX_RESOURCE,\n) : BasePublicSuffixList() {\n override fun listSource(): Source {\n val assets = PlatformRegistry.applicationContext?.assets\n\n if (assets == null) {\n if (Build.FINGERPRINT == null) {\n throw IOException(\n \"Platform applicationContext not initialized. \" +\n \"Possibly running Android unit test without Robolectric. \" +\n \"Android tests should run with Robolectric \" +\n \"and call OkHttp.initialize before test\",\n )\n } else {\n throw IOException(\n \"Platform applicationContext not initialized. \" +\n \"Startup Initializer possibly disabled, \" +\n \"call OkHttp.initialize before test.\",\n )\n }\n }\n\n return assets.open(path).source()\n }\n\n companion object {\n val PUBLIC_SUFFIX_RESOURCE = \"PublicSuffixDatabase.list\"\n }\n}"} {"repo":"okhttp","file":"okhttp/src/androidMain/kotlin/okhttp3/internal/publicsuffix/AssetPublicSuffixList.kt","line":27,"symbol":"listSource","kind":"function","lang":"kotlin","code":"override fun listSource(): Source {\n val assets = PlatformRegistry.applicationContext?.assets\n\n if (assets == null) {\n if (Build.FINGERPRINT == null) {\n throw IOException(\n \"Platform applicationContext not initialized. \" +\n \"Possibly running Android unit test without Robolectric. \" +\n \"Android tests should run with Robolectric \" +\n \"and call OkHttp.initialize before test\",\n )\n } else {\n throw IOException(\n \"Platform applicationContext not initialized. \" +\n \"Startup Initializer possibly disabled, \" +\n \"call OkHttp.initialize before test.\",\n )\n }\n }\n\n return assets.open(path).source()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":34,"symbol":"Address","kind":"class","lang":"kotlin","doc":"server's hostname and port. If an explicit proxy is requested (or [no proxy][Proxy.NO_PROXY] is explicitly requested), this also includes that proxy information. For secure connections the address also includes the SSL socket factory, hostname verifier, and certificate pinner. HTTP requests that share the same [Address] may also share the same [Connection].","code":"class Address(\n uriHost: String,\n uriPort: Int,\n /** Returns the service that will be used to resolve IP addresses for hostnames. */\n @get:JvmName(\"dns\") val dns: Dns,\n /** Returns the socket factory for new connections. */\n @get:JvmName(\"socketFactory\") val socketFactory: SocketFactory,\n /** Returns the SSL socket factory, or null if this is not an HTTPS address. */\n @get:JvmName(\"sslSocketFactory\") val sslSocketFactory: SSLSocketFactory?,\n /** Returns the hostname verifier, or null if this is not an HTTPS address. */\n @get:JvmName(\"hostnameVerifier\") val hostnameVerifier: HostnameVerifier?,\n /** Returns this address's certificate pinner, or null if this is not an HTTPS address. */\n @get:JvmName(\"certificatePinner\") val certificatePinner: CertificatePinner?,\n /** Returns the client's proxy authenticator. */\n @get:JvmName(\"proxyAuthenticator\") val proxyAuthenticator: Authenticator,\n /**\n * Returns this address's explicitly-specified HTTP proxy, or null to delegate to the\n * [proxy selector][proxySelector].\n */\n @get:JvmName(\"proxy\") val proxy: Proxy?,\n protocols: List,\n connectionSpecs: List,\n /**\n * Returns this address's proxy "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":86,"symbol":"url","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_url\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"url\"),\n level = DeprecationLevel.ERROR,\n )\n fun url(): HttpUrl = url"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":94,"symbol":"dns","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_dns\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"dns\"),\n level = DeprecationLevel.ERROR,\n )\n fun dns(): Dns = dns"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":102,"symbol":"socketFactory","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_socketFactory\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"socketFactory\"),\n level = DeprecationLevel.ERROR,\n )\n fun socketFactory(): SocketFactory = socketFactory"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":110,"symbol":"proxyAuthenticator","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_proxyAuthenticator\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"proxyAuthenticator\"),\n level = DeprecationLevel.ERROR,\n )\n fun proxyAuthenticator(): Authenticator = proxyAuthenticator"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":118,"symbol":"protocols","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_protocols\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"protocols\"),\n level = DeprecationLevel.ERROR,\n )\n fun protocols(): List = protocols"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":126,"symbol":"connectionSpecs","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_connectionSpecs\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"connectionSpecs\"),\n level = DeprecationLevel.ERROR,\n )\n fun connectionSpecs(): List = connectionSpecs"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":134,"symbol":"proxySelector","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_proxySelector\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"proxySelector\"),\n level = DeprecationLevel.ERROR,\n )\n fun proxySelector(): ProxySelector = proxySelector"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":142,"symbol":"proxy","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_proxy\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"proxy\"),\n level = DeprecationLevel.ERROR,\n )\n fun proxy(): Proxy? = proxy"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":150,"symbol":"sslSocketFactory","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_sslSocketFactory\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"sslSocketFactory\"),\n level = DeprecationLevel.ERROR,\n )\n fun sslSocketFactory(): SSLSocketFactory? = sslSocketFactory"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":158,"symbol":"hostnameVerifier","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_hostnameVerifier\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"hostnameVerifier\"),\n level = DeprecationLevel.ERROR,\n )\n fun hostnameVerifier(): HostnameVerifier? = hostnameVerifier"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":166,"symbol":"certificatePinner","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_certificatePinner\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"certificatePinner\"),\n level = DeprecationLevel.ERROR,\n )\n fun certificatePinner(): CertificatePinner? = certificatePinner"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":174,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other is Address &&\n url == other.url &&\n equalsNonHost(other)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":179,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int {\n var result = 17\n result = 31 * result + url.hashCode()\n result = 31 * result + dns.hashCode()\n result = 31 * result + proxyAuthenticator.hashCode()\n result = 31 * result + protocols.hashCode()\n result = 31 * result + connectionSpecs.hashCode()\n result = 31 * result + proxySelector.hashCode()\n result = 31 * result + Objects.hashCode(proxy)\n result = 31 * result + Objects.hashCode(sslSocketFactory)\n result = 31 * result + Objects.hashCode(hostnameVerifier)\n result = 31 * result + Objects.hashCode(certificatePinner)\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":194,"symbol":"equalsNonHost","kind":"function","lang":"kotlin","code":"internal fun equalsNonHost(that: Address): Boolean =\n this.dns == that.dns &&\n this.proxyAuthenticator == that.proxyAuthenticator &&\n this.protocols == that.protocols &&\n this.connectionSpecs == that.connectionSpecs &&\n this.proxySelector == that.proxySelector &&\n this.proxy == that.proxy &&\n this.sslSocketFactory == that.sslSocketFactory &&\n this.hostnameVerifier == that.hostnameVerifier &&\n this.certificatePinner == that.certificatePinner &&\n this.url.port == that.url.port"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Address.kt","line":206,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n \"Address{\" +\n \"${url.host}:${url.port}, \" +\n (if (proxy != null) \"proxy=$proxy\" else \"proxySelector=$proxySelector\") +\n \"}\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Authenticator.kt","line":115,"symbol":"Authenticator","kind":"interface","lang":"kotlin","doc":"return result; } ``` [1]: https://tools.ietf.org/html/rfc2817","code":"fun interface Authenticator {\n /**\n * Returns a request that includes a credential to satisfy an authentication challenge in\n * [response]. Returns null if the challenge cannot be satisfied.\n *\n * The route is best effort, it currently may not always be provided even when logically\n * available. It may also not be provided when an authenticator is re-used manually in an\n * application interceptor, such as when implementing client-specific retries.\n */\n @Throws(IOException::class)\n fun authenticate(\n route: Route?,\n response: Response,\n ): Request?\n\n companion object {\n /** An authenticator that knows no credentials and makes no attempt to authenticate. */\n @JvmField\n val NONE: Authenticator = AuthenticatorNone()\n\n private class AuthenticatorNone : Authenticator {\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? = null\n }\n\n /** An authenticator that uses the java.net.Authenticator global authenticator. */\n @JvmField\n val JAVA_NET_AUTHENTICATOR: Authenticator = JavaNetAuthenticator()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Authenticator.kt","line":124,"symbol":"authenticate","kind":"function","lang":"kotlin","doc":"[response]. Returns null if the challenge cannot be satisfied. The route is best effort, it currently may not always be provided even when logically available. It may also not be provided when an authenticator is re-used manually in an application interceptor, such as when implementing client-specific retries.","code":"@Throws(IOException::class)\n fun authenticate(\n route: Route?,\n response: Response,\n ): Request?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Authenticator.kt","line":135,"symbol":"AuthenticatorNone","kind":"class","lang":"kotlin","code":"private class AuthenticatorNone : Authenticator {\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? = null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Authenticator.kt","line":136,"symbol":"authenticate","kind":"function","lang":"kotlin","code":"override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? = null"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":193,"symbol":"get","kind":"function","lang":"kotlin","code":"internal fun get(request: Request): Response? {\n val key = key(request.url)\n val snapshot: DiskLruCache.Snapshot =\n try {\n cache[key] ?: return null\n } catch (_: IOException) {\n return null // Give up because the cache cannot be read.\n }\n\n val entry: Entry =\n try {\n Entry(snapshot.getSource(ENTRY_METADATA))\n } catch (_: IOException) {\n snapshot.closeQuietly()\n return null\n }\n\n val response = entry.response(snapshot)\n if (!entry.matches(request, response)) {\n response.body.closeQuietly()\n return null\n }\n\n return response\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":219,"symbol":"put","kind":"function","lang":"kotlin","code":"internal fun put(response: Response): CacheRequest? {\n val requestMethod = response.request.method\n\n if (HttpMethod.invalidatesCache(response.request.method)) {\n try {\n remove(response.request)\n } catch (_: IOException) {\n // The cache cannot be written.\n }\n return null\n }\n\n if (requestMethod != \"GET\") {\n // Don't cache non-GET responses. We're technically allowed to cache HEAD, QUERY and some\n // POST requests, but the complexity of doing so is high and the benefit is low.\n return null\n }\n\n if (response.hasVaryAll()) {\n return null\n }\n\n val entry = Entry(response)\n var editor: DiskLruCache.Editor? = null\n try {\n editor = cache.edit(key(response.request.url)) ?: return null\n entry.writeTo(editor)\n return RealCacheRequest(editor)\n } catch (_: IOException) {\n abortQuietly(editor)\n return null\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":253,"symbol":"remove","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n internal fun remove(request: Request) {\n cache.remove(key(request.url))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":258,"symbol":"update","kind":"function","lang":"kotlin","code":"internal fun update(\n cached: Response,\n network: Response,\n ) {\n val entry = Entry(network)\n val snapshot = (cached.body as CacheResponseBody).snapshot\n var editor: DiskLruCache.Editor? = null\n try {\n editor = snapshot.edit() ?: return // edit() returns null if snapshot is not current.\n entry.writeTo(editor)\n editor.commit()\n } catch (_: IOException) {\n abortQuietly(editor)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":274,"symbol":"abortQuietly","kind":"function","lang":"kotlin","code":"private fun abortQuietly(editor: DiskLruCache.Editor?) {\n // Give up because the cache cannot be written.\n try {\n editor?.abort()\n } catch (_: IOException) {\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":293,"symbol":"initialize","kind":"function","lang":"kotlin","doc":"cache size. The application needs to be aware of calling this function during the initialization phase and preferably in a background worker thread. Note that if the application chooses to not call this method to initialize the cache. By default, OkHttp will perform lazy initialization upon the first usage of the cache.","code":"@Throws(IOException::class)\n fun initialize() {\n cache.initialize()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":302,"symbol":"delete","kind":"function","lang":"kotlin","doc":"Closes the cache and deletes all of its stored values. This will delete all files in the cache directory including files that weren't created by the cache.","code":"@Throws(IOException::class)\n fun delete() {\n cache.delete()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":311,"symbol":"evictAll","kind":"function","lang":"kotlin","doc":"Deletes all values stored in the cache. In-flight writes to the cache will complete normally, but the corresponding responses will not be stored.","code":"@Throws(IOException::class)\n fun evictAll() {\n cache.evictAll()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":325,"symbol":"urls","kind":"function","lang":"kotlin","doc":"will not be returned. If existing responses are evicted during iteration, they will be absent (unless they were already returned). The iterator supports [MutableIterator.remove]. Removing a URL from the iterator evicts the corresponding response from the cache. Use this to evict selected responses.","code":"@Throws(IOException::class)\n fun urls(): MutableIterator {\n return object : MutableIterator {\n private val delegate: MutableIterator = cache.snapshots()\n private var nextUrl: String? = null\n private var canRemove = false\n\n override fun hasNext(): Boolean {\n if (nextUrl != null) return true\n\n canRemove = false // Prevent delegate.remove() on the wrong item!\n while (delegate.hasNext()) {\n try {\n delegate.next().use { snapshot ->\n val metadata = snapshot.getSource(ENTRY_METADATA).buffer()\n nextUrl = metadata.readUtf8LineStrict()\n return true\n }\n } catch (_: IOException) {\n // We couldn't read the metadata for this snapshot; possibly because the host filesystem\n // has disappeared! Skip it.\n }\n }\n\n return false\n }\n\n override fun next(): String {\n if (!hasNext()) throw NoSuchElementException()\n val result = nextUrl!!\n nextUrl = null\n canRemove = true\n return result\n }\n\n override fun remove() {\n check(canRemove) { \"remove("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":332,"symbol":"hasNext","kind":"function","lang":"kotlin","code":"override fun hasNext(): Boolean {\n if (nextUrl != null) return true\n\n canRemove = false // Prevent delegate.remove() on the wrong item!\n while (delegate.hasNext()) {\n try {\n delegate.next().use { snapshot ->\n val metadata = snapshot.getSource(ENTRY_METADATA).buffer()\n nextUrl = metadata.readUtf8LineStrict()\n return true\n }\n } catch (_: IOException) {\n // We couldn't read the metadata for this snapshot; possibly because the host filesystem\n // has disappeared! Skip it.\n }\n }\n\n return false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":352,"symbol":"next","kind":"function","lang":"kotlin","code":"override fun next(): String {\n if (!hasNext()) throw NoSuchElementException()\n val result = nextUrl!!\n nextUrl = null\n canRemove = true\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":360,"symbol":"remove","kind":"function","lang":"kotlin","code":"override fun remove() {\n check(canRemove) { \"remove() before next()\" }\n delegate.remove()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":367,"symbol":"writeAbortCount","kind":"function","lang":"kotlin","code":"@Synchronized fun writeAbortCount(): Int = writeAbortCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":369,"symbol":"writeSuccessCount","kind":"function","lang":"kotlin","code":"@Synchronized fun writeSuccessCount(): Int = writeSuccessCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":371,"symbol":"size","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun size(): Long = cache.size()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":375,"symbol":"maxSize","kind":"function","lang":"kotlin","doc":"Max size of the cache (in bytes).","code":"fun maxSize(): Long = cache.maxSize"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":377,"symbol":"flush","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun flush() {\n cache.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":382,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n cache.close()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":395,"symbol":"directory","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_directory\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"directory\"),\n level = DeprecationLevel.ERROR,\n )\n fun directory(): File = cache.directory.toFile()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":403,"symbol":"trackResponse","kind":"function","lang":"kotlin","code":"@Synchronized internal fun trackResponse(cacheStrategy: CacheStrategy) {\n requestCount++\n\n if (cacheStrategy.networkRequest != null) {\n // If this is a conditional request, we'll increment hitCount if/when it hits.\n networkCount++\n } else if (cacheStrategy.cacheResponse != null) {\n // This response uses the cache and not the network. That's a cache hit.\n hitCount++\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":415,"symbol":"trackConditionalCacheHit","kind":"function","lang":"kotlin","code":"@Synchronized internal fun trackConditionalCacheHit() {\n hitCount++\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":419,"symbol":"networkCount","kind":"function","lang":"kotlin","code":"@Synchronized fun networkCount(): Int = networkCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":421,"symbol":"hitCount","kind":"function","lang":"kotlin","code":"@Synchronized fun hitCount(): Int = hitCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":423,"symbol":"requestCount","kind":"function","lang":"kotlin","code":"@Synchronized fun requestCount(): Int = requestCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":425,"symbol":"RealCacheRequest","kind":"class","lang":"kotlin","code":"private inner class RealCacheRequest(\n private val editor: DiskLruCache.Editor,\n ) : CacheRequest {\n private val cacheOut: Sink = editor.newSink(ENTRY_BODY)\n private val body: Sink\n var done = false\n\n init {\n this.body =\n object : ForwardingSink(cacheOut) {\n @Throws(IOException::class)\n override fun close() {\n synchronized(this@Cache) {\n if (done) return\n done = true\n writeSuccessCount++\n }\n super.close()\n editor.commit()\n }\n }\n }\n\n override fun abort() {\n synchronized(this@Cache) {\n if (done) return\n done = true\n writeAbortCount++\n }\n cacheOut.closeQuietly()\n try {\n editor.abort()\n } catch (_: IOException) {\n }\n }\n\n override fun body(): Sink = body\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":435,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n synchronized(this@Cache) {\n if (done) return\n done = true\n writeSuccessCount++\n }\n super.close()\n editor.commit()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":448,"symbol":"abort","kind":"function","lang":"kotlin","code":"override fun abort() {\n synchronized(this@Cache) {\n if (done) return\n done = true\n writeAbortCount++\n }\n cacheOut.closeQuietly()\n try {\n editor.abort()\n } catch (_: IOException) {\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":461,"symbol":"body","kind":"function","lang":"kotlin","code":"override fun body(): Sink = body"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":662,"symbol":"writeCertList","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun writeCertList(\n sink: BufferedSink,\n certificates: List,\n ) {\n try {\n sink.writeDecimalLong(certificates.size.toLong()).writeByte('\\n'.code)\n for (element in certificates) {\n val bytes = element.encoded\n val line = bytes.toByteString().base64()\n sink.writeUtf8(line).writeByte('\\n'.code)\n }\n } catch (e: CertificateEncodingException) {\n throw IOException(e.message)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":679,"symbol":"matches","kind":"function","lang":"kotlin","code":"fun matches(\n request: Request,\n response: Response,\n ): Boolean =\n url == request.url &&\n requestMethod == request.method &&\n varyMatches(response, varyHeaders, request)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":687,"symbol":"response","kind":"function","lang":"kotlin","code":"fun response(snapshot: DiskLruCache.Snapshot): Response {\n val contentType = responseHeaders[\"Content-Type\"]\n val contentLength = responseHeaders[\"Content-Length\"]\n val cacheRequest = Request(url, varyHeaders, requestMethod)\n return Response\n .Builder()\n .request(cacheRequest)\n .protocol(protocol)\n .code(code)\n .message(message)\n .headers(responseHeaders)\n .body(CacheResponseBody(snapshot, contentType, contentLength))\n .handshake(handshake)\n .sentRequestAtMillis(sentRequestMillis)\n .receivedResponseAtMillis(receivedResponseMillis)\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":714,"symbol":"CacheResponseBody","kind":"class","lang":"kotlin","code":"private class CacheResponseBody(\n val snapshot: DiskLruCache.Snapshot,\n private val contentType: String?,\n private val contentLength: String?,\n ) : ResponseBody() {\n private val bodySource: BufferedSource\n\n init {\n val source = snapshot.getSource(ENTRY_BODY)\n bodySource =\n object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close() {\n snapshot.close()\n super.close()\n }\n }.buffer()\n }\n\n override fun contentType(): MediaType? = contentType?.toMediaTypeOrNull()\n\n override fun contentLength(): Long = contentLength?.toLongOrDefault(-1L) ?: -1L\n\n override fun source(): BufferedSource = bodySource\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":725,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n snapshot.close()\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":733,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = contentType?.toMediaTypeOrNull()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":735,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = contentLength?.toLongOrDefault(-1L) ?: -1L"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":737,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource = bodySource"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":746,"symbol":"key","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun key(url: HttpUrl): String =\n url\n .toString()\n .encodeUtf8()\n .md5()\n .hex()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt","line":820,"symbol":"varyHeaders","kind":"function","lang":"kotlin","doc":"Returns the subset of the headers in [requestHeaders] that impact the content of the response's body.","code":"private fun varyHeaders(\n requestHeaders: Headers,\n responseHeaders: Headers,\n ): Headers {\n val varyFields = responseHeaders.varyFields()\n if (varyFields.isEmpty()) return Headers.EMPTY\n\n val result = Headers.Builder()\n for (i in 0 until requestHeaders.size) {\n val fieldName = requestHeaders.name(i)\n if (fieldName in varyFields) {\n result.add(fieldName, requestHeaders.value(i))\n }\n }\n return result.build()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":38,"symbol":"CacheControl","kind":"class","lang":"kotlin","doc":"A Cache-Control header with cache directives from a server or client. These directives set policy on what responses can be stored, and which requests can be satisfied by those stored responses. See [RFC 7234, 5.2](https://tools.ietf.org/html/rfc7234#section-5.2).","code":"class CacheControl internal constructor(\n /**\n * In a response, this field's name \"no-cache\" is misleading. It doesn't prevent us from caching\n * the response; it only means we have to validate the response with the origin server before\n * returning it. We can do this with a conditional GET.\n *\n * In a request, it means do not use a cache to satisfy the request.\n */\n @get:JvmName(\"noCache\") val noCache: Boolean,\n /** If true, this response should not be cached. */\n @get:JvmName(\"noStore\") val noStore: Boolean,\n /** The duration past the response's served date that it can be served without validation. */\n @get:JvmName(\"maxAgeSeconds\") val maxAgeSeconds: Int,\n /**\n * The \"s-maxage\" directive is the max age for shared caches. Not to be confused with \"max-age\"\n * for non-shared caches, As in Firefox and Chrome, this directive is not honored by this cache.\n */\n @get:JvmName(\"sMaxAgeSeconds\") val sMaxAgeSeconds: Int,\n val isPrivate: Boolean,\n val isPublic: Boolean,\n @get:JvmName(\"mustRevalidate\") val mustRevalidate: Boolean,\n @get:JvmName(\"maxStaleSeconds\") val maxStaleSeconds: Int,\n @get:JvmName(\"minFreshSeconds\") val minFreshSeconds: Int,\n /**\n * This "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":72,"symbol":"noCache","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_noCache\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"noCache\"),\n level = DeprecationLevel.ERROR,\n )\n fun noCache(): Boolean = noCache"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":80,"symbol":"noStore","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_noStore\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"noStore\"),\n level = DeprecationLevel.ERROR,\n )\n fun noStore(): Boolean = noStore"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":88,"symbol":"maxAgeSeconds","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_maxAgeSeconds\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"maxAgeSeconds\"),\n level = DeprecationLevel.ERROR,\n )\n fun maxAgeSeconds(): Int = maxAgeSeconds"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":96,"symbol":"sMaxAgeSeconds","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_sMaxAgeSeconds\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"sMaxAgeSeconds\"),\n level = DeprecationLevel.ERROR,\n )\n fun sMaxAgeSeconds(): Int = sMaxAgeSeconds"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":104,"symbol":"mustRevalidate","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_mustRevalidate\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"mustRevalidate\"),\n level = DeprecationLevel.ERROR,\n )\n fun mustRevalidate(): Boolean = mustRevalidate"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":112,"symbol":"maxStaleSeconds","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_maxStaleSeconds\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"maxStaleSeconds\"),\n level = DeprecationLevel.ERROR,\n )\n fun maxStaleSeconds(): Int = maxStaleSeconds"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":120,"symbol":"minFreshSeconds","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_minFreshSeconds\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"minFreshSeconds\"),\n level = DeprecationLevel.ERROR,\n )\n fun minFreshSeconds(): Int = minFreshSeconds"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":128,"symbol":"onlyIfCached","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_onlyIfCached\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"onlyIfCached\"),\n level = DeprecationLevel.ERROR,\n )\n fun onlyIfCached(): Boolean = onlyIfCached"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":136,"symbol":"noTransform","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_noTransform\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"noTransform\"),\n level = DeprecationLevel.ERROR,\n )\n fun noTransform(): Boolean = noTransform"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":144,"symbol":"immutable","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_immutable\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"immutable\"),\n level = DeprecationLevel.ERROR,\n )\n fun immutable(): Boolean = immutable"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":152,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = commonToString()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":155,"symbol":"Builder","kind":"class","lang":"kotlin","doc":"Builds a `Cache-Control` request header.","code":"class Builder {\n internal var noCache: Boolean = false\n internal var noStore: Boolean = false\n internal var maxAgeSeconds = -1\n internal var maxStaleSeconds = -1\n internal var minFreshSeconds = -1\n internal var onlyIfCached: Boolean = false\n internal var noTransform: Boolean = false\n internal var immutable: Boolean = false\n\n /** Don't accept an unvalidated cached response. */\n fun noCache() = commonNoCache()\n\n /** Don't store the server's response in any cache. */\n fun noStore() = commonNoStore()\n\n /**\n * Only accept the response if it is in the cache. If the response isn't cached, a `504\n * Unsatisfiable Request` response will be returned.\n */\n fun onlyIfCached() = commonOnlyIfCached()\n\n /** Don't accept a transformed response. */\n fun noTransform() = commonNoTransform()\n\n fun immutable() = commonImmutable()\n\n /**\n * Sets the maximum age of a cached response. If the cache response's age exceeds [maxAge], it\n * will not be used and a network request will be made.\n *\n * @param maxAge a non-negative duration. This is stored and transmitted with [TimeUnit.SECONDS]\n * precision; finer precision wi"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":166,"symbol":"noCache","kind":"function","lang":"kotlin","doc":"Don't accept an unvalidated cached response.","code":"fun noCache() = commonNoCache()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":169,"symbol":"noStore","kind":"function","lang":"kotlin","doc":"Don't store the server's response in any cache.","code":"fun noStore() = commonNoStore()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":175,"symbol":"onlyIfCached","kind":"function","lang":"kotlin","doc":"Only accept the response if it is in the cache. If the response isn't cached, a `504 Unsatisfiable Request` response will be returned.","code":"fun onlyIfCached() = commonOnlyIfCached()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":178,"symbol":"noTransform","kind":"function","lang":"kotlin","doc":"Don't accept a transformed response.","code":"fun noTransform() = commonNoTransform()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":180,"symbol":"immutable","kind":"function","lang":"kotlin","code":"fun immutable() = commonImmutable()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":189,"symbol":"maxAge","kind":"function","lang":"kotlin","doc":"Sets the maximum age of a cached response. If the cache response's age exceeds [maxAge], it will not be used and a network request will be made. @param maxAge a non-negative duration. This is stored and transmitted with [TimeUnit.SECONDS] precision; finer precision will be lost.","code":"fun maxAge(maxAge: Duration) =\n apply {\n val maxAgeSeconds = maxAge.inWholeSeconds\n require(maxAgeSeconds >= 0) { \"maxAge < 0: $maxAgeSeconds\" }\n this.maxAgeSeconds = maxAgeSeconds.commonClampToInt()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":196,"symbol":"maxStale","kind":"function","lang":"kotlin","code":"fun maxStale(maxStale: Duration) =\n apply {\n val maxStaleSeconds = maxStale.inWholeSeconds\n require(maxStaleSeconds >= 0) { \"maxStale < 0: $maxStaleSeconds\" }\n this.maxStaleSeconds = maxStaleSeconds.commonClampToInt()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":203,"symbol":"minFresh","kind":"function","lang":"kotlin","code":"fun minFresh(minFresh: Duration) =\n apply {\n val minFreshSeconds = minFresh.inWholeSeconds\n require(minFreshSeconds >= 0) { \"minFresh < 0: $minFreshSeconds\" }\n this.minFreshSeconds = minFreshSeconds.commonClampToInt()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":217,"symbol":"maxAge","kind":"function","lang":"kotlin","doc":"Sets the maximum age of a cached response. If the cache response's age exceeds [maxAge], it will not be used and a network request will be made. @param maxAge a non-negative integer. This is stored and transmitted with [TimeUnit.SECONDS] precision; finer precision will be lost.","code":"fun maxAge(\n maxAge: Int,\n timeUnit: TimeUnit,\n ) = apply {\n require(maxAge >= 0) { \"maxAge < 0: $maxAge\" }\n val maxAgeSecondsLong = timeUnit.toSeconds(maxAge.toLong())\n this.maxAgeSeconds = maxAgeSecondsLong.commonClampToInt()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":233,"symbol":"maxStale","kind":"function","lang":"kotlin","doc":"Accept cached responses that have exceeded their freshness lifetime by up to `maxStale`. If unspecified, stale cache responses will not be used. @param maxStale a non-negative integer. This is stored and transmitted with [TimeUnit.SECONDS] precision; finer precision will be lost.","code":"fun maxStale(\n maxStale: Int,\n timeUnit: TimeUnit,\n ) = apply {\n require(maxStale >= 0) { \"maxStale < 0: $maxStale\" }\n val maxStaleSecondsLong = timeUnit.toSeconds(maxStale.toLong())\n this.maxStaleSeconds = maxStaleSecondsLong.commonClampToInt()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":250,"symbol":"minFresh","kind":"function","lang":"kotlin","doc":"response will be stale when [minFresh] have elapsed, the cached response will not be used and a network request will be made. @param minFresh a non-negative integer. This is stored and transmitted with [TimeUnit.SECONDS] precision; finer precision will be lost.","code":"fun minFresh(\n minFresh: Int,\n timeUnit: TimeUnit,\n ) = apply {\n require(minFresh >= 0) { \"minFresh < 0: $minFresh\" }\n val minFreshSecondsLong = timeUnit.toSeconds(minFresh.toLong())\n this.minFreshSeconds = minFreshSecondsLong.commonClampToInt()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":259,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): CacheControl = commonBuild()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CacheControl.kt","line":282,"symbol":"parse","kind":"function","lang":"kotlin","doc":"Returns the cache directives of [headers]. This honors both Cache-Control and Pragma headers if they are present.","code":"@JvmStatic\n fun parse(headers: Headers): CacheControl = commonParse(headers)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":26,"symbol":"Call","kind":"interface","lang":"kotlin","doc":"A call is a request that has been prepared for execution. A call can be canceled. As this object represents a single request/response pair (stream), it cannot be executed twice.","code":"interface Call : Cloneable {\n /** Returns the original request that initiated this call. */\n fun request(): Request\n\n /**\n * Invokes the request immediately, and blocks until the response can be processed or is in error.\n *\n * To avoid leaking resources callers should close the [Response] which in turn will close the\n * underlying [ResponseBody].\n *\n * ```java\n * // ensure the response (and underlying response body) is closed\n * try (Response response = client.newCall(request).execute()) {\n * ...\n * }\n * ```\n *\n * The caller may read the response body with the response's [Response.body] method. To avoid\n * leaking resources callers must [close the response body][ResponseBody] or the response.\n *\n * Note that transport-layer success (receiving a HTTP response code, headers and body) does not\n * necessarily indicate application-layer success: `response` may still indicate an unhappy HTTP\n * response code like 404 or 500.\n *\n * @throws IOException if the request could not be executed due to cancellation, a connectivity\n * problem or timeout. Because networks can fail during an exchange, it is possible that the\n * remote server a"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":28,"symbol":"request","kind":"function","lang":"kotlin","doc":"Returns the original request that initiated this call.","code":"fun request(): Request"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":55,"symbol":"execute","kind":"function","lang":"kotlin","doc":"@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.","code":"@Throws(IOException::class)\n fun execute(): Response"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":69,"symbol":"enqueue","kind":"function","lang":"kotlin","doc":"This client will later call back `responseCallback` with either an HTTP response or a failure exception. @throws IllegalStateException when the call has already been executed.","code":"fun enqueue(responseCallback: Callback)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":72,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"Cancels the request, if possible. Requests that are already complete cannot be canceled.","code":"fun cancel()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":78,"symbol":"isExecuted","kind":"function","lang":"kotlin","doc":"Returns true if this call has been either [executed][execute] or [enqueued][enqueue]. It is an error to execute a call more than once.","code":"fun isExecuted(): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":80,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"fun isCanceled(): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":89,"symbol":"timeout","kind":"function","lang":"kotlin","doc":"Returns a timeout that spans the entire call: resolving DNS, connecting, writing the request body, server processing, and reading the response body. If the call requires redirects or retries all must complete within one timeout period. Configure the client's default timeout with [OkHttpClient.Builder.callTimeout].","code":"fun timeout(): Timeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":102,"symbol":"addEventListener","kind":"function","lang":"kotlin","doc":"There is no mechanism to remove an event listener. Implementations should instead ignore events that they are not interested in. @see EventListener for semantics and restrictions on listener implementations.","code":"fun addEventListener(eventListener: EventListener)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":110,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Returns the tag attached with [type] as a key, or null if no tag is attached with that key. The tags on a call are seeded from the [request tags][Request.tag]. This set will grow if new tags are computed.","code":"fun tag(type: KClass): T?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":118,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Returns the tag attached with [type] as a key, or null if no tag is attached with that key. The tags on a call are seeded from the [request tags][Request.tag]. This set will grow if new tags are computed.","code":"fun tag(type: Class): T?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":131,"symbol":"tag","kind":"function","lang":"kotlin","doc":"may be computed. But only one value will be inserted, and that inserted value will be returned to all callers. If computing multiple values is problematic, use an appropriate concurrency mechanism in your [computeIfAbsent] implementation. No locks are held while calling this function.","code":"fun tag(\n type: KClass,\n computeIfAbsent: () -> T,\n ): T"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":147,"symbol":"tag","kind":"function","lang":"kotlin","doc":"may be computed. But only one value will be inserted, and that inserted value will be returned to all callers. If computing multiple values is problematic, use an appropriate concurrency mechanism in your [computeIfAbsent] implementation. No locks are held while calling this function.","code":"fun tag(\n type: Class,\n computeIfAbsent: () -> T,\n ): T"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":181,"symbol":"clone","kind":"function","lang":"kotlin","doc":"} ``` If any event listeners were installed on this call with [addEventListener], they will not be installed on this copy.","code":"public override fun clone(): Call"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":183,"symbol":"Factory","kind":"interface","lang":"kotlin","code":"fun interface Factory {\n fun newCall(request: Request): Call\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Call.kt","line":184,"symbol":"newCall","kind":"function","lang":"kotlin","code":"fun newCall(request: Request): Call"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Callback.kt","line":20,"symbol":"Callback","kind":"interface","lang":"kotlin","code":"interface Callback {\n /**\n * Called when the request could not be executed due to cancellation, a connectivity problem or\n * timeout. Because networks can fail during an exchange, it is possible that the remote server\n * accepted the request before the failure.\n */\n fun onFailure(\n call: Call,\n e: IOException,\n )\n\n /**\n * Called when the HTTP response was successfully returned by the remote server. The callback may\n * proceed to read the response body with [Response.body]. The response is still live until its\n * response body is [closed][ResponseBody]. The recipient of the callback may consume the response\n * body on another thread.\n *\n * Note that transport-layer success (receiving a HTTP response code, headers and body) does not\n * necessarily indicate application-layer success: `response` may still indicate an unhappy HTTP\n * response code like 404 or 500.\n */\n @Throws(IOException::class)\n fun onResponse(\n call: Call,\n response: Response,\n )\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Callback.kt","line":26,"symbol":"onFailure","kind":"function","lang":"kotlin","doc":"Called when 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.","code":"fun onFailure(\n call: Call,\n e: IOException,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Callback.kt","line":41,"symbol":"onResponse","kind":"function","lang":"kotlin","doc":"body on another thread. 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.","code":"@Throws(IOException::class)\n fun onResponse(\n call: Call,\n response: Response,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":135,"symbol":"CertificatePinner","kind":"class","lang":"kotlin","doc":"[fiddler]: http://fiddlertool.com [langley]: http://goo.gl/AIx3e5 [owasp]: https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning [rfc_7469]: http://tools.ietf.org/html/rfc7469 [static_certificates]: http://goo.gl/XDh6je","code":"@Suppress(\"NAME_SHADOWING\")\nclass CertificatePinner internal constructor(\n val pins: Set,\n internal val certificateChainCleaner: CertificateChainCleaner? = null,\n) {\n /**\n * Confirms that at least one of the certificates pinned for `hostname` is in `peerCertificates`.\n * Does nothing if there are no certificates pinned for `hostname`. OkHttp calls this after a\n * successful TLS handshake, but before the connection is used.\n *\n * @throws SSLPeerUnverifiedException if `peerCertificates` don't match the certificates pinned\n * for `hostname`.\n */\n @Throws(SSLPeerUnverifiedException::class)\n fun check(\n hostname: String,\n peerCertificates: List,\n ) = check(hostname) {\n (certificateChainCleaner?.clean(peerCertificates, hostname) ?: peerCertificates)\n .map { it as X509Certificate }\n }\n\n internal fun check(\n hostname: String,\n cleanedPeerCertificatesFn: () -> List,\n ) {\n val pins = findMatchingPins(hostname)\n if (pins.isEmpty()) return\n\n val peerCertificates = cleanedPeerCertificatesFn()\n\n for (peerCertificate in peerCertificates) {\n // Lazily compute the hashes for each certificate.\n va"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":148,"symbol":"check","kind":"function","lang":"kotlin","doc":"Does nothing if there are no certificates pinned for `hostname`. OkHttp calls this after a successful TLS handshake, but before the connection is used. @throws SSLPeerUnverifiedException if `peerCertificates` don't match the certificates pinned for `hostname`.","code":"@Throws(SSLPeerUnverifiedException::class)\n fun check(\n hostname: String,\n peerCertificates: List,\n ) = check(hostname) {\n (certificateChainCleaner?.clean(peerCertificates, hostname) ?: peerCertificates)\n .map { it as X509Certificate }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":157,"symbol":"check","kind":"function","lang":"kotlin","code":"internal fun check(\n hostname: String,\n cleanedPeerCertificatesFn: () -> List,\n ) {\n val pins = findMatchingPins(hostname)\n if (pins.isEmpty()) return\n\n val peerCertificates = cleanedPeerCertificatesFn()\n\n for (peerCertificate in peerCertificates) {\n // Lazily compute the hashes for each certificate.\n var sha1: ByteString? = null\n var sha256: ByteString? = null\n\n for (pin in pins) {\n when (pin.hashAlgorithm) {\n \"sha256\" -> {\n if (sha256 == null) sha256 = peerCertificate.sha256Hash()\n if (pin.hash == sha256) return // Success!\n }\n\n \"sha1\" -> {\n if (sha1 == null) sha1 = peerCertificate.sha1Hash()\n if (pin.hash == sha1) return // Success!\n }\n\n else -> {\n throw AssertionError(\"unsupported hashAlgorithm: ${pin.hashAlgorithm}\")\n }\n }\n }\n }\n\n // If we couldn't find a matching pin, format a nice exception.\n val message =\n buildString {\n append(\"Certificate pinning failure!\")\n append(\"\\n Peer certificate chain:\")\n for (element in peerCertificates) {\n append(\"\\n \""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":212,"symbol":"check","kind":"function","lang":"kotlin","code":"@Deprecated(\n \"replaced with {@link #check(String, List)}.\",\n ReplaceWith(\"check(hostname, peerCertificates.toList())\"),\n )\n @Throws(SSLPeerUnverifiedException::class)\n fun check(\n hostname: String,\n vararg peerCertificates: Certificate,\n ) {\n check(hostname, peerCertificates.toList())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":228,"symbol":"findMatchingPins","kind":"function","lang":"kotlin","doc":"Returns list of matching certificates' pins for the hostname. Returns an empty list if the hostname does not have pinned certificates.","code":"fun findMatchingPins(hostname: String): List = pins.filterList { matchesHostname(hostname) }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":231,"symbol":"withCertificateChainCleaner","kind":"function","lang":"kotlin","doc":"Returns a certificate pinner that uses `certificateChainCleaner`.","code":"internal fun withCertificateChainCleaner(certificateChainCleaner: CertificateChainCleaner): CertificatePinner =\n if (this.certificateChainCleaner == certificateChainCleaner) {\n this\n } else {\n CertificatePinner(pins, certificateChainCleaner)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":238,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other is CertificatePinner &&\n other.pins == pins &&\n other.certificateChainCleaner == certificateChainCleaner"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":243,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int {\n var result = 37\n result = 41 * result + pins.hashCode()\n result = 41 * result + certificateChainCleaner.hashCode()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":251,"symbol":"Pin","kind":"class","lang":"kotlin","doc":"A hostname pattern and certificate hash for Certificate Pinning.","code":"class Pin(\n pattern: String,\n pin: String,\n ) {\n /** A hostname like `example.com` or a pattern like `*.example.com` (canonical form). */\n val pattern: String\n\n /** Either `sha1` or `sha256`. */\n val hashAlgorithm: String\n\n /** The hash of the pinned certificate using [hashAlgorithm]. */\n val hash: ByteString\n\n init {\n require(\n (pattern.startsWith(\"*.\") && pattern.indexOf(\"*\", 1) == -1) ||\n (pattern.startsWith(\"**.\") && pattern.indexOf(\"*\", 2) == -1) ||\n pattern.indexOf(\"*\") == -1,\n ) {\n \"Unexpected pattern: $pattern\"\n }\n\n this.pattern =\n pattern.toCanonicalHost() ?: throw IllegalArgumentException(\"Invalid pattern: $pattern\")\n\n when {\n pin.startsWith(\"sha1/\") -> {\n this.hashAlgorithm = \"sha1\"\n this.hash = pin.substring(\"sha1/\".length).decodeBase64() ?: throw IllegalArgumentException(\"Invalid pin hash: $pin\")\n }\n\n pin.startsWith(\"sha256/\") -> {\n this.hashAlgorithm = \"sha256\"\n this.hash = pin.substring(\"sha256/\".length).decodeBase64() ?: throw IllegalArgumentException(\"Invalid pin hash: $pin\")\n }\n\n else -> {\n thro"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":293,"symbol":"matchesHostname","kind":"function","lang":"kotlin","code":"fun matchesHostname(hostname: String): Boolean =\n when {\n pattern.startsWith(\"**.\") -> {\n // With ** empty prefixes match so exclude the dot from regionMatches().\n val suffixLength = pattern.length - 3\n val prefixLength = hostname.length - suffixLength\n hostname.regionMatches(hostname.length - suffixLength, pattern, 3, suffixLength) &&\n (prefixLength == 0 || hostname[prefixLength - 1] == '.')\n }\n\n pattern.startsWith(\"*.\") -> {\n // With * there must be a prefix so include the dot in regionMatches().\n val suffixLength = pattern.length - 1\n val prefixLength = hostname.length - suffixLength\n hostname.regionMatches(hostname.length - suffixLength, pattern, 1, suffixLength) &&\n hostname.lastIndexOf('.', prefixLength - 1) == -1\n }\n\n else -> {\n hostname == pattern\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":316,"symbol":"matchesCertificate","kind":"function","lang":"kotlin","code":"fun matchesCertificate(certificate: X509Certificate): Boolean =\n when (hashAlgorithm) {\n \"sha256\" -> hash == certificate.sha256Hash()\n \"sha1\" -> hash == certificate.sha1Hash()\n else -> false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":323,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"$hashAlgorithm/${hash.base64()}\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":325,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean {\n if (this === other) return true\n if (other !is Pin) return false\n\n if (pattern != other.pattern) return false\n if (hashAlgorithm != other.hashAlgorithm) return false\n if (hash != other.hash) return false\n\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":336,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int {\n var result = pattern.hashCode()\n result = 31 * result + hashAlgorithm.hashCode()\n result = 31 * result + hash.hashCode()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":345,"symbol":"Builder","kind":"class","lang":"kotlin","doc":"Builds a configured certificate pinner.","code":"class Builder {\n val pins = mutableListOf()\n\n /**\n * Pins certificates for `pattern`.\n *\n * @param pattern lower-case host name or wildcard pattern such as `*.example.com`.\n * @param pins SHA-256 or SHA-1 hashes. Each pin is a hash of a certificate's Subject Public Key\n * Info, base64-encoded and prefixed with either `sha256/` or `sha1/`.\n */\n fun add(\n pattern: String,\n vararg pins: String,\n ) = apply {\n for (pin in pins) {\n this.pins.add(Pin(pattern, pin))\n }\n }\n\n fun build(): CertificatePinner = CertificatePinner(pins.toSet())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":355,"symbol":"add","kind":"function","lang":"kotlin","doc":"Pins certificates for `pattern`. @param pattern lower-case host name or wildcard pattern such as `*.example.com`. @param pins SHA-256 or SHA-1 hashes. Each pin is a hash of a certificate's Subject Public Key Info, base64-encoded and prefixed with either `sha256/` or `sha1/`.","code":"fun add(\n pattern: String,\n vararg pins: String,\n ) = apply {\n for (pin in pins) {\n this.pins.add(Pin(pattern, pin))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":364,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): CertificatePinner = CertificatePinner(pins.toSet())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":371,"symbol":"sha1Hash","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun X509Certificate.sha1Hash(): ByteString = publicKey.encoded.toByteString().sha1()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":374,"symbol":"sha256Hash","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun X509Certificate.sha256Hash(): ByteString = publicKey.encoded.toByteString().sha256()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CertificatePinner.kt","line":383,"symbol":"pin","kind":"function","lang":"kotlin","doc":"Returns the SHA-256 of `certificate`'s public key. In OkHttp 3.1.2 and earlier, this returned a SHA-1 hash of the public key. Both types are supported, but SHA-256 is preferred.","code":"@JvmStatic\n fun pin(certificate: Certificate): String {\n require(certificate is X509Certificate) { \"Certificate pinning requires X509 certificates\" }\n return \"sha256/${certificate.sha256Hash().base64()}\"\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":29,"symbol":"Challenge","kind":"class","lang":"kotlin","doc":"An [RFC 7235][rfc_7235] challenge. [rfc_7235]: https://tools.ietf.org/html/rfc7235","code":"class Challenge(\n /** Returns the authentication scheme, like `Basic`. */\n @get:JvmName(\"scheme\") val scheme: String,\n authParams: Map,\n) {\n /**\n * Returns the auth params, including [realm] and [charset] if present, but as\n * strings. The map's keys are lowercase and should be treated case-insensitively.\n */\n @get:JvmName(\"authParams\")\n val authParams: Map\n\n /** Returns the protection space. */\n @get:JvmName(\"realm\")\n val realm: String?\n get() = authParams[\"realm\"]\n\n /** The charset that should be used to encode the credentials. */\n @get:JvmName(\"charset\")\n val charset: Charset\n get() {\n val charset = authParams[\"charset\"]\n if (charset != null) {\n try {\n return Charset.forName(charset)\n } catch (ignore: Exception) {\n }\n }\n return ISO_8859_1\n }\n\n constructor(scheme: String, realm: String) : this(scheme, singletonMap(\"realm\", realm))\n\n init {\n val newAuthParams = mutableMapOf()\n for ((key, value) in authParams) {\n val newKey = key?.lowercase(US)\n newAuthParams[newKey] = value\n }\n this.authParams = newAuthParams.unmodifiable()\n }\n\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":72,"symbol":"withCharset","kind":"function","lang":"kotlin","doc":"Returns a copy of this charset that expects a credential encoded with [charset].","code":"fun withCharset(charset: Charset): Challenge {\n val authParams = this.authParams.toMutableMap()\n authParams[\"charset\"] = charset.name()\n return Challenge(scheme, authParams)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":78,"symbol":"scheme","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_scheme\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"scheme\"),\n level = DeprecationLevel.ERROR,\n )\n fun scheme(): String = scheme"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":86,"symbol":"authParams","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_authParams\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"authParams\"),\n level = DeprecationLevel.ERROR,\n )\n fun authParams(): Map = authParams"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":94,"symbol":"realm","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_realm\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"realm\"),\n level = DeprecationLevel.ERROR,\n )\n fun realm(): String? = realm"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":102,"symbol":"charset","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_charset\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"charset\"),\n level = DeprecationLevel.ERROR,\n )\n fun charset(): Charset = charset"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":110,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other is Challenge &&\n other.scheme == scheme &&\n other.authParams == authParams"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":115,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int {\n var result = 29\n result = 31 * result + scheme.hashCode()\n result = 31 * result + authParams.hashCode()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Challenge.kt","line":122,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"$scheme authParams=$authParams\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CipherSuite.kt","line":38,"symbol":"CipherSuite","kind":"class","lang":"kotlin","doc":"[iana_tls_parameters]: https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml [sslengine]: https://developer.android.com/reference/javax/net/ssl/SSLEngine.html [oracle_providers]: https://docs.oracle.com/javase/10/security/oracle-providers.htm [conscrypt_providers]: https://github.com/google/conscrypt/blob/master/common/src/main/java/org/conscrypt/NativeCrypto.java","code":"class CipherSuite private constructor(\n /**\n * Returns the Java name of this cipher suite. For some older cipher suites the Java name has the\n * prefix `SSL_`, causing the Java name to be different from the instance name which is always\n * prefixed `TLS_`. For example, `TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName()` is\n * `\"SSL_RSA_EXPORT_WITH_RC4_40_MD5\"`.\n */\n @get:JvmName(\"javaName\") val javaName: String,\n) {\n @JvmName(\"-deprecated_javaName\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"javaName\"),\n level = DeprecationLevel.ERROR,\n )\n fun javaName(): String = javaName\n\n override fun toString(): String = javaName\n\n companion object {\n /**\n * Compares cipher suites names like \"TLS_RSA_WITH_NULL_MD5\" and \"SSL_RSA_WITH_NULL_MD5\",\n * ignoring the \"TLS_\" or \"SSL_\" prefix which is not consistent across platforms. In particular\n * some IBM JVMs use the \"SSL_\" prefix everywhere whereas Oracle JVMs mix \"TLS_\" and \"SSL_\".\n */\n internal val ORDER_BY_NAME =\n object : Comparator {\n override fun compare(\n a: String,\n b: String,\n ): Int {\n var i = 4\n v"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CipherSuite.kt","line":47,"symbol":"javaName","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_javaName\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"javaName\"),\n level = DeprecationLevel.ERROR,\n )\n fun javaName(): String = javaName"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CipherSuite.kt","line":55,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = javaName"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CipherSuite.kt","line":65,"symbol":"compare","kind":"function","lang":"kotlin","code":"override fun compare(\n a: String,\n b: String,\n ): Int {\n var i = 4\n val limit = minOf(a.length, b.length)\n while (i < limit) {\n val charA = a[i]\n val charB = b[i]\n if (charA != charB) return if (charA < charB) -1 else 1\n i++\n }\n val lengthA = a.length\n val lengthB = b.length\n if (lengthA != lengthB) return if (lengthA < lengthB) -1 else 1\n return 0\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CipherSuite.kt","line":547,"symbol":"forJavaName","kind":"function","lang":"kotlin","doc":"@param javaName the name used by Java APIs for this cipher suite. Different than the IANA name for older cipher suites because the prefix is `SSL_` instead of `TLS_`.","code":"@JvmStatic\n @Synchronized fun forJavaName(javaName: String): CipherSuite {\n var result: CipherSuite? = INSTANCES[javaName]\n if (result == null) {\n result = INSTANCES[secondaryName(javaName)]\n\n if (result == null) {\n result = CipherSuite(javaName)\n }\n\n // Add the new cipher suite, or a confirmed alias.\n INSTANCES[javaName] = result\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CipherSuite.kt","line":563,"symbol":"secondaryName","kind":"function","lang":"kotlin","code":"private fun secondaryName(javaName: String): String =\n when {\n javaName.startsWith(\"TLS_\") -> \"SSL_\" + javaName.substring(4)\n javaName.startsWith(\"SSL_\") -> \"TLS_\" + javaName.substring(4)\n else -> javaName\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CipherSuite.kt","line":575,"symbol":"init","kind":"function","lang":"kotlin","doc":"@param javaName the name used by Java APIs for this cipher suite. Different than the IANA name for older cipher suites because the prefix is `SSL_` instead of `TLS_`. @param value the integer identifier for this cipher suite. (Documentation only.)","code":"private fun init(\n javaName: String,\n value: Int,\n ): CipherSuite {\n val suite = CipherSuite(javaName)\n INSTANCES[javaName] = suite\n return suite\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CompressionInterceptor.kt","line":34,"symbol":"CompressionInterceptor","kind":"class","lang":"kotlin","doc":"If [algorithms] is empty this interceptor has no effect. To disable compression set a specific \"Accept-Encoding: identity\" or similar. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept-Encoding","code":"open class CompressionInterceptor(\n vararg val algorithms: DecompressionAlgorithm,\n) : Interceptor {\n internal val acceptEncoding =\n algorithms\n .map {\n it.encoding\n }.joinToString(separator = \", \")\n\n override fun intercept(chain: Interceptor.Chain): Response =\n if (algorithms.isNotEmpty() && chain.request().header(\"Accept-Encoding\") == null) {\n val request =\n chain\n .request()\n .newBuilder()\n .header(\"Accept-Encoding\", acceptEncoding)\n .build()\n\n val response = chain.proceed(request)\n\n decompress(response)\n } else {\n chain.proceed(chain.request())\n }\n\n /**\n * Returns a decompressed copy of the Response, typically via a streaming Source.\n * If no known decompression or the response is not compressed, returns the response unmodified.\n */\n internal fun decompress(response: Response): Response {\n if (!response.promisesBody()) {\n return response\n }\n val body = response.body\n val encoding = response.header(\"Content-Encoding\") ?: return response\n\n val algorithm = lookupDecompressor(encoding) ?: return response\n\n val decompressedSource = algorithm.decompress(body.s"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CompressionInterceptor.kt","line":43,"symbol":"intercept","kind":"function","lang":"kotlin","code":"override fun intercept(chain: Interceptor.Chain): Response =\n if (algorithms.isNotEmpty() && chain.request().header(\"Accept-Encoding\") == null) {\n val request =\n chain\n .request()\n .newBuilder()\n .header(\"Accept-Encoding\", acceptEncoding)\n .build()\n\n val response = chain.proceed(request)\n\n decompress(response)\n } else {\n chain.proceed(chain.request())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CompressionInterceptor.kt","line":63,"symbol":"decompress","kind":"function","lang":"kotlin","doc":"Returns a decompressed copy of the Response, typically via a streaming Source. If no known decompression or the response is not compressed, returns the response unmodified.","code":"internal fun decompress(response: Response): Response {\n if (!response.promisesBody()) {\n return response\n }\n val body = response.body\n val encoding = response.header(\"Content-Encoding\") ?: return response\n\n val algorithm = lookupDecompressor(encoding) ?: return response\n\n val decompressedSource = algorithm.decompress(body.source()).buffer()\n\n return response\n .newBuilder()\n .removeHeader(\"Content-Encoding\")\n .removeHeader(\"Content-Length\")\n .body(decompressedSource.asResponseBody(body.contentType(), -1))\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CompressionInterceptor.kt","line":82,"symbol":"lookupDecompressor","kind":"function","lang":"kotlin","code":"internal fun lookupDecompressor(encoding: String): DecompressionAlgorithm? =\n algorithms.find {\n it.encoding.equals(encoding, ignoreCase = true)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CompressionInterceptor.kt","line":90,"symbol":"DecompressionAlgorithm","kind":"interface","lang":"kotlin","doc":"A decompression algorithm such as Gzip. Must provide the Accept-Encoding value and decompress a Source.","code":"interface DecompressionAlgorithm {\n val encoding: String\n\n fun decompress(compressedSource: BufferedSource): Source\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CompressionInterceptor.kt","line":93,"symbol":"decompress","kind":"function","lang":"kotlin","code":"fun decompress(compressedSource: BufferedSource): Source"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Connection.kt","line":69,"symbol":"Connection","kind":"interface","lang":"kotlin","doc":"Attempting to create new streams on these allocations will fail. Note that an allocation may be released before its stream is completed. This is intended to make bookkeeping easier for the caller: releasing the allocation as soon as the terminal stream has been found. But only complete the stream once its data stream has been exhausted.","code":"interface Connection {\n /** Returns the route used by this connection. */\n fun route(): Route\n\n /**\n * Returns the socket that this connection is using. Returns an\n * [SSL socket][javax.net.ssl.SSLSocket] if this connection is HTTPS. If this is an HTTP/2\n * connection the socket may be shared by multiple concurrent calls.\n */\n fun socket(): Socket\n\n /**\n * Returns the TLS handshake used to establish this connection, or null if the connection is not\n * HTTPS.\n */\n fun handshake(): Handshake?\n\n /**\n * Returns the protocol negotiated by this connection, or [Protocol.HTTP_1_1] if no protocol\n * has been negotiated. This method returns [Protocol.HTTP_1_1] even if the remote peer is using\n * [Protocol.HTTP_1_0].\n */\n fun protocol(): Protocol\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Connection.kt","line":71,"symbol":"route","kind":"function","lang":"kotlin","doc":"Returns the route used by this connection.","code":"fun route(): Route"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Connection.kt","line":78,"symbol":"socket","kind":"function","lang":"kotlin","doc":"Returns the socket that this connection is using. Returns an [SSL socket][javax.net.ssl.SSLSocket] if this connection is HTTPS. If this is an HTTP/2 connection the socket may be shared by multiple concurrent calls.","code":"fun socket(): Socket"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Connection.kt","line":84,"symbol":"handshake","kind":"function","lang":"kotlin","doc":"Returns the TLS handshake used to establish this connection, or null if the connection is not HTTPS.","code":"fun handshake(): Handshake?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Connection.kt","line":91,"symbol":"protocol","kind":"function","lang":"kotlin","doc":"Returns the protocol negotiated by this connection, or [Protocol.HTTP_1_1] if no protocol has been negotiated. This method returns [Protocol.HTTP_1_1] even if the remote peer is using [Protocol.HTTP_1_0].","code":"fun protocol(): Protocol"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionPool.kt","line":37,"symbol":"ConnectionPool","kind":"class","lang":"kotlin","doc":"@constructor Create a new connection pool with tuning parameters appropriate for a single-user application. The tuning parameters in this pool are subject to change in future OkHttp releases. Currently this pool holds up to 5 idle connections which will be evicted after 5 minutes of inactivity.","code":"class ConnectionPool internal constructor(\n internal val delegate: RealConnectionPool,\n) {\n internal constructor(\n maxIdleConnections: Int = 5,\n keepAliveDuration: Long = 5,\n timeUnit: TimeUnit = TimeUnit.MINUTES,\n taskRunner: TaskRunner = TaskRunner.INSTANCE,\n connectionListener: ConnectionListener = ConnectionListener.NONE,\n ) : this(\n RealConnectionPool(\n taskRunner = taskRunner,\n maxIdleConnections = maxIdleConnections,\n keepAliveDuration = keepAliveDuration,\n timeUnit = timeUnit,\n connectionListener = connectionListener,\n ),\n )\n\n // Internal until we promote ConnectionListener to be a public API.\n internal constructor(\n maxIdleConnections: Int = 5,\n keepAliveDuration: Long = 5,\n timeUnit: TimeUnit = TimeUnit.MINUTES,\n connectionListener: ConnectionListener = ConnectionListener.NONE,\n ) : this(\n taskRunner = TaskRunner.INSTANCE,\n maxIdleConnections = maxIdleConnections,\n keepAliveDuration = keepAliveDuration,\n timeUnit = timeUnit,\n connectionListener = connectionListener,\n )\n\n // Public API\n constructor(\n maxIdleConnections: Int,\n keepAliveDuration: Long,\n timeUnit: TimeUnit,\n ) : this("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionPool.kt","line":86,"symbol":"idleConnectionCount","kind":"function","lang":"kotlin","doc":"Returns the number of idle connections in the pool.","code":"fun idleConnectionCount(): Int = delegate.idleConnectionCount()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionPool.kt","line":89,"symbol":"connectionCount","kind":"function","lang":"kotlin","doc":"Returns total number of connections in the pool.","code":"fun connectionCount(): Int = delegate.connectionCount()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionPool.kt","line":95,"symbol":"evictAll","kind":"function","lang":"kotlin","doc":"Close and remove all idle connections in the pool.","code":"fun evictAll() {\n delegate.evictAll()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":47,"symbol":"ConnectionSpec","kind":"class","lang":"kotlin","doc":"your OkHttp library can break connectivity to certain web servers! But it’s a necessary annoyance because the TLS ecosystem is dynamic and staying up to date is necessary to stay secure. See [OkHttp's TLS Configuration History][tls_history] to track these changes. [tls_history]: https://lysine.dev/okhttp/tls_configuration_history/","code":"class ConnectionSpec internal constructor(\n @get:JvmName(\"isTls\") val isTls: Boolean,\n @get:JvmName(\"supportsTlsExtensions\") val supportsTlsExtensions: Boolean,\n internal val cipherSuitesAsString: Array?,\n private val tlsVersionsAsString: Array?,\n) {\n /**\n * Returns the cipher suites to use for a connection. Returns null if all of the SSL socket's\n * enabled cipher suites should be used.\n */\n @get:JvmName(\"cipherSuites\")\n val cipherSuites: List?\n get() {\n return cipherSuitesAsString?.map { CipherSuite.forJavaName(it) }\n }\n\n @JvmName(\"-deprecated_cipherSuites\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"cipherSuites\"),\n level = DeprecationLevel.ERROR,\n )\n fun cipherSuites(): List? = cipherSuites\n\n /**\n * Returns the TLS versions to use when negotiating a connection. Returns null if all of the SSL\n * socket's enabled TLS versions should be used.\n */\n @get:JvmName(\"tlsVersions\")\n val tlsVersions: List?\n get() {\n return tlsVersionsAsString?.map { TlsVersion.forJavaName(it) }\n }\n\n @JvmName(\"-deprecated_tlsVersions\")\n @Deprecated(\n mes"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":63,"symbol":"cipherSuites","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_cipherSuites\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"cipherSuites\"),\n level = DeprecationLevel.ERROR,\n )\n fun cipherSuites(): List? = cipherSuites"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":81,"symbol":"tlsVersions","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_tlsVersions\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"tlsVersions\"),\n level = DeprecationLevel.ERROR,\n )\n fun tlsVersions(): List? = tlsVersions"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":89,"symbol":"supportsTlsExtensions","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_supportsTlsExtensions\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"supportsTlsExtensions\"),\n level = DeprecationLevel.ERROR,\n )\n fun supportsTlsExtensions(): Boolean = supportsTlsExtensions"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":98,"symbol":"apply","kind":"function","lang":"kotlin","doc":"Applies this spec to [sslSocket].","code":"internal fun apply(\n sslSocket: SSLSocket,\n isFallback: Boolean,\n ) {\n val specToApply = supportedSpec(sslSocket, isFallback)\n\n if (specToApply.tlsVersions != null) {\n sslSocket.enabledProtocols = specToApply.tlsVersionsAsString\n }\n\n if (specToApply.cipherSuites != null) {\n sslSocket.enabledCipherSuites = specToApply.cipherSuitesAsString\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":116,"symbol":"supportedSpec","kind":"function","lang":"kotlin","doc":"Returns a copy of this that omits cipher suites and TLS versions not enabled by [sslSocket].","code":"private fun supportedSpec(\n sslSocket: SSLSocket,\n isFallback: Boolean,\n ): ConnectionSpec {\n val socketEnabledCipherSuites = sslSocket.enabledCipherSuites\n var cipherSuitesIntersection: Array = effectiveCipherSuites(socketEnabledCipherSuites)\n\n val tlsVersionsIntersection =\n if (tlsVersionsAsString != null) {\n sslSocket.enabledProtocols.intersect(tlsVersionsAsString, naturalOrder())\n } else {\n sslSocket.enabledProtocols\n }\n\n // In accordance with https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00 the SCSV\n // cipher is added to signal that a protocol fallback has taken place.\n val supportedCipherSuites = sslSocket.supportedCipherSuites\n val indexOfFallbackScsv =\n supportedCipherSuites.indexOf(\n \"TLS_FALLBACK_SCSV\",\n CipherSuite.ORDER_BY_NAME,\n )\n if (isFallback && indexOfFallbackScsv != -1) {\n cipherSuitesIntersection =\n cipherSuitesIntersection.concat(\n supportedCipherSuites[indexOfFallbackScsv],\n )\n }\n\n return Builder(this)\n .cipherSuites(*cipherSuitesIntersection)\n .tlsVersions(*tlsVersionsIntersection)\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":162,"symbol":"isCompatible","kind":"function","lang":"kotlin","doc":"socket's enabled cipher suites. If there are no required cipher suites the socket must have at least one cipher suite enabled. For protocols, at least one of the [required protocols][tlsVersions] must match the socket's enabled protocols.","code":"fun isCompatible(socket: SSLSocket): Boolean {\n if (!isTls) {\n return false\n }\n\n if (tlsVersionsAsString != null &&\n !tlsVersionsAsString.hasIntersection(socket.enabledProtocols, naturalOrder())\n ) {\n return false\n }\n\n if (cipherSuitesAsString != null &&\n !cipherSuitesAsString.hasIntersection(\n socket.enabledCipherSuites,\n CipherSuite.ORDER_BY_NAME,\n )\n ) {\n return false\n }\n\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":185,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean {\n if (other !is ConnectionSpec) return false\n if (other === this) return true\n\n if (this.isTls != other.isTls) return false\n\n if (isTls) {\n if (!Arrays.equals(this.cipherSuitesAsString, other.cipherSuitesAsString)) return false\n if (!Arrays.equals(this.tlsVersionsAsString, other.tlsVersionsAsString)) return false\n if (this.supportsTlsExtensions != other.supportsTlsExtensions) return false\n }\n\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":200,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int {\n var result = 17\n if (isTls) {\n result = 31 * result + (cipherSuitesAsString?.contentHashCode() ?: 0)\n result = 31 * result + (tlsVersionsAsString?.contentHashCode() ?: 0)\n result = 31 * result + if (supportsTlsExtensions) 0 else 1\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":210,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String {\n if (!isTls) return \"ConnectionSpec()\"\n\n return (\n \"ConnectionSpec(\" +\n \"cipherSuites=${Objects.toString(cipherSuites, \"[all enabled]\")}, \" +\n \"tlsVersions=${Objects.toString(tlsVersions, \"[all enabled]\")}, \" +\n \"supportsTlsExtensions=$supportsTlsExtensions)\"\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":221,"symbol":"Builder","kind":"class","lang":"kotlin","code":"class Builder {\n internal var tls: Boolean = false\n internal var cipherSuites: Array? = null\n internal var tlsVersions: Array? = null\n internal var supportsTlsExtensions: Boolean = false\n\n internal constructor(tls: Boolean) {\n this.tls = tls\n }\n\n constructor(connectionSpec: ConnectionSpec) {\n this.tls = connectionSpec.isTls\n this.cipherSuites = connectionSpec.cipherSuitesAsString\n this.tlsVersions = connectionSpec.tlsVersionsAsString\n this.supportsTlsExtensions = connectionSpec.supportsTlsExtensions\n }\n\n fun allEnabledCipherSuites() =\n apply {\n require(tls) { \"no cipher suites for cleartext connections\" }\n this.cipherSuites = null\n }\n\n fun cipherSuites(vararg cipherSuites: CipherSuite): Builder =\n apply {\n require(tls) { \"no cipher suites for cleartext connections\" }\n val strings = cipherSuites.map { it.javaName }.toTypedArray()\n return cipherSuites(*strings)\n }\n\n fun cipherSuites(vararg cipherSuites: String) =\n apply {\n require(tls) { \"no cipher suites for cleartext connections\" }\n require(cipherSuites.isNotEmpty()) { \"At least one cip"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":238,"symbol":"allEnabledCipherSuites","kind":"function","lang":"kotlin","code":"fun allEnabledCipherSuites() =\n apply {\n require(tls) { \"no cipher suites for cleartext connections\" }\n this.cipherSuites = null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":244,"symbol":"cipherSuites","kind":"function","lang":"kotlin","code":"fun cipherSuites(vararg cipherSuites: CipherSuite): Builder =\n apply {\n require(tls) { \"no cipher suites for cleartext connections\" }\n val strings = cipherSuites.map { it.javaName }.toTypedArray()\n return cipherSuites(*strings)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":251,"symbol":"cipherSuites","kind":"function","lang":"kotlin","code":"fun cipherSuites(vararg cipherSuites: String) =\n apply {\n require(tls) { \"no cipher suites for cleartext connections\" }\n require(cipherSuites.isNotEmpty()) { \"At least one cipher suite is required\" }\n\n @Suppress(\"UNCHECKED_CAST\")\n this.cipherSuites = cipherSuites.copyOf() as Array // Defensive copy.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":260,"symbol":"allEnabledTlsVersions","kind":"function","lang":"kotlin","code":"fun allEnabledTlsVersions() =\n apply {\n require(tls) { \"no TLS versions for cleartext connections\" }\n this.tlsVersions = null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":266,"symbol":"tlsVersions","kind":"function","lang":"kotlin","code":"fun tlsVersions(vararg tlsVersions: TlsVersion): Builder =\n apply {\n require(tls) { \"no TLS versions for cleartext connections\" }\n\n val strings = tlsVersions.map { it.javaName }.toTypedArray()\n return tlsVersions(*strings)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":274,"symbol":"tlsVersions","kind":"function","lang":"kotlin","code":"fun tlsVersions(vararg tlsVersions: String) =\n apply {\n require(tls) { \"no TLS versions for cleartext connections\" }\n require(tlsVersions.isNotEmpty()) { \"At least one TLS version is required\" }\n\n @Suppress(\"UNCHECKED_CAST\")\n this.tlsVersions = tlsVersions.copyOf() as Array // Defensive copy.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":283,"symbol":"supportsTlsExtensions","kind":"function","lang":"kotlin","code":"@Deprecated(\n \"since OkHttp 3.13 all TLS-connections are expected to support TLS extensions.\\n\" +\n \"In a future release setting this to true will be unnecessary and setting it to false\\n\" +\n \"will have no effect.\",\n )\n fun supportsTlsExtensions(supportsTlsExtensions: Boolean) =\n apply {\n require(tls) { \"no TLS extensions for cleartext connections\" }\n this.supportsTlsExtensions = supportsTlsExtensions\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ConnectionSpec.kt","line":294,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): ConnectionSpec =\n ConnectionSpec(\n tls,\n supportsTlsExtensions,\n cipherSuites,\n tlsVersions,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":43,"symbol":"Cookie","kind":"class","lang":"kotlin","doc":"This class doesn't support additional attributes on cookies, like [Chromium's Priority=HIGH extension][chromium_extension]. [chromium_extension]: https://code.google.com/p/chromium/issues/detail?id=232693","code":"@Suppress(\"NAME_SHADOWING\")\nclass Cookie private constructor(\n /** Returns a non-empty string with this cookie's name. */\n @get:JvmName(\"name\") val name: String,\n /** Returns a possibly-empty string with this cookie's value. */\n @get:JvmName(\"value\") val value: String,\n /**\n * Returns the time that this cookie expires, in the same format as [System.currentTimeMillis].\n * This is December 31, 9999 if the cookie is not [persistent], in which case it will expire at the\n * end of the current session.\n *\n * This may return a value less than the current time, in which case the cookie is already\n * expired. Webservers may return expired cookies as a mechanism to delete previously set cookies\n * that may or may not themselves be expired.\n */\n @get:JvmName(\"expiresAt\") val expiresAt: Long,\n /**\n * Returns the cookie's domain. If [hostOnly] returns true this is the only domain that matches\n * this cookie; otherwise it matches this domain and all subdomains.\n */\n @get:JvmName(\"domain\") val domain: String,\n /**\n * Returns this cookie's path. This cookie matches URLs prefixed with path segments that match\n * this path's segments. For example, if this path is `"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":127,"symbol":"matches","kind":"function","lang":"kotlin","doc":"Returns true if this cookie should be included on a request to [url]. In addition to this check callers should also confirm that this cookie has not expired.","code":"fun matches(url: HttpUrl): Boolean {\n val domainMatch =\n if (hostOnly) {\n url.host == domain\n } else {\n domainMatch(url.host, domain)\n }\n if (!domainMatch) return false\n\n if (!pathMatch(url, path)) return false\n\n return !secure || url.isHttps\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":141,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other is Cookie &&\n other.name == name &&\n other.value == value &&\n other.expiresAt == expiresAt &&\n other.domain == domain &&\n other.path == path &&\n other.secure == secure &&\n other.httpOnly == httpOnly &&\n other.persistent == persistent &&\n other.hostOnly == hostOnly &&\n other.sameSite == sameSite"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":154,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"@IgnoreJRERequirement // As of AGP 3.4.1, D8 desugars API 24 hashCode methods.\n override fun hashCode(): Int {\n var result = 17\n result = 31 * result + name.hashCode()\n result = 31 * result + value.hashCode()\n result = 31 * result + expiresAt.hashCode()\n result = 31 * result + domain.hashCode()\n result = 31 * result + path.hashCode()\n result = 31 * result + secure.hashCode()\n result = 31 * result + httpOnly.hashCode()\n result = 31 * result + persistent.hashCode()\n result = 31 * result + hostOnly.hashCode()\n result = 31 * result + sameSite.hashCode()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":170,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = toString(false)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":172,"symbol":"name","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_name\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"name\"),\n level = DeprecationLevel.ERROR,\n )\n fun name(): String = name"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":180,"symbol":"value","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_value\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"value\"),\n level = DeprecationLevel.ERROR,\n )\n fun value(): String = value"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":188,"symbol":"persistent","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_persistent\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"persistent\"),\n level = DeprecationLevel.ERROR,\n )\n fun persistent(): Boolean = persistent"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":196,"symbol":"expiresAt","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_expiresAt\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"expiresAt\"),\n level = DeprecationLevel.ERROR,\n )\n fun expiresAt(): Long = expiresAt"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":204,"symbol":"hostOnly","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_hostOnly\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"hostOnly\"),\n level = DeprecationLevel.ERROR,\n )\n fun hostOnly(): Boolean = hostOnly"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":212,"symbol":"domain","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_domain\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"domain\"),\n level = DeprecationLevel.ERROR,\n )\n fun domain(): String = domain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":220,"symbol":"path","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_path\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"path\"),\n level = DeprecationLevel.ERROR,\n )\n fun path(): String = path"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":228,"symbol":"httpOnly","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_httpOnly\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"httpOnly\"),\n level = DeprecationLevel.ERROR,\n )\n fun httpOnly(): Boolean = httpOnly"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":236,"symbol":"secure","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_secure\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"secure\"),\n level = DeprecationLevel.ERROR,\n )\n fun secure(): Boolean = secure"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":249,"symbol":"toString","kind":"function","lang":"kotlin","doc":"@param forObsoleteRfc2965 true to include a leading `.` on the domain pattern. This is necessary for `example.com` to match `www.example.com` under RFC 2965. This extra dot is ignored by more recent specifications.","code":"internal fun toString(forObsoleteRfc2965: Boolean): String {\n return buildString {\n append(name)\n append('=')\n append(value)\n\n if (persistent) {\n if (expiresAt == Long.MIN_VALUE) {\n append(\"; max-age=0\")\n } else {\n append(\"; expires=\").append(Date(expiresAt).toHttpDateString())\n }\n }\n\n if (!hostOnly) {\n append(\"; domain=\")\n if (forObsoleteRfc2965) {\n append(\".\")\n }\n append(domain)\n }\n\n append(\"; path=\").append(path)\n\n if (secure) {\n append(\"; secure\")\n }\n\n if (httpOnly) {\n append(\"; httponly\")\n }\n\n if (sameSite != null) {\n append(\"; samesite=\").append(sameSite)\n }\n\n return toString()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":289,"symbol":"newBuilder","kind":"function","lang":"kotlin","code":"fun newBuilder(): Builder = Builder(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":295,"symbol":"Builder","kind":"class","lang":"kotlin","doc":"Builds a cookie. The [name], [value], and [domain] values must all be set before calling [build].","code":"class Builder() {\n private var name: String? = null\n private var value: String? = null\n private var expiresAt = MAX_DATE\n private var domain: String? = null\n private var path = \"/\"\n private var secure = false\n private var httpOnly = false\n private var persistent = false\n private var hostOnly = false\n private var sameSite: String? = null\n\n internal constructor(cookie: Cookie) : this() {\n this.name = cookie.name\n this.value = cookie.value\n this.expiresAt = cookie.expiresAt\n this.domain = cookie.domain\n this.path = cookie.path\n this.secure = cookie.secure\n this.httpOnly = cookie.httpOnly\n this.persistent = cookie.persistent\n this.hostOnly = cookie.hostOnly\n this.sameSite = cookie.sameSite\n }\n\n fun name(name: String) =\n apply {\n require(name.trim() == name) { \"name is not trimmed\" }\n this.name = name\n }\n\n fun value(value: String) =\n apply {\n require(value.trim() == value) { \"value is not trimmed\" }\n this.value = value\n }\n\n fun expiresAt(expiresAt: Long) =\n apply {\n var expiresAt = expiresAt\n if (expiresAt <= 0L) expiresAt = Lo"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":320,"symbol":"name","kind":"function","lang":"kotlin","code":"fun name(name: String) =\n apply {\n require(name.trim() == name) { \"name is not trimmed\" }\n this.name = name\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":326,"symbol":"value","kind":"function","lang":"kotlin","code":"fun value(value: String) =\n apply {\n require(value.trim() == value) { \"value is not trimmed\" }\n this.value = value\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":332,"symbol":"expiresAt","kind":"function","lang":"kotlin","code":"fun expiresAt(expiresAt: Long) =\n apply {\n var expiresAt = expiresAt\n if (expiresAt <= 0L) expiresAt = Long.MIN_VALUE\n if (expiresAt > MAX_DATE) expiresAt = MAX_DATE\n this.expiresAt = expiresAt\n this.persistent = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":345,"symbol":"domain","kind":"function","lang":"kotlin","doc":"Set the domain pattern for this cookie. The cookie will match [domain] and all of its subdomains.","code":"fun domain(domain: String): Builder = domain(domain, false)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":351,"symbol":"hostOnlyDomain","kind":"function","lang":"kotlin","doc":"Set the host-only domain for this cookie. The cookie will match [domain] but none of its subdomains.","code":"fun hostOnlyDomain(domain: String): Builder = domain(domain, true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":353,"symbol":"domain","kind":"function","lang":"kotlin","code":"private fun domain(\n domain: String,\n hostOnly: Boolean,\n ) = apply {\n val canonicalDomain =\n domain.toCanonicalHost()\n ?: throw IllegalArgumentException(\"unexpected domain: $domain\")\n this.domain = canonicalDomain\n this.hostOnly = hostOnly\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":364,"symbol":"path","kind":"function","lang":"kotlin","code":"fun path(path: String) =\n apply {\n require(path.startsWith(\"/\")) { \"path must start with '/'\" }\n this.path = path\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":370,"symbol":"secure","kind":"function","lang":"kotlin","code":"fun secure() =\n apply {\n this.secure = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":375,"symbol":"httpOnly","kind":"function","lang":"kotlin","code":"fun httpOnly() =\n apply {\n this.httpOnly = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":380,"symbol":"sameSite","kind":"function","lang":"kotlin","code":"fun sameSite(sameSite: String) =\n apply {\n require(sameSite.trim() == sameSite) { \"sameSite is not trimmed\" }\n this.sameSite = sameSite\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":386,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): Cookie =\n Cookie(\n name ?: throw NullPointerException(\"builder.name == null\"),\n value ?: throw NullPointerException(\"builder.value == null\"),\n expiresAt,\n domain ?: throw NullPointerException(\"builder.domain == null\"),\n path,\n secure,\n httpOnly,\n persistent,\n hostOnly,\n sameSite,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":409,"symbol":"domainMatch","kind":"function","lang":"kotlin","code":"private fun domainMatch(\n urlHost: String,\n domain: String,\n ): Boolean {\n if (urlHost == domain) {\n return true // As in 'example.com' matching 'example.com'.\n }\n\n return urlHost.endsWith(domain) &&\n urlHost[urlHost.length - domain.length - 1] == '.' &&\n !urlHost.canParseAsIpAddress()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":422,"symbol":"pathMatch","kind":"function","lang":"kotlin","code":"private fun pathMatch(\n url: HttpUrl,\n path: String,\n ): Boolean {\n val urlPath = url.encodedPath\n\n if (urlPath == path) {\n return true // As in '/foo' matching '/foo'.\n }\n\n if (urlPath.startsWith(path)) {\n if (path.endsWith(\"/\")) return true // As in '/' matching '/foo'.\n if (urlPath[path.length] == '/') return true // As in '/foo' matching '/foo/bar'.\n }\n\n return false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":444,"symbol":"parse","kind":"function","lang":"kotlin","doc":"Attempt to parse a `Set-Cookie` HTTP header value [setCookie] as a cookie. Returns null if [setCookie] is not a well-formed cookie.","code":"@JvmStatic\n fun parse(\n url: HttpUrl,\n setCookie: String,\n ): Cookie? = parse(System.currentTimeMillis(), url, setCookie)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":450,"symbol":"parse","kind":"function","lang":"kotlin","code":"internal fun parse(\n currentTimeMillis: Long,\n url: HttpUrl,\n setCookie: String,\n ): Cookie? {\n val cookiePairEnd = setCookie.delimiterOffset(';')\n\n val pairEqualsSign = setCookie.delimiterOffset('=', endIndex = cookiePairEnd)\n if (pairEqualsSign == cookiePairEnd) return null\n\n val cookieName = setCookie.trimSubstring(endIndex = pairEqualsSign)\n if (cookieName.isEmpty() || cookieName.indexOfControlOrNonAscii() != -1) return null\n\n val cookieValue = setCookie.trimSubstring(pairEqualsSign + 1, cookiePairEnd)\n if (cookieValue.indexOfControlOrNonAscii() != -1) return null\n\n var expiresAt = MAX_DATE\n var deltaSeconds = -1L\n var domain: String? = null\n var path: String? = null\n var secureOnly = false\n var httpOnly = false\n var hostOnly = true\n var persistent = false\n var sameSite: String? = null\n\n var pos = cookiePairEnd + 1\n val limit = setCookie.length\n while (pos < limit) {\n val attributePairEnd = setCookie.delimiterOffset(';', pos, limit)\n\n val attributeEqualsSign = setCookie.delimiterOffset('=', pos, attributePairEnd)\n val attributeName = setCookie.tr"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":593,"symbol":"parseExpires","kind":"function","lang":"kotlin","doc":"Parse a date as specified in RFC 6265, section 5.1.1.","code":"private fun parseExpires(\n s: String,\n pos: Int,\n limit: Int,\n ): Long {\n var pos = pos\n pos = dateCharacterOffset(s, pos, limit, false)\n\n var hour = -1\n var minute = -1\n var second = -1\n var dayOfMonth = -1\n var month = -1\n var year = -1\n val matcher = TIME_PATTERN.matcher(s)\n\n while (pos < limit) {\n val end = dateCharacterOffset(s, pos + 1, limit, true)\n matcher.region(pos, end)\n\n when {\n hour == -1 && matcher.usePattern(TIME_PATTERN).matches() -> {\n hour = matcher.group(1).toInt()\n minute = matcher.group(2).toInt()\n second = matcher.group(3).toInt()\n }\n\n dayOfMonth == -1 && matcher.usePattern(DAY_OF_MONTH_PATTERN).matches() -> {\n dayOfMonth = matcher.group(1).toInt()\n }\n\n month == -1 && matcher.usePattern(MONTH_PATTERN).matches() -> {\n val monthString = matcher.group(1).lowercase(Locale.US)\n month = MONTH_PATTERN.pattern().indexOf(monthString) / 4 // Sneaky! jan=1, dec=12.\n }\n\n year == -1 && matcher.usePattern(YEAR_PATTERN).matches() -> {\n year = matcher"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":667,"symbol":"dateCharacterOffset","kind":"function","lang":"kotlin","doc":"Returns the index of the next date character in `input`, or if `invert` the index of the next non-date character in `input`.","code":"private fun dateCharacterOffset(\n input: String,\n pos: Int,\n limit: Int,\n invert: Boolean,\n ): Int {\n for (i in pos until limit) {\n val c = input[i].code\n val dateCharacter =\n (\n (\n ((c < ' '.code) && (c != '\\t'.code)) || (c >= '\\u007f'.code) || (c in ('0'.code..'9'.code)) || (c in ('a'.code..'z'.code)) ||\n (c in ('A'.code..'Z'.code)) ||\n (c == ':'.code)\n )\n )\n if (dateCharacter == !invert) return i\n }\n return limit\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":694,"symbol":"parseMaxAge","kind":"function","lang":"kotlin","doc":"Returns the positive value if [s] is positive, or [Long.MIN_VALUE] if it is either 0 or negative. If the value is positive but out of range, this returns [Long.MAX_VALUE]. @throws NumberFormatException if [s] is not an integer of any precision.","code":"private fun parseMaxAge(s: String): Long {\n try {\n val parsed = s.toLong()\n return if (parsed <= 0L) Long.MIN_VALUE else parsed\n } catch (e: NumberFormatException) {\n // Check if the value is an integer (positive or negative) that's too big for a long.\n if (s.matches(\"-?\\\\d+\".toRegex())) {\n return if (s.startsWith(\"-\")) Long.MIN_VALUE else Long.MAX_VALUE\n }\n throw e\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":711,"symbol":"parseDomain","kind":"function","lang":"kotlin","doc":"Returns a domain string like `example.com` for an input domain like `EXAMPLE.COM` or `.example.com`.","code":"private fun parseDomain(s: String): String {\n require(!s.endsWith(\".\"))\n return s.removePrefix(\".\").toCanonicalHost() ?: throw IllegalArgumentException()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cookie.kt","line":717,"symbol":"parseAll","kind":"function","lang":"kotlin","doc":"Returns all of the cookies from a set of HTTP response headers.","code":"@JvmStatic\n fun parseAll(\n url: HttpUrl,\n headers: Headers,\n ): List {\n val cookieStrings = headers.values(\"Set-Cookie\")\n var cookies: MutableList? = null\n\n for (i in 0 until cookieStrings.size) {\n val cookie = parse(url, cookieStrings[i]) ?: continue\n if (cookies == null) cookies = mutableListOf()\n cookies.add(cookie)\n }\n\n return cookies?.unmodifiable().orEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CookieJar.kt","line":32,"symbol":"CookieJar","kind":"interface","lang":"kotlin","doc":"implementations may store cookies in memory; sophisticated ones may use the file system or database to hold accepted cookies. The [cookie storage model][rfc_6265_53] specifies policies for updating and expiring cookies. [rfc_6265_53]: https://tools.ietf.org/html/rfc6265#section-5.3","code":"interface CookieJar {\n /**\n * Saves [cookies] from an HTTP response to this store according to this jar's policy.\n *\n * Note that this method may be called a second time for a single HTTP response if the response\n * includes a trailer. For this obscure HTTP feature, [cookies] contains only the trailer's\n * cookies.\n */\n fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n )\n\n /**\n * Load cookies from the jar for an HTTP request to [url]. This method returns a possibly\n * empty list of cookies for the network request.\n *\n * Simple implementations will return the accepted cookies that have not yet expired and that\n * [match][Cookie.matches] [url].\n */\n fun loadForRequest(url: HttpUrl): List\n\n companion object {\n /** A cookie jar that never accepts any cookies. */\n @JvmField\n val NO_COOKIES: CookieJar = NoCookies()\n\n private class NoCookies : CookieJar {\n override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) {\n }\n\n override fun loadForRequest(url: HttpUrl): List = emptyList()\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CookieJar.kt","line":40,"symbol":"saveFromResponse","kind":"function","lang":"kotlin","doc":"Saves [cookies] from an HTTP response to this store according to this jar's policy. Note that this method may be called a second time for a single HTTP response if the response includes a trailer. For this obscure HTTP feature, [cookies] contains only the trailer's cookies.","code":"fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CookieJar.kt","line":52,"symbol":"loadForRequest","kind":"function","lang":"kotlin","doc":"Load cookies from the jar for an HTTP request to [url]. This method returns a possibly empty list of cookies for the network request. Simple implementations will return the accepted cookies that have not yet expired and that [match][Cookie.matches] [url].","code":"fun loadForRequest(url: HttpUrl): List"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CookieJar.kt","line":59,"symbol":"NoCookies","kind":"class","lang":"kotlin","code":"private class NoCookies : CookieJar {\n override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) {\n }\n\n override fun loadForRequest(url: HttpUrl): List = emptyList()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CookieJar.kt","line":60,"symbol":"saveFromResponse","kind":"function","lang":"kotlin","code":"override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/CookieJar.kt","line":66,"symbol":"loadForRequest","kind":"function","lang":"kotlin","code":"override fun loadForRequest(url: HttpUrl): List = emptyList()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Credentials.kt","line":23,"symbol":"Credentials","kind":"object","lang":"kotlin","doc":"Factory for HTTP authorization credentials.","code":"object Credentials {\n /** Returns an auth credential for the Basic scheme. */\n @JvmStatic @JvmOverloads\n fun basic(\n username: String,\n password: String,\n charset: Charset = ISO_8859_1,\n ): String {\n val usernameAndPassword = \"$username:$password\"\n val encoded = usernameAndPassword.encode(charset).base64()\n return \"Basic $encoded\"\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Credentials.kt","line":25,"symbol":"basic","kind":"function","lang":"kotlin","doc":"Returns an auth credential for the Basic scheme.","code":"@JvmStatic @JvmOverloads\n fun basic(\n username: String,\n password: String,\n charset: Charset = ISO_8859_1,\n ): String {\n val usernameAndPassword = \"$username:$password\"\n val encoded = usernameAndPassword.encode(charset).base64()\n return \"Basic $encoded\"\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":44,"symbol":"Dispatcher","kind":"class","lang":"kotlin","doc":"are already running. A pool sized exactly to [maxRequests] is not sufficient with a [SynchronousQueue], because the dispatcher may submit the next call from a worker that has not yet returned to the queue. Prefer the default pattern (`corePoolSize=0`, `maxPoolSize=Int.MAX_VALUE`, [SynchronousQueue]), a bound of about `2 * maxRequests`, or a queueing executor.","code":"class Dispatcher() {\n /**\n * The maximum number of requests to execute concurrently. Above this requests queue in memory,\n * waiting for the running calls to complete.\n *\n * If more than [maxRequests] requests are in flight when this is invoked, those requests will\n * remain in flight.\n */\n @get:Synchronized\n var maxRequests = 64\n set(maxRequests) {\n require(maxRequests >= 1) { \"max < 1: $maxRequests\" }\n synchronized(this) {\n field = maxRequests\n }\n promoteAndExecute()\n }\n\n /**\n * The maximum number of requests for each host to execute concurrently. This limits requests by\n * the URL's host name. Note that concurrent requests to a single IP address may still exceed this\n * limit: multiple hostnames may share an IP address or be routed through the same HTTP proxy.\n *\n * If more than [maxRequestsPerHost] requests are in flight when this is invoked, those requests\n * will remain in flight.\n *\n * WebSocket connections to hosts **do not** count against this limit.\n */\n @get:Synchronized\n var maxRequestsPerHost = 5\n set(maxRequestsPerHost) {\n require(maxRequestsPerHost >= 1) { \"max < 1: $maxRequestsPerHost\" }\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":130,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"internal fun enqueue(call: AsyncCall) {\n promoteAndExecute(enqueuedCall = call)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":134,"symbol":"findExistingCallWithHost","kind":"function","lang":"kotlin","code":"private fun findExistingCallWithHost(host: String): AsyncCall? {\n for (existingCall in runningAsyncCalls) {\n if (existingCall.host == host) return existingCall\n }\n for (existingCall in readyAsyncCalls) {\n if (existingCall.host == host) return existingCall\n }\n return null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":148,"symbol":"cancelAll","kind":"function","lang":"kotlin","doc":"Cancel all calls currently enqueued or executing. Includes calls executed both [synchronously][Call.execute] and [asynchronously][Call.enqueue].","code":"@Synchronized\n fun cancelAll() {\n for (call in readyAsyncCalls) {\n call.call.cancel()\n }\n for (call in runningAsyncCalls) {\n call.call.cancel()\n }\n for (call in runningSyncCalls) {\n call.cancel()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":170,"symbol":"promoteAndExecute","kind":"function","lang":"kotlin","doc":"into user code. @param enqueuedCall a call to enqueue in the synchronized block @param finishedCall a call to finish in the synchronized block @param finishedAsyncCall an async call to finish in the synchronized block","code":"private fun promoteAndExecute(\n enqueuedCall: AsyncCall? = null,\n finishedCall: RealCall? = null,\n finishedAsyncCall: AsyncCall? = null,\n ) {\n assertLockNotHeld()\n val executorIsShutdown = executorService.isShutdown\n\n // Actions to take outside the synchronized block.\n class Effects(\n val callsToExecute: List,\n val idleCallbackToRun: Runnable?,\n )\n\n val effects =\n synchronized(this) {\n if (finishedCall != null) {\n check(runningSyncCalls.remove(finishedCall)) { \"Call wasn't in-flight!\" }\n }\n\n if (finishedAsyncCall != null) {\n finishedAsyncCall.callsPerHost.decrementAndGet()\n check(runningAsyncCalls.remove(finishedAsyncCall)) { \"Call wasn't in-flight!\" }\n }\n\n if (enqueuedCall != null) {\n readyAsyncCalls.add(enqueuedCall)\n\n // Mutate the AsyncCall so that it shares the AtomicInteger of an existing running call to\n // the same host.\n if (!enqueuedCall.call.forWebSocket) {\n val existingCall = findExistingCallWithHost(enqueuedCall.host)\n if (existingCall != null) enqueuedCall.reuseCallsPerHostFrom(existingCall)\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":271,"symbol":"executed","kind":"function","lang":"kotlin","doc":"Used by [Call.execute] to signal it is in-flight.","code":"@Synchronized\n internal fun executed(call: RealCall) = runningSyncCalls.add(call)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":275,"symbol":"finished","kind":"function","lang":"kotlin","doc":"Used by [AsyncCall.run] to signal completion.","code":"internal fun finished(call: AsyncCall) {\n promoteAndExecute(finishedAsyncCall = call)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":280,"symbol":"finished","kind":"function","lang":"kotlin","doc":"Used by [Call.execute] to signal completion.","code":"internal fun finished(call: RealCall) {\n promoteAndExecute(finishedCall = call)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":285,"symbol":"queuedCalls","kind":"function","lang":"kotlin","doc":"Returns a snapshot of the calls currently awaiting execution.","code":"@Synchronized\n fun queuedCalls(): List = readyAsyncCalls.map { it.call }.unmodifiable()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":289,"symbol":"runningCalls","kind":"function","lang":"kotlin","doc":"Returns a snapshot of the calls currently being executed.","code":"@Synchronized\n fun runningCalls(): List = (runningSyncCalls + runningAsyncCalls.map { it.call }).unmodifiable()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":292,"symbol":"queuedCallsCount","kind":"function","lang":"kotlin","code":"@Synchronized\n fun queuedCallsCount(): Int = readyAsyncCalls.size"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":295,"symbol":"runningCallsCount","kind":"function","lang":"kotlin","code":"@Synchronized\n fun runningCallsCount(): Int = runningAsyncCalls.size + runningSyncCalls.size"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dispatcher.kt","line":298,"symbol":"executorService","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_executorService\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"executorService\"),\n level = DeprecationLevel.ERROR,\n )\n fun executorService(): ExecutorService = executorService"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":42,"symbol":"Dns","kind":"interface","lang":"kotlin","doc":"write DNS records. [Dns.SYSTEM] is the default implementation. Implementations of this interface must be safe for concurrent use.","code":"fun interface Dns {\n /**\n * Returns the IP addresses of `hostname`.\n *\n * If a connection to an address fails, OkHttp will retry the connection with the next address\n * until either a connection is made, the set of IP addresses is exhausted, or a limit is\n * exceeded.\n */\n @Throws(UnknownHostException::class)\n fun lookup(hostname: String): List\n\n /** Recursively resolve [request] to learn IP addresses and service metadata to connect. */\n fun newCall(request: Request): Call = LookupDnsCall(TaskRunner.INSTANCE, this, request)\n\n interface Call {\n val request: Request\n\n fun enqueue(callback: Callback)\n\n /** This does nothing if the call is already complete. */\n fun cancel()\n\n fun isCanceled(): Boolean\n }\n\n /**\n * Receives a stream of records from the DNS server.\n *\n * Calls to [onRecords] and [onFailure] may be invoked by different threads, but never in\n * parallel: a call will not be made until the prior call has returned.\n */\n interface Callback {\n /**\n * @param last true if this is the last list of records for this address. That is a terminal\n * event and no further calls to this callback will be made for this c"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":50,"symbol":"lookup","kind":"function","lang":"kotlin","doc":"Returns the IP addresses of `hostname`. If a connection to an address fails, OkHttp will retry the connection with the next address until either a connection is made, the set of IP addresses is exhausted, or a limit is exceeded.","code":"@Throws(UnknownHostException::class)\n fun lookup(hostname: String): List"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":54,"symbol":"newCall","kind":"function","lang":"kotlin","doc":"Recursively resolve [request] to learn IP addresses and service metadata to connect.","code":"fun newCall(request: Request): Call = LookupDnsCall(TaskRunner.INSTANCE, this, request)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":56,"symbol":"Call","kind":"interface","lang":"kotlin","code":"interface Call {\n val request: Request\n\n fun enqueue(callback: Callback)\n\n /** This does nothing if the call is already complete. */\n fun cancel()\n\n fun isCanceled(): Boolean\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":59,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"fun enqueue(callback: Callback)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":62,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"This does nothing if the call is already complete.","code":"fun cancel()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":64,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"fun isCanceled(): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":73,"symbol":"Callback","kind":"interface","lang":"kotlin","doc":"Receives a stream of records from the DNS server. Calls to [onRecords] and [onFailure] may be invoked by different threads, but never in parallel: a call will not be made until the prior call has returned.","code":"interface Callback {\n /**\n * @param last true if this is the last list of records for this address. That is a terminal\n * event and no further calls to this callback will be made for this call.\n * @param records a possibly-empty set of records received from the name server.\n */\n fun onRecords(\n call: Call,\n last: Boolean,\n records: List,\n )\n\n /**\n * This is a terminal event and no further calls to this callback will be made for this call.\n */\n fun onFailure(\n call: Call,\n e: IOException,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":79,"symbol":"onRecords","kind":"function","lang":"kotlin","doc":"@param last true if this is the last list of records for this address. That is a terminal event and no further calls to this callback will be made for this call. @param records a possibly-empty set of records received from the name server.","code":"fun onRecords(\n call: Call,\n last: Boolean,\n records: List,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":88,"symbol":"onFailure","kind":"function","lang":"kotlin","doc":"This is a terminal event and no further calls to this callback will be made for this call.","code":"fun onFailure(\n call: Call,\n e: IOException,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":132,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?) = other is Request && other.hostname == hostname && other.port == port"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":134,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode() = (31 * hostname.hashCode()) + port"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":136,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n when (port) {\n 443 -> hostname\n else -> \"$hostname:$port\"\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":143,"symbol":"Record","kind":"class","lang":"kotlin","code":"sealed class Record private constructor() {\n /**\n * The hostname that this record applies to.\n *\n * A single hostname (`api.example.com`) may be served by multiple supporting servers. For\n * example, this is useful for geographic distribution (`us-east.api.example.com` and\n * `eu-central.api.example.com`), and for change management (`blue.api.example.com`,\n * `green.api.example.com`).\n *\n * This field will be different from [Request.hostname] if it is served by alternate hostname,\n * as above. This will be that original hostname if no alternate hostnames are in use, or if the\n * underlying DNS resolver doesn't expose that data.\n */\n abstract val hostname: String\n\n /** An IPv4 or IPv6 address for this host. */\n class IpAddress(\n hostname: String,\n @get:JvmName(\"address\") val address: InetAddress,\n ) : Record() {\n @get:JvmName(\"hostname\")\n override val hostname: String =\n hostname.toCanonicalHost()\n ?: throw IllegalArgumentException(\"unexpected hostname: $hostname\")\n\n override fun equals(other: Any?) = other is IpAddress && other.hostname == hostname && other.address == address\n\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":159,"symbol":"IpAddress","kind":"class","lang":"kotlin","doc":"An IPv4 or IPv6 address for this host.","code":"class IpAddress(\n hostname: String,\n @get:JvmName(\"address\") val address: InetAddress,\n ) : Record() {\n @get:JvmName(\"hostname\")\n override val hostname: String =\n hostname.toCanonicalHost()\n ?: throw IllegalArgumentException(\"unexpected hostname: $hostname\")\n\n override fun equals(other: Any?) = other is IpAddress && other.hostname == hostname && other.address == address\n\n override fun hashCode() = (31 * hostname.hashCode()) + address.hashCode()\n\n override fun toString() = \"$hostname/${address.hostAddress}\"\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":168,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?) = other is IpAddress && other.hostname == hostname && other.address == address"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":170,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode() = (31 * hostname.hashCode()) + address.hashCode()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":172,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"$hostname/${address.hostAddress}\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":192,"symbol":"ServiceMetadata","kind":"class","lang":"kotlin","doc":"simulate a 307 redirect to the equivalent `https://` URL. From RFC 9460, part 9.5: If an HTTPS RR query for this \"https\" URL re RRs or any compatible ServiceMode HTTPS RRs, the client SHOULD behave as if it has received an HTTP 307 (Temporary Redirect) status code with this \"https\" URL in the \"Location\" field.","code":"class ServiceMetadata(\n hostname: String,\n /**\n * The protocols supported by this server. When an input URL's hostname is served by multiple\n * servers, use this to select a server that supports the client's available protocols.\n *\n * This value is created by composing two service params. For the \"http\" protocol, this takes\n * the `HTTPS` record's `alpn` value and then add the default [Protocol.HTTP_1_1] unless\n * `no-default-alpn` is present.\n *\n * If the service returns an unrecognized [Protocol], that element is discarded.\n */\n alpnIds: List? = null,\n /**\n * The socket should connect to this port, even if the URL has a different port. This will be\n * [Request.port] unless an override is specified.\n */\n port: Int = -1,\n /**\n * The IP of the servers known to support this record. If empty, assume all records with the\n * same [hostname] also support this configuration.\n */\n ipAddressHints: List = listOf(),\n /**\n * The Encrypted Client Hello (ECH) data. This is encoded according to RFC 9848 and RFC 9849.\n */\n @get:Jv"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":240,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other is ServiceMetadata &&\n other.hostname == hostname &&\n other.alpnIds == alpnIds &&\n other.port == port &&\n other.ipAddressHints == ipAddressHints &&\n other.echConfigList == echConfigList"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":248,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int {\n var result = 17\n result = 31 * result + hostname.hashCode()\n result = 31 * result + alpnIds.hashCode()\n result = 31 * result + port\n result = 31 * result + ipAddressHints.hashCode()\n result = 31 * result + echConfigList.hashCode()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":258,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n buildString(32) {\n append(\"ServiceMetadata{\")\n append(hostname)\n if (alpnIds != null) {\n append(\", alpnIds=\")\n append(alpnIds)\n }\n if (port != 443) {\n append(\", port=\")\n append(port)\n }\n if (ipAddressHints.isNotEmpty()) {\n append(\", ipAddressHints=[\")\n append(ipAddressHints.joinToString { it.hostAddress })\n append(\"]\")\n }\n if (echConfigList != null) {\n append(\", echConfigList=\")\n append(echConfigList.hex())\n }\n append(\"}\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":293,"symbol":"lookup","kind":"function","lang":"kotlin","code":"override fun lookup(hostname: String) = Platform.get().systemDns.lookup(hostname)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":295,"symbol":"newCall","kind":"function","lang":"kotlin","code":"override fun newCall(request: Request) = Platform.get().systemDns.newCall(request)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Dns.kt","line":297,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"Dns.SYSTEM\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/DnsCache.kt","line":76,"symbol":"DnsCache","kind":"class","lang":"kotlin","doc":"types `A` (IPv4), `AAAA` (IPv6), and `HTTPS` (service metadata). Between evictions, the cache may grow to double this configured limit. Each entry consumes about 400 bytes of memory. In total, the default cache will use about 800 KiB of memory when it is full.","code":"class DnsCache internal constructor(\n @OkHttpInternalApi\n @JvmField\n internal val `-delegate`: RealDnsCache,\n) {\n @get:JvmName(\"minimumTimeToLive\")\n val minimumTimeToLive: Duration\n get() = `-delegate`.minimumTimeToLive\n\n @get:JvmName(\"maximumTimeToLive\")\n val maximumTimeToLive: Duration\n get() = `-delegate`.maximumTimeToLive\n\n @get:JvmName(\"failureTimeToLive\")\n val failureTimeToLive: Duration\n get() = `-delegate`.failureTimeToLive\n\n @get:JvmName(\"revalidateBeforeExpire\")\n val revalidateBeforeExpire: Duration\n get() = `-delegate`.revalidateBeforeExpire\n\n @get:JvmName(\"maxSize\")\n val maxSize: Int\n get() = `-delegate`.maxSize\n\n @get:JvmName(\"size\")\n val size: Int\n get() = `-delegate`.size\n\n /** Returns the number of calls made to the DNS server. */\n @get:JvmName(\"networkCount\")\n val networkCount: Int\n get() = `-delegate`.networkCount\n\n /** Returns the number of DNS calls served by the cache. */\n @get:JvmName(\"hitCount\")\n val hitCount: Int\n get() = `-delegate`.hitCount\n\n /**\n * Returns the total number of DNS calls handled by this cache. This may be greater than the\n * sum of [networkCount] and [hitCount] because revalidation calls do "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/DnsCache.kt","line":146,"symbol":"evictAll","kind":"function","lang":"kotlin","doc":"Deletes all values stored in the cache. In-flight writes to the cache will complete normally, but the corresponding responses will not be stored.","code":"fun evictAll() {\n `-delegate`.evictAll()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":63,"symbol":"EventListener","kind":"class","lang":"kotlin","doc":"Events and sequences of events may be repeated for retries and follow-ups. All event methods must execute fast, without external locking, cannot throw exceptions, attempt to mutate the event parameters, or be re-entrant back into the client. Any IO - writing to files or network should be done asynchronously.","code":"abstract class EventListener {\n /**\n * Invoked as soon as a call is enqueued or executed by a client. In case of thread or stream\n * limits, this call may be executed well before processing the request is able to begin.\n *\n * This will be invoked only once for a single [Call]. Retries of different routes or redirects\n * will be handled within the boundaries of a single [callStart] and [callEnd]/[callFailed] pair.\n */\n open fun callStart(call: Call) {\n }\n\n /**\n * Invoked for calls that were not executed immediately because resources weren't available. The\n * call will remain in the queue until resources are available.\n *\n * Use [Dispatcher.maxRequests] and [Dispatcher.maxRequestsPerHost] to configure how many calls\n * OkHttp performs concurrently.\n */\n open fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n }\n\n /**\n * Invoked when [call] will be executed immediately.\n *\n * This method is invoked after [dispatcherQueueStart].\n */\n open fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n }\n\n /**\n * Invoked prior to a proxy selection.\n *\n * This will be invoked for route selection regardles"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":71,"symbol":"callStart","kind":"function","lang":"kotlin","doc":"Invoked as soon as a call is enqueued or executed by a client. In case of thread or stream limits, this call may be executed well before processing the request is able to begin. This will be invoked only once for a single [Call]. Retries of different routes or redirects will be handled within the boundaries of a single [callStart] and [callEnd]/[callFailed] pair.","code":"open fun callStart(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":81,"symbol":"dispatcherQueueStart","kind":"function","lang":"kotlin","doc":"Invoked for calls that were not executed immediately because resources weren't available. The call will remain in the queue until resources are available. Use [Dispatcher.maxRequests] and [Dispatcher.maxRequestsPerHost] to configure how many calls OkHttp performs concurrently.","code":"open fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":92,"symbol":"dispatcherQueueEnd","kind":"function","lang":"kotlin","doc":"Invoked when [call] will be executed immediately. This method is invoked after [dispatcherQueueStart].","code":"open fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":106,"symbol":"proxySelectStart","kind":"function","lang":"kotlin","doc":"This will be invoked for route selection regardless of whether the client is configured with a single proxy, a proxy selector, or neither. @param url a URL with only the scheme, hostname, and port specified.","code":"open fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":127,"symbol":"proxySelectEnd","kind":"function","lang":"kotlin","doc":"* If the proxy selector returns an empty list or null. Otherwise it lists the proxies in the order they will be attempted. @param url a URL with only the scheme, hostname, and port specified.","code":"open fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List<@JvmSuppressWildcards Proxy>,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":143,"symbol":"dnsStart","kind":"function","lang":"kotlin","doc":"This can be invoked more than 1 time for a single [Call]. For example, if the response to the [Call.request] is a redirect to a different host. If the [Call] is able to reuse an existing pooled connection, this method will not be invoked. See [ConnectionPool].","code":"open fun dnsStart(\n call: Call,\n domainName: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":154,"symbol":"dnsEnd","kind":"function","lang":"kotlin","doc":"Invoked immediately after a DNS lookup. This method is invoked after [dnsStart].","code":"open fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List<@JvmSuppressWildcards InetAddress>,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":169,"symbol":"connectStart","kind":"function","lang":"kotlin","doc":"This method will be invoked if no existing connection in the [ConnectionPool] can be reused. This can be invoked more than 1 time for a single [Call]. For example, if the response to the [Call.request] is a redirect to a different address, or a connection is retried.","code":"open fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":188,"symbol":"secureConnectStart","kind":"function","lang":"kotlin","doc":"* No existing connection from the [ConnectionPool] can be reused. This can be invoked more than 1 time for a single [Call]. For example, if the response to the [Call.request] is a redirect to a different address, or a connection is retried.","code":"open fun secureConnectStart(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":196,"symbol":"secureConnectEnd","kind":"function","lang":"kotlin","doc":"Invoked immediately after a TLS connection was attempted. This method is invoked after [secureConnectStart].","code":"open fun secureConnectEnd(\n call: Call,\n handshake: Handshake?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":208,"symbol":"connectEnd","kind":"function","lang":"kotlin","doc":"Invoked immediately after a socket connection was attempted. If the `call` uses HTTPS, this will be invoked after [secureConnectEnd], otherwise it will invoked after [connectStart].","code":"open fun connectEnd(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":223,"symbol":"connectFailed","kind":"function","lang":"kotlin","doc":"Invoked when a connection attempt fails. This failure is not terminal if further routes are available and failure recovery is enabled. If the `call` uses HTTPS, this will be invoked after [secureConnectStart], otherwise it will invoked after [connectStart].","code":"open fun connectFailed(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ioe: IOException,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":238,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","doc":"Invoked after a connection has been acquired for the `call`. This can be invoked more than 1 time for a single [Call]. For example, if the response to the [Call.request] is a redirect to a different address.","code":"open fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":252,"symbol":"connectionReleased","kind":"function","lang":"kotlin","doc":"This method is always invoked after [connectionAcquired]. This can be invoked more than 1 time for a single [Call]. For example, if the response to the [Call.request] is a redirect to a different address.","code":"open fun connectionReleased(\n call: Call,\n connection: Connection,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":266,"symbol":"requestHeadersStart","kind":"function","lang":"kotlin","doc":"The connection is implicit, and will generally relate to the last [connectionAcquired] event. This can be invoked more than 1 time for a single [Call]. For example, if the response to the [Call.request] is a redirect to a different address.","code":"open fun requestHeadersStart(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":277,"symbol":"requestHeadersEnd","kind":"function","lang":"kotlin","doc":"This method is always invoked after [requestHeadersStart]. @param request the request sent over the network. It is an error to access the body of this request.","code":"open fun requestHeadersEnd(\n call: Call,\n request: Request,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":292,"symbol":"requestBodyStart","kind":"function","lang":"kotlin","doc":"The connection is implicit, and will generally relate to the last [connectionAcquired] event. This can be invoked more than 1 time for a single [Call]. For example, if the response to the [Call.request] is a redirect to a different address.","code":"open fun requestBodyStart(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":300,"symbol":"requestBodyEnd","kind":"function","lang":"kotlin","doc":"Invoked immediately after sending a request body. This method is always invoked after [requestBodyStart].","code":"open fun requestBodyEnd(\n call: Call,\n byteCount: Long,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":312,"symbol":"requestFailed","kind":"function","lang":"kotlin","doc":"Invoked when a request fails to be written. This method is invoked after [requestHeadersStart] or [requestBodyStart]. Note that request failures do not necessarily fail the entire call.","code":"open fun requestFailed(\n call: Call,\n ioe: IOException,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":329,"symbol":"responseHeadersStart","kind":"function","lang":"kotlin","doc":"This can be invoked more than 1 time for a single [Call]. For example, if the response to the [Call.request] is a redirect to a different address. Prior to OkHttp 4.3 this was incorrectly invoked when the client was ready to read headers. This was misleading for tracing because it was too early.","code":"open fun responseHeadersStart(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":340,"symbol":"responseHeadersEnd","kind":"function","lang":"kotlin","doc":"This method is always invoked after [responseHeadersStart]. @param response the response received over the network. It is an error to access the body of this response.","code":"open fun responseHeadersEnd(\n call: Call,\n response: Response,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":363,"symbol":"responseBodyStart","kind":"function","lang":"kotlin","doc":"This will usually be invoked only 1 time for a single [Call], exceptions are a limited set of cases including failure recovery. Prior to OkHttp 4.3 this was incorrectly invoked when the client was ready to read the response body. This was misleading for tracing because it was too early.","code":"open fun responseBodyStart(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":378,"symbol":"responseBodyEnd","kind":"function","lang":"kotlin","doc":"If the response body is closed before the response body is exhausted, this is invoked at the time it is closed. In such calls [byteCount] is the number of bytes returned to the application. This may be smaller than the resource's byte count if were read to completion. This method is always invoked after [responseBodyStart].","code":"open fun responseBodyEnd(\n call: Call,\n byteCount: Long,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":393,"symbol":"responseFailed","kind":"function","lang":"kotlin","doc":"Note that response failures do not necessarily fail the entire call. Starting with OkHttp 4.3 this may be invoked without a prior call to [responseHeadersStart] or [responseBodyStart]. In earlier releases this method was documented to only be invoked after one of those methods.","code":"open fun responseFailed(\n call: Call,\n ioe: IOException,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":405,"symbol":"callEnd","kind":"function","lang":"kotlin","doc":"Invoked immediately after a call has completely ended. This includes delayed consumption of response body by the caller. This method is always invoked after [callStart].","code":"open fun callEnd(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":413,"symbol":"callFailed","kind":"function","lang":"kotlin","doc":"Invoked when a call fails permanently. This method is always invoked after [callStart].","code":"open fun callFailed(\n call: Call,\n ioe: IOException,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":435,"symbol":"canceled","kind":"function","lang":"kotlin","doc":"occur after a call is canceled. Typically cancellation takes effect when an expensive I/O operation is required. This is invoked at most once, even if [Call.cancel] is invoked multiple times. It may be invoked at any point in a call's life, including before [callStart] and after [callEnd].","code":"open fun canceled(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":442,"symbol":"satisfactionFailure","kind":"function","lang":"kotlin","doc":"Invoked when a call fails due to cache rules. For example, we're forbidden from using the network and the cache is insufficient","code":"open fun satisfactionFailure(\n call: Call,\n response: Response,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":454,"symbol":"cacheHit","kind":"function","lang":"kotlin","doc":"Invoked when a result is served from the cache. The Response provided is the top level Response and normal event sequences will not be received. This event will only be received when a Cache is configured for the client.","code":"open fun cacheHit(\n call: Call,\n response: Response,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":466,"symbol":"cacheMiss","kind":"function","lang":"kotlin","doc":"Invoked when a response will be served from the network. The Response will be available from normal event sequences. This event will only be received when a Cache is configured for the client.","code":"open fun cacheMiss(call: Call) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":476,"symbol":"cacheConditionalHit","kind":"function","lang":"kotlin","doc":"Invoked when a response will be served from the cache or network based on validating the cached Response freshness. Will be followed by cacheHit or cacheMiss after the network Response is available. This event will only be received when a Cache is configured for the client.","code":"open fun cacheConditionalHit(\n call: Call,\n cachedResponse: Response,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":503,"symbol":"retryDecision","kind":"function","lang":"kotlin","doc":"Each call is made on either a reused [Connection] from a pool, or on a new connection established from a planned [Route]. OkHttp won't retry if it's already attempted all available routes. @param retry true if OkHttp will make another attempt","code":"open fun retryDecision(\n call: Call,\n exception: IOException,\n retry: Boolean,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":531,"symbol":"followUpDecision","kind":"function","lang":"kotlin","doc":"* [OkHttpClient.followSslRedirects] must be true to follow redirects that add or remove HTTPS. * [OkHttpClient.authenticator] must respond to an authorization challenge. @param networkResponse the intermediate response that may require a follow-up request. @param nextRequest the follow-up request that will be made. Null if no follow-up will be made.","code":"open fun followUpDecision(\n call: Call,\n networkResponse: Response,\n nextRequest: Request?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":539,"symbol":"plus","kind":"function","lang":"kotlin","doc":"Returns a new `EventListener` that publishes events to this and then `other`.","code":"operator fun plus(other: EventListener): EventListener {\n val left =\n when {\n this === NONE -> return other\n this is AggregateEventListener -> this.eventListeners\n else -> arrayOf(this)\n }\n val right =\n when {\n other === NONE -> return this\n other is AggregateEventListener -> other.eventListeners\n else -> arrayOf(other)\n }\n\n return AggregateEventListener(left + right)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":556,"symbol":"Factory","kind":"interface","lang":"kotlin","code":"fun interface Factory {\n /**\n * Creates an instance of the [EventListener] for a particular [Call]. The returned\n * [EventListener] instance will be used during the lifecycle of [call].\n *\n * This method is invoked after [call] is created. See [OkHttpClient.newCall].\n *\n * **It is an error for implementations to issue any mutating operations on the [call] instance\n * from this method.**\n */\n fun create(call: Call): EventListener\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":566,"symbol":"create","kind":"function","lang":"kotlin","doc":"This method is invoked after [call] is created. See [OkHttpClient.newCall]. **It is an error for implementations to issue any mutating operations on the [call] instance from this method.**","code":"fun create(call: Call): EventListener"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":576,"symbol":"AggregateEventListener","kind":"class","lang":"kotlin","code":"private class AggregateEventListener(\n val eventListeners: Array,\n ) : EventListener() {\n override fun callStart(call: Call) {\n for (delegate in eventListeners) {\n delegate.callStart(call)\n }\n }\n\n override fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n for (delegate in eventListeners) {\n delegate.dispatcherQueueStart(call, dispatcher)\n }\n }\n\n override fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n for (delegate in eventListeners) {\n delegate.dispatcherQueueEnd(call, dispatcher)\n }\n }\n\n override fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) {\n for (delegate in eventListeners) {\n delegate.proxySelectStart(call, url)\n }\n }\n\n override fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List<@JvmSuppressWildcards Proxy>,\n ) {\n for (delegate in eventListeners) {\n delegate.proxySelectEnd(call, url, proxies)\n }\n }\n\n override fun dnsStart(\n call: Call,\n domainName: String,\n ) {\n for (delegate in eventListeners) {\n deleg"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":579,"symbol":"callStart","kind":"function","lang":"kotlin","code":"override fun callStart(call: Call) {\n for (delegate in eventListeners) {\n delegate.callStart(call)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":585,"symbol":"dispatcherQueueStart","kind":"function","lang":"kotlin","code":"override fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n for (delegate in eventListeners) {\n delegate.dispatcherQueueStart(call, dispatcher)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":594,"symbol":"dispatcherQueueEnd","kind":"function","lang":"kotlin","code":"override fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n for (delegate in eventListeners) {\n delegate.dispatcherQueueEnd(call, dispatcher)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":603,"symbol":"proxySelectStart","kind":"function","lang":"kotlin","code":"override fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) {\n for (delegate in eventListeners) {\n delegate.proxySelectStart(call, url)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":612,"symbol":"proxySelectEnd","kind":"function","lang":"kotlin","code":"override fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List<@JvmSuppressWildcards Proxy>,\n ) {\n for (delegate in eventListeners) {\n delegate.proxySelectEnd(call, url, proxies)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":622,"symbol":"dnsStart","kind":"function","lang":"kotlin","code":"override fun dnsStart(\n call: Call,\n domainName: String,\n ) {\n for (delegate in eventListeners) {\n delegate.dnsStart(call, domainName)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":631,"symbol":"dnsEnd","kind":"function","lang":"kotlin","code":"override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List<@JvmSuppressWildcards InetAddress>,\n ) {\n for (delegate in eventListeners) {\n delegate.dnsEnd(call, domainName, inetAddressList)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":641,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n for (delegate in eventListeners) {\n delegate.connectStart(call, inetSocketAddress, proxy)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":651,"symbol":"secureConnectStart","kind":"function","lang":"kotlin","code":"override fun secureConnectStart(call: Call) {\n for (delegate in eventListeners) {\n delegate.secureConnectStart(call)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":657,"symbol":"secureConnectEnd","kind":"function","lang":"kotlin","code":"override fun secureConnectEnd(\n call: Call,\n handshake: Handshake?,\n ) {\n for (delegate in eventListeners) {\n delegate.secureConnectEnd(call, handshake)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":666,"symbol":"connectEnd","kind":"function","lang":"kotlin","code":"override fun connectEnd(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ) {\n for (delegate in eventListeners) {\n delegate.connectEnd(call, inetSocketAddress, proxy, protocol)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":677,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ioe: IOException,\n ) {\n for (delegate in eventListeners) {\n delegate.connectFailed(call, inetSocketAddress, proxy, protocol, ioe)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":689,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n for (delegate in eventListeners) {\n delegate.connectionAcquired(call, connection)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":698,"symbol":"connectionReleased","kind":"function","lang":"kotlin","code":"override fun connectionReleased(\n call: Call,\n connection: Connection,\n ) {\n for (delegate in eventListeners) {\n delegate.connectionReleased(call, connection)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":707,"symbol":"requestHeadersStart","kind":"function","lang":"kotlin","code":"override fun requestHeadersStart(call: Call) {\n for (delegate in eventListeners) {\n delegate.requestHeadersStart(call)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":713,"symbol":"requestHeadersEnd","kind":"function","lang":"kotlin","code":"override fun requestHeadersEnd(\n call: Call,\n request: Request,\n ) {\n for (delegate in eventListeners) {\n delegate.requestHeadersEnd(call, request)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":722,"symbol":"requestBodyStart","kind":"function","lang":"kotlin","code":"override fun requestBodyStart(call: Call) {\n for (delegate in eventListeners) {\n delegate.requestBodyStart(call)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":728,"symbol":"requestBodyEnd","kind":"function","lang":"kotlin","code":"override fun requestBodyEnd(\n call: Call,\n byteCount: Long,\n ) {\n for (delegate in eventListeners) {\n delegate.requestBodyEnd(call, byteCount)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":737,"symbol":"requestFailed","kind":"function","lang":"kotlin","code":"override fun requestFailed(\n call: Call,\n ioe: IOException,\n ) {\n for (delegate in eventListeners) {\n delegate.requestFailed(call, ioe)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":746,"symbol":"responseHeadersStart","kind":"function","lang":"kotlin","code":"override fun responseHeadersStart(call: Call) {\n for (delegate in eventListeners) {\n delegate.responseHeadersStart(call)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":752,"symbol":"responseHeadersEnd","kind":"function","lang":"kotlin","code":"override fun responseHeadersEnd(\n call: Call,\n response: Response,\n ) {\n for (delegate in eventListeners) {\n delegate.responseHeadersEnd(call, response)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/EventListener.kt","line":761,"symbol":"responseBodyStart","kind":"function","lang":"kotlin","code":"override fun responseBodyStart(call: Call) {\n for (delegate in eventListeners) {\n delegate.responseBodyStart(call)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":28,"symbol":"FormBody","kind":"class","lang":"kotlin","code":"class FormBody internal constructor(\n encodedNames: List,\n encodedValues: List,\n) : RequestBody() {\n private val encodedNames: List = encodedNames.toImmutableList()\n private val encodedValues: List = encodedValues.toImmutableList()\n\n /** The number of key-value pairs in this form-encoded body. */\n @get:JvmName(\"size\")\n val size: Int\n get() = encodedNames.size\n\n @JvmName(\"-deprecated_size\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"size\"),\n level = DeprecationLevel.ERROR,\n )\n fun size(): Int = size\n\n fun encodedName(index: Int): String = encodedNames[index]\n\n fun name(index: Int): String = encodedName(index).percentDecode(plusIsSpace = true)\n\n fun encodedValue(index: Int): String = encodedValues[index]\n\n fun value(index: Int): String = encodedValue(index).percentDecode(plusIsSpace = true)\n\n override fun contentType(): MediaType = CONTENT_TYPE\n\n override fun contentLength(): Long = writeOrCountBytes(null, true)\n\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n writeOrCountBytes(sink, false)\n }\n\n /**\n * Either writes this request to [sink] or measures "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":40,"symbol":"size","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_size\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"size\"),\n level = DeprecationLevel.ERROR,\n )\n fun size(): Int = size"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":48,"symbol":"encodedName","kind":"function","lang":"kotlin","code":"fun encodedName(index: Int): String = encodedNames[index]"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":50,"symbol":"name","kind":"function","lang":"kotlin","code":"fun name(index: Int): String = encodedName(index).percentDecode(plusIsSpace = true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":52,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"fun encodedValue(index: Int): String = encodedValues[index]"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":54,"symbol":"value","kind":"function","lang":"kotlin","code":"fun value(index: Int): String = encodedValue(index).percentDecode(plusIsSpace = true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":56,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType = CONTENT_TYPE"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":58,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = writeOrCountBytes(null, true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":60,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n writeOrCountBytes(sink, false)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":71,"symbol":"writeOrCountBytes","kind":"function","lang":"kotlin","doc":"Either writes this request to [sink] or measures its content length. We have one method do double-duty to make sure the counting and content are consistent, particularly when it comes to awkward operations like measuring the encoded length of header strings, or the length-in-digits of an encoded integer.","code":"private fun writeOrCountBytes(\n sink: BufferedSink?,\n countBytes: Boolean,\n ): Long {\n var byteCount = 0L\n val buffer: Buffer = if (countBytes) Buffer() else sink!!.buffer\n\n for (i in 0 until encodedNames.size) {\n if (i > 0) buffer.writeByte('&'.code)\n buffer.writeUtf8(encodedNames[i])\n buffer.writeByte('='.code)\n buffer.writeUtf8(encodedValues[i])\n }\n\n if (countBytes) {\n byteCount = buffer.size\n buffer.clear()\n }\n\n return byteCount\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":101,"symbol":"add","kind":"function","lang":"kotlin","code":"fun add(\n name: String,\n value: String,\n ) = apply {\n names +=\n name.canonicalizeWithCharset(\n encodeSet = FORM_ENCODE_SET,\n // Plus is encoded as `%2B`, space is encoded as plus.\n plusIsSpace = false,\n charset = charset,\n )\n values +=\n value.canonicalizeWithCharset(\n encodeSet = FORM_ENCODE_SET,\n // Plus is encoded as `%2B`, space is encoded as plus.\n plusIsSpace = false,\n charset = charset,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":121,"symbol":"addEncoded","kind":"function","lang":"kotlin","code":"fun addEncoded(\n name: String,\n value: String,\n ) = apply {\n names +=\n name.canonicalizeWithCharset(\n encodeSet = FORM_ENCODE_SET,\n alreadyEncoded = true,\n plusIsSpace = true,\n charset = charset,\n )\n values +=\n value.canonicalizeWithCharset(\n encodeSet = FORM_ENCODE_SET,\n alreadyEncoded = true,\n plusIsSpace = true,\n charset = charset,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/FormBody.kt","line":141,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): FormBody = FormBody(names, values)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Gzip.kt","line":23,"symbol":"Gzip","kind":"object","lang":"kotlin","code":"object Gzip : DecompressionAlgorithm {\n override val encoding: String get() = \"gzip\"\n\n override fun decompress(compressedSource: BufferedSource): Source = GzipSource(compressedSource)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Gzip.kt","line":26,"symbol":"decompress","kind":"function","lang":"kotlin","code":"override fun decompress(compressedSource: BufferedSource): Source = GzipSource(compressedSource)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":33,"symbol":"Handshake","kind":"class","lang":"kotlin","doc":"A record of a TLS handshake. For HTTPS clients, the client is *local* and the remote server is its *peer*. This value object describes a completed handshake. Use [ConnectionSpec] to set policy for new handshakes.","code":"class Handshake internal constructor(\n /**\n * Returns the TLS version used for this connection. This value wasn't tracked prior to OkHttp\n * 3.0. For responses cached by preceding versions this returns [TlsVersion.SSL_3_0].\n */\n @get:JvmName(\"tlsVersion\") val tlsVersion: TlsVersion,\n /** Returns the cipher suite used for the connection. */\n @get:JvmName(\"cipherSuite\") val cipherSuite: CipherSuite,\n /** Returns a possibly-empty list of certificates that identify this peer. */\n @get:JvmName(\"localCertificates\") val localCertificates: List,\n // Delayed provider of peerCertificates, to allow lazy cleaning.\n peerCertificatesFn: () -> List,\n) {\n /** Returns a possibly-empty list of certificates that identify the remote peer. */\n @get:JvmName(\"peerCertificates\")\n val peerCertificates: List by lazy {\n try {\n peerCertificatesFn()\n } catch (spue: SSLPeerUnverifiedException) {\n listOf()\n }\n }\n\n @JvmName(\"-deprecated_tlsVersion\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"tlsVersion\"),\n level = DeprecationLevel.ERROR,\n )\n fun tlsVersion(): TlsVersion = tlsVersion\n\n @"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":56,"symbol":"tlsVersion","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_tlsVersion\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"tlsVersion\"),\n level = DeprecationLevel.ERROR,\n )\n fun tlsVersion(): TlsVersion = tlsVersion"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":64,"symbol":"cipherSuite","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_cipherSuite\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"cipherSuite\"),\n level = DeprecationLevel.ERROR,\n )\n fun cipherSuite(): CipherSuite = cipherSuite"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":72,"symbol":"peerCertificates","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_peerCertificates\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"peerCertificates\"),\n level = DeprecationLevel.ERROR,\n )\n fun peerCertificates(): List = peerCertificates"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":85,"symbol":"peerPrincipal","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_peerPrincipal\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"peerPrincipal\"),\n level = DeprecationLevel.ERROR,\n )\n fun peerPrincipal(): Principal? = peerPrincipal"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":93,"symbol":"localCertificates","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_localCertificates\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"localCertificates\"),\n level = DeprecationLevel.ERROR,\n )\n fun localCertificates(): List = localCertificates"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":106,"symbol":"localPrincipal","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_localPrincipal\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"localPrincipal\"),\n level = DeprecationLevel.ERROR,\n )\n fun localPrincipal(): Principal? = localPrincipal"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":114,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other is Handshake &&\n other.tlsVersion == tlsVersion &&\n other.cipherSuite == cipherSuite &&\n other.peerCertificates == peerCertificates &&\n other.localCertificates == localCertificates"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":121,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int {\n var result = 17\n result = 31 * result + tlsVersion.hashCode()\n result = 31 * result + cipherSuite.hashCode()\n result = 31 * result + peerCertificates.hashCode()\n result = 31 * result + localCertificates.hashCode()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":130,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String {\n val peerCertificatesString = peerCertificates.map { it.name }.toString()\n return \"Handshake{\" +\n \"tlsVersion=$tlsVersion \" +\n \"cipherSuite=$cipherSuite \" +\n \"peerCertificates=$peerCertificatesString \" +\n \"localCertificates=${localCertificates.map { it.name }}}\"\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":147,"symbol":"handshake","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n @JvmStatic\n @JvmName(\"get\")\n fun SSLSession.handshake(): Handshake {\n val cipherSuite =\n when (val cipherSuiteString = checkNotNull(cipherSuite) { \"cipherSuite == null\" }) {\n \"TLS_NULL_WITH_NULL_NULL\", \"SSL_NULL_WITH_NULL_NULL\" -> {\n throw IOException(\"cipherSuite == $cipherSuiteString\")\n }\n\n else -> {\n CipherSuite.forJavaName(cipherSuiteString)\n }\n }\n\n val tlsVersionString = checkNotNull(protocol) { \"tlsVersion == null\" }\n if (\"NONE\" == tlsVersionString) throw IOException(\"tlsVersion == NONE\")\n val tlsVersion = TlsVersion.forJavaName(tlsVersionString)\n\n val peerCertificatesCopy =\n try {\n peerCertificates.toImmutableList()\n } catch (_: SSLPeerUnverifiedException) {\n listOf()\n }\n\n return Handshake(\n tlsVersion,\n cipherSuite,\n localCertificates.toImmutableList(),\n ) { peerCertificatesCopy }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":180,"symbol":"get","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n @JvmName(\"-deprecated_get\")\n @Deprecated(\n message = \"moved to extension function\",\n replaceWith = ReplaceWith(expression = \"sslSession.handshake()\"),\n level = DeprecationLevel.ERROR,\n )\n fun get(sslSession: SSLSession) = sslSession.handshake()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Handshake.kt","line":189,"symbol":"get","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun get(\n tlsVersion: TlsVersion,\n cipherSuite: CipherSuite,\n peerCertificates: List,\n localCertificates: List,\n ): Handshake {\n val peerCertificatesCopy = peerCertificates.toImmutableList()\n return Handshake(tlsVersion, cipherSuite, localCertificates.toImmutableList()) {\n peerCertificatesCopy\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":65,"symbol":"Headers","kind":"class","lang":"kotlin","doc":"This class trims whitespace from values. It never returns values with leading or trailing whitespace. Instances of this class are immutable. Use [Builder] to create instances.","code":"@Suppress(\"NAME_SHADOWING\")\nclass Headers internal constructor(\n internal val namesAndValues: Array,\n) : Iterable> {\n /** Returns the last value corresponding to the specified field, or null. */\n operator fun get(name: String): String? = commonHeadersGet(namesAndValues, name)\n\n /**\n * Returns the last value corresponding to the specified field parsed as an HTTP date, or null if\n * either the field is absent or cannot be parsed as a date.\n */\n fun getDate(name: String): Date? = get(name)?.toHttpDateOrNull()\n\n /**\n * Returns the last value corresponding to the specified field parsed as an HTTP date, or null if\n * either the field is absent or cannot be parsed as a date.\n */\n @Suppress(\"NewApi\")\n @IgnoreJRERequirement // Only programs that already have Instant will use this.\n fun getInstant(name: String): Instant? = getDate(name)?.toInstant()\n\n /** Returns the number of field values. */\n @get:JvmName(\"size\")\n val size: Int\n get() = namesAndValues.size / 2\n\n @JvmName(\"-deprecated_size\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"size\"),\n level = DeprecationLevel.ERROR,\n )\n fun si"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":70,"symbol":"get","kind":"function","lang":"kotlin","doc":"Returns the last value corresponding to the specified field, or null.","code":"operator fun get(name: String): String? = commonHeadersGet(namesAndValues, name)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":76,"symbol":"getDate","kind":"function","lang":"kotlin","doc":"Returns the last value corresponding to the specified field parsed as an HTTP date, or null if either the field is absent or cannot be parsed as a date.","code":"fun getDate(name: String): Date? = get(name)?.toHttpDateOrNull()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":82,"symbol":"getInstant","kind":"function","lang":"kotlin","doc":"Returns the last value corresponding to the specified field parsed as an HTTP date, or null if either the field is absent or cannot be parsed as a date.","code":"@Suppress(\"NewApi\")\n @IgnoreJRERequirement // Only programs that already have Instant will use this.\n fun getInstant(name: String): Instant? = getDate(name)?.toInstant()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":91,"symbol":"size","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_size\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"size\"),\n level = DeprecationLevel.ERROR,\n )\n fun size(): Int = size"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":100,"symbol":"name","kind":"function","lang":"kotlin","doc":"Returns the field at `position`.","code":"fun name(index: Int): String = commonName(index)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":103,"symbol":"value","kind":"function","lang":"kotlin","doc":"Returns the value at `index`.","code":"fun value(index: Int): String = commonValue(index)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":106,"symbol":"names","kind":"function","lang":"kotlin","doc":"Returns an immutable case-insensitive set of header names.","code":"fun names(): Set {\n val result = TreeSet(String.CASE_INSENSITIVE_ORDER)\n for (i in 0 until size) {\n result.add(name(i))\n }\n return result.unmodifiable()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":115,"symbol":"values","kind":"function","lang":"kotlin","doc":"Returns an immutable list of the header values for `name`.","code":"fun values(name: String): List = commonValues(name)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":122,"symbol":"byteCount","kind":"function","lang":"kotlin","doc":"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.","code":"fun byteCount(): Long {\n // Each header name has 2 bytes of overhead for ': ' and every header value has 2 bytes of\n // overhead for '\\r\\n'.\n var result = (namesAndValues.size * 2).toLong()\n\n for (i in 0 until namesAndValues.size) {\n result += namesAndValues[i].length.toLong()\n }\n\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":134,"symbol":"iterator","kind":"function","lang":"kotlin","code":"override operator fun iterator(): Iterator> = commonIterator()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":136,"symbol":"newBuilder","kind":"function","lang":"kotlin","code":"fun newBuilder(): Builder = commonNewBuilder()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":174,"symbol":"equals","kind":"function","lang":"kotlin","doc":"Content-Length: 050 ``` Applications that require semantically equal headers should convert them into a canonical form before comparing them for equality.","code":"override fun equals(other: Any?): Boolean = commonEquals(other)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":176,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int = commonHashCode()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":189,"symbol":"toString","kind":"function","lang":"kotlin","doc":"* `Authorization` * `Cookie` * `Proxy-Authorization` * `Set-Cookie`","code":"override fun toString(): String = commonToString()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":191,"symbol":"toMultimap","kind":"function","lang":"kotlin","code":"fun toMultimap(): Map> {\n val result = TreeMap>(String.CASE_INSENSITIVE_ORDER)\n for (i in 0 until size) {\n val name = name(i).lowercase(Locale.US)\n var values: MutableList? = result[name]\n if (values == null) {\n values = ArrayList(2)\n result[name] = values\n }\n values.add(value(i))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":205,"symbol":"Builder","kind":"class","lang":"kotlin","code":"class Builder {\n internal val namesAndValues: MutableList = ArrayList(20)\n\n /**\n * Add a header line without any validation. Only appropriate for headers from the remote peer\n * or cache.\n */\n internal fun addLenient(line: String) =\n apply {\n val index = line.indexOf(':', 1)\n when {\n index != -1 -> {\n addLenient(line.substring(0, index), line.substring(index + 1))\n }\n\n line[0] == ':' -> {\n // Work around empty header names and header names that start with a colon (created by old\n // broken SPDY versions of the response cache).\n addLenient(\"\", line.substring(1)) // Empty header name.\n }\n\n else -> {\n // No header name.\n addLenient(\"\", line)\n }\n }\n }\n\n /** Add an header line containing a field name, a literal colon, and a value. */\n fun add(line: String) =\n apply {\n val index = line.indexOf(':')\n require(index != -1) { \"Unexpected header: $line\" }\n add(line.substring(0, index).trim(), line.substring(index + 1))\n }\n\n /**\n * Add a header with the specified name and v"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":212,"symbol":"addLenient","kind":"function","lang":"kotlin","doc":"Add a header line without any validation. Only appropriate for headers from the remote peer or cache.","code":"internal fun addLenient(line: String) =\n apply {\n val index = line.indexOf(':', 1)\n when {\n index != -1 -> {\n addLenient(line.substring(0, index), line.substring(index + 1))\n }\n\n line[0] == ':' -> {\n // Work around empty header names and header names that start with a colon (created by old\n // broken SPDY versions of the response cache).\n addLenient(\"\", line.substring(1)) // Empty header name.\n }\n\n else -> {\n // No header name.\n addLenient(\"\", line)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":234,"symbol":"add","kind":"function","lang":"kotlin","doc":"Add an header line containing a field name, a literal colon, and a value.","code":"fun add(line: String) =\n apply {\n val index = line.indexOf(':')\n require(index != -1) { \"Unexpected header: $line\" }\n add(line.substring(0, index).trim(), line.substring(index + 1))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":244,"symbol":"add","kind":"function","lang":"kotlin","doc":"Add a header with the specified name and value. Does validation of header names and values.","code":"fun add(\n name: String,\n value: String,\n ) = commonAdd(name, value)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":253,"symbol":"addUnsafeNonAscii","kind":"function","lang":"kotlin","doc":"Add a header with the specified name and value. Does validation of header names, allowing non-ASCII values.","code":"fun addUnsafeNonAscii(\n name: String,\n value: String,\n ) = apply {\n headersCheckName(name)\n addLenient(name, value)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":264,"symbol":"addAll","kind":"function","lang":"kotlin","doc":"Adds all headers from an existing collection.","code":"fun addAll(headers: Headers) = commonAddAll(headers)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":270,"symbol":"add","kind":"function","lang":"kotlin","doc":"Add a header with the specified name and formatted date. Does validation of header names and value.","code":"fun add(\n name: String,\n value: Date,\n ) = add(name, value.toHttpDateString())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":279,"symbol":"add","kind":"function","lang":"kotlin","doc":"Add a header with the specified name and formatted instant. Does validation of header names and value.","code":"@Suppress(\"NewApi\")\n @IgnoreJRERequirement // Only programs that already have Instant will use this.\n fun add(\n name: String,\n value: Instant,\n ) = add(name, Date.from(value))"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":290,"symbol":"set","kind":"function","lang":"kotlin","doc":"Set a field with the specified date. If the field is not found, it is added. If the field is found, the existing values are replaced.","code":"operator fun set(\n name: String,\n value: Date,\n ) = set(name, value.toHttpDateString())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":299,"symbol":"set","kind":"function","lang":"kotlin","doc":"Set a field with the specified instant. If the field is not found, it is added. If the field is found, the existing values are replaced.","code":"@Suppress(\"NewApi\")\n @IgnoreJRERequirement // Only programs that already have Instant will use this.\n operator fun set(name: String, value: Instant) = set(name, Date.from(value))"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":307,"symbol":"addLenient","kind":"function","lang":"kotlin","doc":"Add a field with the specified value without any validation. Only appropriate for headers from the remote peer or cache.","code":"internal fun addLenient(\n name: String,\n value: String,\n ) = commonAddLenient(name, value)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":312,"symbol":"removeAll","kind":"function","lang":"kotlin","code":"fun removeAll(name: String) = commonRemoveAll(name)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":318,"symbol":"set","kind":"function","lang":"kotlin","doc":"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.","code":"operator fun set(\n name: String,\n value: String,\n ) = commonSet(name, value)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":324,"symbol":"get","kind":"function","lang":"kotlin","doc":"Equivalent to `build().get(name)`, but potentially faster.","code":"operator fun get(name: String): String? = commonGet(name)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":326,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): Headers = commonBuild()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":338,"symbol":"headersOf","kind":"function","lang":"kotlin","doc":"Returns headers for the alternating header names and values. There must be an even number of arguments, and they must alternate between header names and values.","code":"@JvmStatic\n @JvmName(\"of\")\n fun headersOf(vararg namesAndValues: String): Headers = commonHeadersOf(*namesAndValues)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":342,"symbol":"of","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_of\")\n @Deprecated(\n message = \"function name changed\",\n replaceWith = ReplaceWith(expression = \"headersOf(*namesAndValues)\"),\n level = DeprecationLevel.ERROR,\n )\n fun of(vararg namesAndValues: String): Headers = headersOf(*namesAndValues)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":351,"symbol":"toHeaders","kind":"function","lang":"kotlin","doc":"Returns headers for the header names and values in the [Map].","code":"@JvmStatic\n @JvmName(\"of\")\n fun Map.toHeaders(): Headers = commonToHeaders()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Headers.kt","line":355,"symbol":"of","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_of\")\n @Deprecated(\n message = \"function moved to extension\",\n replaceWith = ReplaceWith(expression = \"headers.toHeaders()\"),\n level = DeprecationLevel.ERROR,\n )\n fun of(headers: Map): Headers = headers.toHeaders()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":386,"symbol":"toUrl","kind":"function","lang":"kotlin","doc":"Returns this URL as a [java.net.URL][URL].","code":"@JvmName(\"url\")\n fun toUrl(): URL {\n try {\n return URL(url)\n } catch (e: MalformedURLException) {\n throw RuntimeException(e) // Unexpected!\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":408,"symbol":"toUri","kind":"function","lang":"kotlin","doc":"* Whitespace and control characters in the fragment will be stripped. These differences may have a significant consequence when the URI is interpreted by a web server. For this reason the [URI class][URI] and this method should be avoided.","code":"@JvmName(\"uri\")\n fun toUri(): URI {\n val uri = newBuilder().reencodeForUri().toString()\n return try {\n URI(uri)\n } catch (e: URISyntaxException) {\n // Unlikely edge case: the URI has a forbidden character in the fragment. Strip it & retry.\n try {\n val stripped = uri.replace(Regex(\"[\\\\u0000-\\\\u001F\\\\u007F-\\\\u009F\\\\p{javaWhitespace}]\"), \"\")\n URI.create(stripped)\n } catch (e1: Exception) {\n throw RuntimeException(e) // Unexpected!\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":594,"symbol":"queryParameter","kind":"function","lang":"kotlin","doc":"| `http://host/` | null | | `http://host/?` | null | | `http://host/?a=apple&k=key+lime` | `\"apple\"` | | `http://host/?a=apple&a=apricot` | `\"apple\"` | | `http://host/?a=apple&b` | `\"apple\"` |","code":"fun queryParameter(name: String): String? {\n if (queryNamesAndValues == null) return null\n for (i in 0 until queryNamesAndValues.size step 2) {\n if (name == queryNamesAndValues[i]) {\n return queryNamesAndValues[i + 1]\n }\n }\n return null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":640,"symbol":"queryParameterValues","kind":"function","lang":"kotlin","doc":"| `http://host/` | `[]` | `[]` | | `http://host/?` | `[]` | `[]` | | `http://host/?a=apple&k=key+lime` | `[\"apple\"]` | `[]` | | `http://host/?a=apple&a=apricot` | `[\"apple\", \"apricot\"]` | `[]` | | `http://host/?a=apple&b` | `[\"apple\"]` | `[null]` |","code":"fun queryParameterValues(name: String): List {\n if (queryNamesAndValues == null) return emptyList()\n val result = ArrayList(4)\n for (i in 0 until queryNamesAndValues.size step 2) {\n if (name == queryNamesAndValues[i]) {\n result.add(queryNamesAndValues[i + 1])\n }\n }\n return result.unmodifiable()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":664,"symbol":"queryParameterName","kind":"function","lang":"kotlin","doc":"| `http://host/` | exception | exception | | `http://host/?` | `\"\"` | exception | | `http://host/?a=apple&k=key+lime` | `\"a\"` | `\"k\"` | | `http://host/?a=apple&a=apricot` | `\"a\"` | `\"a\"` | | `http://host/?a=apple&b` | `\"a\"` | `\"b\"` |","code":"fun queryParameterName(index: Int): String {\n if (queryNamesAndValues == null) throw IndexOutOfBoundsException()\n return queryNamesAndValues[index * 2]!!\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":682,"symbol":"queryParameterValue","kind":"function","lang":"kotlin","doc":"| `http://host/` | exception | exception | | `http://host/?` | null | exception | | `http://host/?a=apple&k=key+lime` | `\"apple\"` | `\"key lime\"` | | `http://host/?a=apple&a=apricot` | `\"apple\"` | `\"apricot\"` | | `http://host/?a=apple&b` | `\"apple\"` | null |","code":"fun queryParameterValue(index: Int): String? {\n if (queryNamesAndValues == null) throw IndexOutOfBoundsException()\n return queryNamesAndValues[index * 2 + 1]\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":711,"symbol":"redact","kind":"function","lang":"kotlin","doc":"Returns a string with containing this URL with its username, password, query, and fragment stripped, and its path replaced with `/...`. For example, redacting `http://username:password@example.com/path` returns `http://example.com/...`.","code":"fun redact(): String =\n newBuilder(\"/...\")!!\n .username(\"\")\n .password(\"\")\n .build()\n .toString()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":722,"symbol":"resolve","kind":"function","lang":"kotlin","doc":"Returns the URL that would be retrieved by following `link` from this URL, or null if the resulting URL is not well-formed.","code":"fun resolve(link: String): HttpUrl? = newBuilder(link)?.build()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":727,"symbol":"newBuilder","kind":"function","lang":"kotlin","doc":"Returns a builder based on this URL.","code":"fun newBuilder(): Builder {\n val result = Builder()\n result.scheme = scheme\n result.encodedUsername = encodedUsername\n result.encodedPassword = encodedPassword\n result.host = host\n // If we're set to a default port, unset it in case of a scheme change.\n result.port = if (port != defaultPort(scheme)) port else -1\n result.encodedPathSegments.clear()\n result.encodedPathSegments.addAll(encodedPathSegments)\n result.encodedQuery(encodedQuery)\n result.encodedFragment = encodedFragment\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":746,"symbol":"newBuilder","kind":"function","lang":"kotlin","doc":"Returns a builder for the URL that would be retrieved by following `link` from this URL, or null if the resulting URL is not well-formed.","code":"fun newBuilder(link: String): Builder? =\n try {\n Builder().parse(this, link)\n } catch (_: IllegalArgumentException) {\n null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":753,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean = other is HttpUrl && other.url == url"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":755,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int = url.hashCode()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":757,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = url"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":776,"symbol":"topPrivateDomain","kind":"function","lang":"kotlin","doc":"| `http://adwords.google.co.uk` | `\"google.co.uk\"` | | `http://square` | null | | `http://co.uk` | null | | `http://localhost` | null | | `http://127.0.0.1` | null |","code":"fun topPrivateDomain(): String? =\n if (host.canParseAsIpAddress()) {\n null\n } else {\n PublicSuffixDatabase.get().getEffectiveTldPlusOne(host)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":783,"symbol":"url","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_url\")\n @Deprecated(\n message = \"moved to toUrl()\",\n replaceWith = ReplaceWith(expression = \"toUrl()\"),\n level = DeprecationLevel.ERROR,\n )\n fun url(): URL = toUrl()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":791,"symbol":"uri","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_uri\")\n @Deprecated(\n message = \"moved to toUri()\",\n replaceWith = ReplaceWith(expression = \"toUri()\"),\n level = DeprecationLevel.ERROR,\n )\n fun uri(): URI = toUri()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":799,"symbol":"scheme","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_scheme\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"scheme\"),\n level = DeprecationLevel.ERROR,\n )\n fun scheme(): String = scheme"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":807,"symbol":"encodedUsername","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_encodedUsername\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"encodedUsername\"),\n level = DeprecationLevel.ERROR,\n )\n fun encodedUsername(): String = encodedUsername"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":815,"symbol":"username","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_username\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"username\"),\n level = DeprecationLevel.ERROR,\n )\n fun username(): String = username"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":823,"symbol":"encodedPassword","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_encodedPassword\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"encodedPassword\"),\n level = DeprecationLevel.ERROR,\n )\n fun encodedPassword(): String = encodedPassword"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":831,"symbol":"password","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_password\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"password\"),\n level = DeprecationLevel.ERROR,\n )\n fun password(): String = password"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":839,"symbol":"host","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_host\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"host\"),\n level = DeprecationLevel.ERROR,\n )\n fun host(): String = host"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":847,"symbol":"port","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_port\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"port\"),\n level = DeprecationLevel.ERROR,\n )\n fun port(): Int = port"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":855,"symbol":"pathSize","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_pathSize\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"pathSize\"),\n level = DeprecationLevel.ERROR,\n )\n fun pathSize(): Int = pathSize"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":863,"symbol":"encodedPath","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_encodedPath\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"encodedPath\"),\n level = DeprecationLevel.ERROR,\n )\n fun encodedPath(): String = encodedPath"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":871,"symbol":"encodedPathSegments","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_encodedPathSegments\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"encodedPathSegments\"),\n level = DeprecationLevel.ERROR,\n )\n fun encodedPathSegments(): List = encodedPathSegments"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":879,"symbol":"pathSegments","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_pathSegments\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"pathSegments\"),\n level = DeprecationLevel.ERROR,\n )\n fun pathSegments(): List = pathSegments"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":887,"symbol":"encodedQuery","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_encodedQuery\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"encodedQuery\"),\n level = DeprecationLevel.ERROR,\n )\n fun encodedQuery(): String? = encodedQuery"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":895,"symbol":"query","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_query\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"query\"),\n level = DeprecationLevel.ERROR,\n )\n fun query(): String? = query"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":903,"symbol":"querySize","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_querySize\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"querySize\"),\n level = DeprecationLevel.ERROR,\n )\n fun querySize(): Int = querySize"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":911,"symbol":"queryParameterNames","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_queryParameterNames\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"queryParameterNames\"),\n level = DeprecationLevel.ERROR,\n )\n fun queryParameterNames(): Set = queryParameterNames"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":919,"symbol":"encodedFragment","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_encodedFragment\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"encodedFragment\"),\n level = DeprecationLevel.ERROR,\n )\n fun encodedFragment(): String? = encodedFragment"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":927,"symbol":"fragment","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_fragment\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"fragment\"),\n level = DeprecationLevel.ERROR,\n )\n fun fragment(): String? = fragment"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":948,"symbol":"scheme","kind":"function","lang":"kotlin","doc":"@param scheme either \"http\" or \"https\".","code":"fun scheme(scheme: String) =\n apply {\n when {\n scheme.equals(\"http\", ignoreCase = true) -> this.scheme = \"http\"\n scheme.equals(\"https\", ignoreCase = true) -> this.scheme = \"https\"\n else -> throw IllegalArgumentException(\"unexpected scheme: $scheme\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":957,"symbol":"username","kind":"function","lang":"kotlin","code":"fun username(username: String) =\n apply {\n this.encodedUsername = username.canonicalize(encodeSet = USERNAME_ENCODE_SET)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":962,"symbol":"encodedUsername","kind":"function","lang":"kotlin","code":"fun encodedUsername(encodedUsername: String) =\n apply {\n this.encodedUsername =\n encodedUsername.canonicalize(\n encodeSet = USERNAME_ENCODE_SET,\n alreadyEncoded = true,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":971,"symbol":"password","kind":"function","lang":"kotlin","code":"fun password(password: String) =\n apply {\n this.encodedPassword = password.canonicalize(encodeSet = PASSWORD_ENCODE_SET)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":976,"symbol":"encodedPassword","kind":"function","lang":"kotlin","code":"fun encodedPassword(encodedPassword: String) =\n apply {\n this.encodedPassword =\n encodedPassword.canonicalize(\n encodeSet = PASSWORD_ENCODE_SET,\n alreadyEncoded = true,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":989,"symbol":"host","kind":"function","lang":"kotlin","doc":"@param host either a regular hostname, International Domain Name, IPv4 address, or IPv6 address.","code":"fun host(host: String) =\n apply {\n val encoded =\n host.percentDecode().toCanonicalHost()\n ?: throw IllegalArgumentException(\"unexpected host: $host\")\n this.host = encoded\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":997,"symbol":"port","kind":"function","lang":"kotlin","code":"fun port(port: Int) =\n apply {\n require(port in 1..65535) { \"unexpected port: $port\" }\n this.port = port\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1003,"symbol":"addPathSegment","kind":"function","lang":"kotlin","code":"fun addPathSegment(pathSegment: String) =\n apply {\n push(pathSegment, 0, pathSegment.length, addTrailingSlash = false, alreadyEncoded = false)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1012,"symbol":"addPathSegments","kind":"function","lang":"kotlin","doc":"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.","code":"fun addPathSegments(pathSegments: String): Builder = addPathSegments(pathSegments, false)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1014,"symbol":"addEncodedPathSegment","kind":"function","lang":"kotlin","code":"fun addEncodedPathSegment(encodedPathSegment: String) =\n apply {\n push(\n encodedPathSegment,\n 0,\n encodedPathSegment.length,\n addTrailingSlash = false,\n alreadyEncoded = true,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1029,"symbol":"addEncodedPathSegments","kind":"function","lang":"kotlin","doc":"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.","code":"fun addEncodedPathSegments(encodedPathSegments: String): Builder = addPathSegments(encodedPathSegments, true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1031,"symbol":"addPathSegments","kind":"function","lang":"kotlin","code":"private fun addPathSegments(\n pathSegments: String,\n alreadyEncoded: Boolean,\n ) = apply {\n var offset = 0\n do {\n val segmentEnd = pathSegments.delimiterOffset(\"/\\\\\", offset, pathSegments.length)\n val addTrailingSlash = segmentEnd < pathSegments.length\n push(pathSegments, offset, segmentEnd, addTrailingSlash, alreadyEncoded)\n offset = segmentEnd + 1\n } while (offset <= pathSegments.length)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1044,"symbol":"setPathSegment","kind":"function","lang":"kotlin","code":"fun setPathSegment(\n index: Int,\n pathSegment: String,\n ) = apply {\n val canonicalPathSegment = pathSegment.canonicalize(encodeSet = PATH_SEGMENT_ENCODE_SET)\n require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) {\n \"unexpected path segment: $pathSegment\"\n }\n encodedPathSegments[index] = canonicalPathSegment\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1055,"symbol":"setEncodedPathSegment","kind":"function","lang":"kotlin","code":"fun setEncodedPathSegment(\n index: Int,\n encodedPathSegment: String,\n ) = apply {\n val canonicalPathSegment =\n encodedPathSegment.canonicalize(\n encodeSet = PATH_SEGMENT_ENCODE_SET,\n alreadyEncoded = true,\n )\n encodedPathSegments[index] = canonicalPathSegment\n require(!isDot(canonicalPathSegment) && !isDotDot(canonicalPathSegment)) {\n \"unexpected path segment: $encodedPathSegment\"\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1070,"symbol":"removePathSegment","kind":"function","lang":"kotlin","code":"fun removePathSegment(index: Int) =\n apply {\n encodedPathSegments.removeAt(index)\n if (encodedPathSegments.isEmpty()) {\n encodedPathSegments.add(\"\") // Always leave at least one '/'.\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1078,"symbol":"encodedPath","kind":"function","lang":"kotlin","code":"fun encodedPath(encodedPath: String) =\n apply {\n require(encodedPath.startsWith(\"/\")) { \"unexpected encodedPath: $encodedPath\" }\n resolvePath(encodedPath, 0, encodedPath.length)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1084,"symbol":"query","kind":"function","lang":"kotlin","code":"fun query(query: String?) =\n apply {\n this.encodedQueryNamesAndValues =\n query\n ?.canonicalize(\n encodeSet = QUERY_ENCODE_SET,\n plusIsSpace = true,\n )?.toQueryNamesAndValues()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1094,"symbol":"encodedQuery","kind":"function","lang":"kotlin","code":"fun encodedQuery(encodedQuery: String?) =\n apply {\n this.encodedQueryNamesAndValues =\n encodedQuery\n ?.canonicalize(\n encodeSet = QUERY_ENCODE_SET,\n alreadyEncoded = true,\n plusIsSpace = true,\n )?.toQueryNamesAndValues()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1106,"symbol":"addQueryParameter","kind":"function","lang":"kotlin","doc":"Encodes the query parameter using UTF-8 and adds it to this URL's query string.","code":"fun addQueryParameter(\n name: String,\n value: String?,\n ) = apply {\n if (encodedQueryNamesAndValues == null) encodedQueryNamesAndValues = mutableListOf()\n encodedQueryNamesAndValues!!.add(\n name.canonicalize(\n encodeSet = QUERY_COMPONENT_ENCODE_SET,\n plusIsSpace = true,\n ),\n )\n encodedQueryNamesAndValues!!.add(\n value?.canonicalize(\n encodeSet = QUERY_COMPONENT_ENCODE_SET,\n plusIsSpace = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1126,"symbol":"addEncodedQueryParameter","kind":"function","lang":"kotlin","doc":"Adds the pre-encoded query parameter to this URL's query string.","code":"fun addEncodedQueryParameter(\n encodedName: String,\n encodedValue: String?,\n ) = apply {\n if (encodedQueryNamesAndValues == null) encodedQueryNamesAndValues = mutableListOf()\n encodedQueryNamesAndValues!!.add(\n encodedName.canonicalize(\n encodeSet = QUERY_COMPONENT_REENCODE_SET,\n alreadyEncoded = true,\n plusIsSpace = true,\n ),\n )\n encodedQueryNamesAndValues!!.add(\n encodedValue?.canonicalize(\n encodeSet = QUERY_COMPONENT_REENCODE_SET,\n alreadyEncoded = true,\n plusIsSpace = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1147,"symbol":"setQueryParameter","kind":"function","lang":"kotlin","code":"fun setQueryParameter(\n name: String,\n value: String?,\n ) = apply {\n removeAllQueryParameters(name)\n addQueryParameter(name, value)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1155,"symbol":"setEncodedQueryParameter","kind":"function","lang":"kotlin","code":"fun setEncodedQueryParameter(\n encodedName: String,\n encodedValue: String?,\n ) = apply {\n removeAllEncodedQueryParameters(encodedName)\n addEncodedQueryParameter(encodedName, encodedValue)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1163,"symbol":"removeAllQueryParameters","kind":"function","lang":"kotlin","code":"fun removeAllQueryParameters(name: String) =\n apply {\n if (encodedQueryNamesAndValues == null) return this\n val nameToRemove =\n name.canonicalize(\n encodeSet = QUERY_COMPONENT_ENCODE_SET,\n plusIsSpace = true,\n )\n removeAllCanonicalQueryParameters(nameToRemove)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1174,"symbol":"removeAllEncodedQueryParameters","kind":"function","lang":"kotlin","code":"fun removeAllEncodedQueryParameters(encodedName: String) =\n apply {\n if (encodedQueryNamesAndValues == null) return this\n removeAllCanonicalQueryParameters(\n encodedName.canonicalize(\n encodeSet = QUERY_COMPONENT_REENCODE_SET,\n alreadyEncoded = true,\n plusIsSpace = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1186,"symbol":"removeAllCanonicalQueryParameters","kind":"function","lang":"kotlin","code":"private fun removeAllCanonicalQueryParameters(canonicalName: String) {\n for (i in encodedQueryNamesAndValues!!.size - 2 downTo 0 step 2) {\n if (canonicalName == encodedQueryNamesAndValues!![i]) {\n encodedQueryNamesAndValues!!.removeAt(i + 1)\n encodedQueryNamesAndValues!!.removeAt(i)\n if (encodedQueryNamesAndValues!!.isEmpty()) {\n encodedQueryNamesAndValues = null\n return\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1199,"symbol":"fragment","kind":"function","lang":"kotlin","code":"fun fragment(fragment: String?) =\n apply {\n this.encodedFragment =\n fragment?.canonicalize(\n encodeSet = FRAGMENT_ENCODE_SET,\n unicodeAllowed = true,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/HttpUrl.kt","line":1208,"symbol":"encodedFragment","kind":"function","lang":"kotlin","code":"fun encodedFragment(encodedFragment: String?) =\n apply {\n this.encodedFragment =\n encodedFragment?.canonicalize(\n encodeSet = FRAGMENT_ENCODE_SET,\n alreadyEncoded = true,\n unicodeAllowed = true,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":66,"symbol":"Interceptor","kind":"interface","lang":"kotlin","doc":"} return chain.proceed(chain.request()) } ```","code":"fun interface Interceptor {\n @Throws(IOException::class)\n fun intercept(chain: Chain): Response\n\n companion object {\n /**\n * Constructs an interceptor for a lambda. This compact syntax is most useful for inline\n * interceptors.\n *\n * ```kotlin\n * val interceptor = Interceptor { chain: Interceptor.Chain ->\n * chain.proceed(chain.request())\n * }\n * ```\n */\n inline operator fun invoke(crossinline block: (chain: Chain) -> Response): Interceptor = Interceptor { block(it) }\n }\n\n interface Chain {\n fun request(): Request\n\n @Throws(IOException::class)\n fun proceed(request: Request): Response\n\n /**\n * Returns the connection the request will be executed on. This is only available in the chains\n * of network interceptors. For application interceptors this is always null.\n */\n fun connection(): Connection?\n\n /**\n * Returns the `Call` to which this chain belongs.\n */\n fun call(): Call\n\n /**\n * Returns the connect timeout in milliseconds.\n */\n fun connectTimeoutMillis(): Int\n\n /**\n * Returns a new chain with the specified connect timeout.\n */\n fun withConnectTimeout(\n time"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":67,"symbol":"intercept","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun intercept(chain: Chain): Response"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":81,"symbol":"invoke","kind":"function","lang":"kotlin","doc":"```kotlin val interceptor = Interceptor { chain: Interceptor.Chain -> chain.proceed(chain.request()) } ```","code":"inline operator fun invoke(crossinline block: (chain: Chain) -> Response): Interceptor = Interceptor { block(it) }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":84,"symbol":"Chain","kind":"interface","lang":"kotlin","code":"interface Chain {\n fun request(): Request\n\n @Throws(IOException::class)\n fun proceed(request: Request): Response\n\n /**\n * Returns the connection the request will be executed on. This is only available in the chains\n * of network interceptors. For application interceptors this is always null.\n */\n fun connection(): Connection?\n\n /**\n * Returns the `Call` to which this chain belongs.\n */\n fun call(): Call\n\n /**\n * Returns the connect timeout in milliseconds.\n */\n fun connectTimeoutMillis(): Int\n\n /**\n * Returns a new chain with the specified connect timeout.\n */\n fun withConnectTimeout(\n timeout: Int,\n unit: TimeUnit,\n ): Chain\n\n /**\n * Returns the read timeout in milliseconds.\n */\n fun readTimeoutMillis(): Int\n\n /**\n * Returns a new chain with the specified read timeout.\n */\n fun withReadTimeout(\n timeout: Int,\n unit: TimeUnit,\n ): Chain\n\n /**\n * Returns the write timeout in milliseconds.\n */\n fun writeTimeoutMillis(): Int\n\n /**\n * Returns a new chain with the specified write timeout.\n */\n fun withWriteTimeout(\n timeout: Int,\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":85,"symbol":"request","kind":"function","lang":"kotlin","code":"fun request(): Request"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":87,"symbol":"proceed","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun proceed(request: Request): Response"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":94,"symbol":"connection","kind":"function","lang":"kotlin","doc":"Returns the connection the request will be executed on. This is only available in the chains of network interceptors. For application interceptors this is always null.","code":"fun connection(): Connection?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":99,"symbol":"call","kind":"function","lang":"kotlin","doc":"Returns the `Call` to which this chain belongs.","code":"fun call(): Call"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":104,"symbol":"connectTimeoutMillis","kind":"function","lang":"kotlin","doc":"Returns the connect timeout in milliseconds.","code":"fun connectTimeoutMillis(): Int"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":109,"symbol":"withConnectTimeout","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified connect timeout.","code":"fun withConnectTimeout(\n timeout: Int,\n unit: TimeUnit,\n ): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":117,"symbol":"readTimeoutMillis","kind":"function","lang":"kotlin","doc":"Returns the read timeout in milliseconds.","code":"fun readTimeoutMillis(): Int"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":122,"symbol":"withReadTimeout","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified read timeout.","code":"fun withReadTimeout(\n timeout: Int,\n unit: TimeUnit,\n ): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":130,"symbol":"writeTimeoutMillis","kind":"function","lang":"kotlin","doc":"Returns the write timeout in milliseconds.","code":"fun writeTimeoutMillis(): Int"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":135,"symbol":"withWriteTimeout","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified write timeout.","code":"fun withWriteTimeout(\n timeout: Int,\n unit: TimeUnit,\n ): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":154,"symbol":"withDns","kind":"function","lang":"kotlin","doc":"Override the [DNS] for the Call.Chain. @throws IllegalStateException if this is a Network Interceptor, since the override is too late.","code":"fun withDns(dns: Dns): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":166,"symbol":"withSocketFactory","kind":"function","lang":"kotlin","doc":"Override the [SocketFactory] for the Call.Chain. @throws IllegalStateException if this is a Network Interceptor, since the override is too late.","code":"fun withSocketFactory(socketFactory: SocketFactory): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":176,"symbol":"withRetryOnConnectionFailure","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified retry on connection failure setting.","code":"fun withRetryOnConnectionFailure(retryOnConnectionFailure: Boolean): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":188,"symbol":"withAuthenticator","kind":"function","lang":"kotlin","doc":"Override the [Authenticator] for the Call.Chain. @throws IllegalStateException if this is a Network Interceptor, since the override is too late.","code":"fun withAuthenticator(authenticator: Authenticator): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":198,"symbol":"withCookieJar","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified [CookieJar].","code":"fun withCookieJar(cookieJar: CookieJar): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":210,"symbol":"withCache","kind":"function","lang":"kotlin","doc":"Override the [Cache] for the Call.Chain. @throws IllegalStateException if this is a Network Interceptor, since the override is too late.","code":"fun withCache(cache: Cache?): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":220,"symbol":"withProxy","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified [Proxy].","code":"fun withProxy(proxy: Proxy?): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":232,"symbol":"withProxySelector","kind":"function","lang":"kotlin","doc":"Override the [ProxySelector] for the Call.Chain. @throws IllegalStateException if this is a Network Interceptor, since the override is too late.","code":"fun withProxySelector(proxySelector: ProxySelector): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":242,"symbol":"withProxyAuthenticator","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified proxy [Authenticator].","code":"fun withProxyAuthenticator(proxyAuthenticator: Authenticator): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":254,"symbol":"withSslSocketFactory","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified [SSLSocketFactory]. @throws IllegalStateException if this is a Network Interceptor, since the override is too late.","code":"fun withSslSocketFactory(\n sslSocketFactory: SSLSocketFactory?,\n x509TrustManager: X509TrustManager?,\n ): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":274,"symbol":"withHostnameVerifier","kind":"function","lang":"kotlin","doc":"Override the [HostnameVerifier] for the Call.Chain. @throws IllegalStateException if this is a Network Interceptor, since the override is too late.","code":"fun withHostnameVerifier(hostnameVerifier: HostnameVerifier): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":284,"symbol":"withCertificatePinner","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified [CertificatePinner].","code":"fun withCertificatePinner(certificatePinner: CertificatePinner): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Interceptor.kt","line":294,"symbol":"withConnectionPool","kind":"function","lang":"kotlin","doc":"Returns a new chain with the specified [ConnectionPool].","code":"fun withConnectionPool(connectionPool: ConnectionPool): Chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":26,"symbol":"MediaType","kind":"class","lang":"kotlin","doc":"An [RFC 2045][rfc_2045] Media Type, appropriate to describe the content type of an HTTP request or response body. [rfc_2045]: http://tools.ietf.org/html/rfc2045","code":"class MediaType internal constructor(\n internal val mediaType: String,\n /**\n * Returns the high-level media type, such as \"text\", \"image\", \"audio\", \"video\", or \"application\".\n */\n @get:JvmName(\"type\") val type: String,\n /**\n * Returns a specific media subtype, such as \"plain\" or \"png\", \"mpeg\", \"mp4\" or \"xml\".\n */\n @get:JvmName(\"subtype\") val subtype: String,\n /** Alternating parameter names with their values, like `[\"charset\", \"utf-8\"]`. */\n private val parameterNamesAndValues: Array,\n) {\n /**\n * Returns the charset of this media type, or [defaultValue] if either this media type doesn't\n * specify a charset, or if its charset is unsupported by the current runtime.\n */\n @JvmOverloads\n fun charset(defaultValue: Charset? = null): Charset? {\n val charset = parameter(\"charset\") ?: return defaultValue\n return try {\n Charset.forName(charset)\n } catch (_: IllegalArgumentException) {\n defaultValue // This charset is invalid or unsupported. Give up.\n }\n }\n\n /**\n * Returns the parameter [name] of this media type, or null if this media type does not define\n * such a parameter.\n */\n fun parameter(name: String): String? {\n for (i "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":43,"symbol":"charset","kind":"function","lang":"kotlin","doc":"Returns the charset of this media type, or [defaultValue] if either this media type doesn't specify a charset, or if its charset is unsupported by the current runtime.","code":"@JvmOverloads\n fun charset(defaultValue: Charset? = null): Charset? {\n val charset = parameter(\"charset\") ?: return defaultValue\n return try {\n Charset.forName(charset)\n } catch (_: IllegalArgumentException) {\n defaultValue // This charset is invalid or unsupported. Give up.\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":57,"symbol":"parameter","kind":"function","lang":"kotlin","doc":"Returns the parameter [name] of this media type, or null if this media type does not define such a parameter.","code":"fun parameter(name: String): String? {\n for (i in parameterNamesAndValues.indices step 2) {\n if (parameterNamesAndValues[i].equals(name, ignoreCase = true)) {\n return parameterNamesAndValues[i + 1]\n }\n }\n return null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":66,"symbol":"type","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_type\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"type\"),\n level = DeprecationLevel.ERROR,\n )\n fun type(): String = type"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":74,"symbol":"subtype","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_subtype\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"subtype\"),\n level = DeprecationLevel.ERROR,\n )\n fun subtype(): String = subtype"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":86,"symbol":"toString","kind":"function","lang":"kotlin","doc":"Returns the encoded media type, like \"text/plain; charset=utf-8\", appropriate for use in a Content-Type header.","code":"override fun toString(): String = mediaType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":88,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean = other is MediaType && other.mediaType == mediaType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":90,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int = mediaType.hashCode()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":153,"symbol":"toMediaTypeOrNull","kind":"function","lang":"kotlin","doc":"Returns a media type for this, or null if this is not a well-formed media type.","code":"@JvmStatic\n @JvmName(\"parse\")\n fun String.toMediaTypeOrNull(): MediaType? =\n try {\n toMediaType()\n } catch (_: IllegalArgumentException) {\n null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":162,"symbol":"get","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_get\")\n @Deprecated(\n message = \"moved to extension function\",\n replaceWith =\n ReplaceWith(\n expression = \"mediaType.toMediaType()\",\n imports = [\"okhttp3.MediaType.Companion.toMediaType\"],\n ),\n level = DeprecationLevel.ERROR,\n )\n fun get(mediaType: String): MediaType = mediaType.toMediaType()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MediaType.kt","line":174,"symbol":"parse","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_parse\")\n @Deprecated(\n message = \"moved to extension function\",\n replaceWith =\n ReplaceWith(\n expression = \"mediaType.toMediaTypeOrNull()\",\n imports = [\"okhttp3.MediaType.Companion.toMediaTypeOrNull\"],\n ),\n level = DeprecationLevel.ERROR,\n )\n fun parse(mediaType: String): MediaType? = mediaType.toMediaTypeOrNull()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":35,"symbol":"MultipartBody","kind":"class","lang":"kotlin","doc":"An [RFC 2387][rfc_2387]-compliant request body. [rfc_2387]: http://www.ietf.org/rfc/rfc2387.txt","code":"@Suppress(\"NAME_SHADOWING\")\nclass MultipartBody internal constructor(\n private val boundaryByteString: ByteString,\n @get:JvmName(\"type\") val type: MediaType,\n @get:JvmName(\"parts\") val parts: List,\n) : RequestBody() {\n private val contentType: MediaType = \"$type; boundary=$boundary\".toMediaType()\n private var contentLength = -1L\n\n @get:JvmName(\"boundary\")\n val boundary: String\n get() = boundaryByteString.utf8()\n\n /** The number of parts in this multipart body. */\n @get:JvmName(\"size\")\n val size: Int\n get() = parts.size\n\n fun part(index: Int): Part = parts[index]\n\n override fun isOneShot(): Boolean = parts.any { it.body.isOneShot() }\n\n /** A combination of [type] and [boundaryByteString]. */\n override fun contentType(): MediaType = contentType\n\n @JvmName(\"-deprecated_type\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"type\"),\n level = DeprecationLevel.ERROR,\n )\n fun type(): MediaType = type\n\n @JvmName(\"-deprecated_boundary\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"boundary\"),\n level = DeprecationLevel.ERROR,\n )\n fun boundary(): String = boundary\n\n @JvmN"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":53,"symbol":"part","kind":"function","lang":"kotlin","code":"fun part(index: Int): Part = parts[index]"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":55,"symbol":"isOneShot","kind":"function","lang":"kotlin","code":"override fun isOneShot(): Boolean = parts.any { it.body.isOneShot() }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":58,"symbol":"contentType","kind":"function","lang":"kotlin","doc":"A combination of [type] and [boundaryByteString].","code":"override fun contentType(): MediaType = contentType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":60,"symbol":"type","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_type\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"type\"),\n level = DeprecationLevel.ERROR,\n )\n fun type(): MediaType = type"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":68,"symbol":"boundary","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_boundary\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"boundary\"),\n level = DeprecationLevel.ERROR,\n )\n fun boundary(): String = boundary"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":76,"symbol":"size","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_size\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"size\"),\n level = DeprecationLevel.ERROR,\n )\n fun size(): Int = size"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":84,"symbol":"parts","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_parts\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"parts\"),\n level = DeprecationLevel.ERROR,\n )\n fun parts(): List = parts"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":92,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun contentLength(): Long {\n var result = contentLength\n if (result == -1L) {\n result = writeOrCountBytes(null, true)\n contentLength = result\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":102,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n writeOrCountBytes(sink, false)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":113,"symbol":"writeOrCountBytes","kind":"function","lang":"kotlin","doc":"Either writes this request to [sink] or measures its content length. We have one method do double-duty to make sure the counting and content are consistent, particularly when it comes to awkward operations like measuring the encoded length of header strings, or the length-in-digits of an encoded integer.","code":"@Throws(IOException::class)\n private fun writeOrCountBytes(\n sink: BufferedSink?,\n countBytes: Boolean,\n ): Long {\n var sink = sink\n var byteCount = 0L\n\n var byteCountBuffer: Buffer? = null\n if (countBytes) {\n byteCountBuffer = Buffer()\n sink = byteCountBuffer\n }\n\n for (p in 0 until parts.size) {\n val part = parts[p]\n val headers = part.headers\n val body = part.body\n\n sink!!.write(DASHDASH)\n sink.write(boundaryByteString)\n sink.write(CRLF)\n\n if (headers != null) {\n for (h in 0 until headers.size) {\n sink\n .writeUtf8(headers.name(h))\n .write(COLONSPACE)\n .writeUtf8(headers.value(h))\n .write(CRLF)\n }\n }\n\n val contentType = body.contentType()\n if (contentType != null) {\n sink\n .writeUtf8(\"Content-Type: \")\n .writeUtf8(contentType.toString())\n .write(CRLF)\n }\n\n // We can't measure the body's size without the sizes of its components.\n val contentLength = body.contentLength()\n if (contentLength == -1L && countBytes) {\n byteCountBuffer!!.clear()\n return -1L\n }\n\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":185,"symbol":"Part","kind":"class","lang":"kotlin","code":"class Part private constructor(\n @get:JvmName(\"headers\") val headers: Headers?,\n @get:JvmName(\"body\") val body: RequestBody,\n ) {\n @JvmName(\"-deprecated_headers\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"headers\"),\n level = DeprecationLevel.ERROR,\n )\n fun headers(): Headers? = headers\n\n @JvmName(\"-deprecated_body\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"body\"),\n level = DeprecationLevel.ERROR,\n )\n fun body(): RequestBody = body\n\n companion object {\n @JvmStatic\n fun create(body: RequestBody): Part = create(null, body)\n\n @JvmStatic\n fun create(\n headers: Headers?,\n body: RequestBody,\n ): Part {\n require(headers?.get(\"Content-Type\") == null) { \"Unexpected header: Content-Type\" }\n require(headers?.get(\"Content-Length\") == null) { \"Unexpected header: Content-Length\" }\n return Part(headers, body)\n }\n\n @JvmStatic\n fun createFormData(\n name: String,\n value: String,\n ): Part = createFormData(name, null, value.toRequestBody())\n\n @JvmStatic\n fun"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":189,"symbol":"headers","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_headers\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"headers\"),\n level = DeprecationLevel.ERROR,\n )\n fun headers(): Headers? = headers"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":197,"symbol":"body","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_body\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"body\"),\n level = DeprecationLevel.ERROR,\n )\n fun body(): RequestBody = body"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":206,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun create(body: RequestBody): Part = create(null, body)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":209,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun create(\n headers: Headers?,\n body: RequestBody,\n ): Part {\n require(headers?.get(\"Content-Type\") == null) { \"Unexpected header: Content-Type\" }\n require(headers?.get(\"Content-Length\") == null) { \"Unexpected header: Content-Length\" }\n return Part(headers, body)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":219,"symbol":"createFormData","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun createFormData(\n name: String,\n value: String,\n ): Part = createFormData(name, null, value.toRequestBody())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":225,"symbol":"createFormData","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun createFormData(\n name: String,\n filename: String?,\n body: RequestBody,\n ): Part {\n val disposition =\n buildString {\n append(\"form-data; name=\")\n appendQuotedString(name)\n\n if (filename != null) {\n append(\"; filename=\")\n appendQuotedString(filename)\n }\n }\n\n val headers =\n Headers\n .Builder()\n .addUnsafeNonAscii(\"Content-Disposition\", disposition)\n .build()\n\n return create(headers, body)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":266,"symbol":"setType","kind":"function","lang":"kotlin","doc":"Set the MIME type. Expected values for `type` are [MIXED] (the default), [ALTERNATIVE], [DIGEST], [PARALLEL] and [FORM].","code":"fun setType(type: MediaType) =\n apply {\n require(type.type == \"multipart\") { \"multipart != $type\" }\n this.type = type\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":273,"symbol":"addPart","kind":"function","lang":"kotlin","doc":"Add a part to the body.","code":"fun addPart(body: RequestBody) =\n apply {\n addPart(Part.create(body))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":279,"symbol":"addPart","kind":"function","lang":"kotlin","doc":"Add a part to the body.","code":"fun addPart(\n headers: Headers?,\n body: RequestBody,\n ) = apply {\n addPart(Part.create(headers, body))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":287,"symbol":"addFormDataPart","kind":"function","lang":"kotlin","doc":"Add a form data part to the body.","code":"fun addFormDataPart(\n name: String,\n value: String,\n ) = apply {\n addPart(Part.createFormData(name, value))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":295,"symbol":"addFormDataPart","kind":"function","lang":"kotlin","doc":"Add a form data part to the body.","code":"fun addFormDataPart(\n name: String,\n filename: String?,\n body: RequestBody,\n ) = apply {\n addPart(Part.createFormData(name, filename, body))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":304,"symbol":"addPart","kind":"function","lang":"kotlin","doc":"Add a part to the body.","code":"fun addPart(part: Part) =\n apply {\n parts += part\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":310,"symbol":"build","kind":"function","lang":"kotlin","doc":"Assemble the specified parts into a request body.","code":"fun build(): MultipartBody {\n check(parts.isNotEmpty()) { \"Multipart body must have at least one part.\" }\n return MultipartBody(boundary, type, parts.toImmutableList())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":370,"symbol":"appendQuotedString","kind":"function","lang":"kotlin","doc":"parameters, and as it turns out Firefox and Chrome actually do rather different things, and both say in their comments that they're not really sure what the right approach is. We go with Chrome's behavior (which also experimentally seems to match what IE does), but if you actually want to have a good chance of things working, please avoid double-quotes, newlines, percent signs, and the like in your field names.","code":"internal fun StringBuilder.appendQuotedString(key: String) {\n append('\"')\n for (i in 0 until key.length) {\n when (val ch = key[i]) {\n '\\n' -> append(\"%0A\")\n '\\r' -> append(\"%0D\")\n '\"' -> append(\"%22\")\n else -> append(ch)\n }\n }\n append('\"')\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":384,"symbol":"NoCloseSink","kind":"class","lang":"kotlin","code":"private class NoCloseSink(\n sink: Sink,\n ) : ForwardingSink(sink) {\n override fun close() {}\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartBody.kt","line":387,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt","line":96,"symbol":"nextPart","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun nextPart(): Part? {\n check(!closed) { \"closed\" }\n\n if (noMoreParts) return null\n\n // Read a boundary, skipping the remainder of the preceding part as necessary.\n if (partCount == 0 && source.rangeEquals(0L, dashDashBoundary)) {\n // This is the first part. Consume \"--\" followed by the boundary.\n source.skip(dashDashBoundary.size.toLong())\n } else {\n // This is a subsequent part or a preamble. Skip until \"\\r\\n--\" followed by the boundary.\n while (true) {\n val toSkip = currentPartBytesRemaining(maxByteCount = 8192)\n if (toSkip == 0L) break\n source.skip(toSkip)\n }\n source.skip(crlfDashDashBoundary.size.toLong())\n }\n\n // Read either \\r\\n or --\\r\\n to determine if there is another part.\n var whitespace = false\n afterBoundaryLoop@while (true) {\n when (source.select(afterBoundaryOptions)) {\n 0 -> {\n // \"\\r\\n\": We've found a new part.\n partCount++\n break@afterBoundaryLoop\n }\n\n 1 -> {\n // \"--\": No more parts.\n if (whitespace) throw ProtocolException(\"unexpe"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt","line":154,"symbol":"PartSource","kind":"class","lang":"kotlin","doc":"A single part in the stream. It is an error to read this after calling [nextPart].","code":"private inner class PartSource : Source {\n private val timeout = Timeout()\n\n override fun close() {\n if (currentPart == this) {\n currentPart = null\n }\n }\n\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n require(byteCount >= 0L) { \"byteCount < 0: $byteCount\" }\n check(currentPart == this) { \"closed\" }\n\n return source.timeout().intersectWith(timeout) {\n when (val limit = currentPartBytesRemaining(maxByteCount = byteCount)) {\n 0L -> -1L\n\n // No more bytes in this part.\n else -> source.read(sink, limit)\n }\n }\n }\n\n override fun timeout(): Timeout = timeout\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt","line":157,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n if (currentPart == this) {\n currentPart = null\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt","line":163,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n require(byteCount >= 0L) { \"byteCount < 0: $byteCount\" }\n check(currentPart == this) { \"closed\" }\n\n return source.timeout().intersectWith(timeout) {\n when (val limit = currentPartBytesRemaining(maxByteCount = byteCount)) {\n 0L -> -1L\n\n // No more bytes in this part.\n else -> source.read(sink, limit)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt","line":180,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = timeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt","line":188,"symbol":"currentPartBytesRemaining","kind":"function","lang":"kotlin","doc":"Returns a value in [0..maxByteCount] with the number of bytes that can be read from [source] in the current part. If this returns 0 the current part is exhausted; otherwise it has at least one byte left to read.","code":"private fun currentPartBytesRemaining(maxByteCount: Long): Long {\n val toIndex = minOf(source.buffer.size, maxByteCount) + 1L\n val boundaryIndex =\n source.indexOf(\n bytes = crlfDashDashBoundary,\n fromIndex = 0L,\n toIndex = toIndex,\n )\n return when {\n boundaryIndex != -1L -> boundaryIndex\n\n // We found the boundary.\n source.buffer.size >= toIndex -> minOf(toIndex, maxByteCount)\n\n // No boundary before toIndex.\n else -> throw EOFException() // We ran out of data before we found the required boundary.\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt","line":207,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n if (closed) return\n closed = true\n currentPart = null\n source.close()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttp.kt","line":18,"symbol":"OkHttp","kind":"object","lang":"kotlin","code":"expect object OkHttp {\n /**\n * This is a string like \"5.0.0\", \"5.0.0-alpha.762\", or \"5.3.0-SNAPSHOT\" indicating the version of\n * OkHttp in the current runtime. Use this to include the OkHttp version in custom `User-Agent`\n * headers.\n *\n * Official OkHttp releases follow [semantic versioning][semver]. Versions with the `-SNAPSHOT`\n * qualifier are not unique and should only be used in development environments. If you create\n * custom builds of OkHttp please include a qualifier your version name, like \"4.7.0-mycompany.3\".\n * The version string is configured in the root project's `build.gradle`.\n *\n * Note that OkHttp's runtime version may be different from the version specified in your\n * project's build file due to the dependency resolution features of your build tool.\n *\n * [semver]: https://semver.org\n */\n val VERSION: String\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":135,"symbol":"OkHttpClient","kind":"class","lang":"kotlin","doc":"client.cache().close(); ``` OkHttp also uses daemon threads for HTTP/2 connections. These will exit automatically if they remain idle.","code":"open class OkHttpClient internal constructor(\n builder: Builder,\n) : Call.Factory,\n WebSocket.Factory {\n @get:JvmName(\"dispatcher\")\n val dispatcher: Dispatcher = builder.dispatcher\n\n /**\n * Returns an immutable list of interceptors that observe the full span of each call: from before\n * the connection is established (if any) until after the response source is selected (either the\n * origin server, cache, or both).\n */\n @get:JvmName(\"interceptors\")\n val interceptors: List =\n builder.interceptors.toImmutableList()\n\n /**\n * Returns an immutable list of interceptors that observe a single network request and response.\n * These interceptors must call [Interceptor.Chain.proceed] exactly once: it is an error for\n * a network interceptor to short-circuit or repeat a network request.\n */\n @get:JvmName(\"networkInterceptors\")\n val networkInterceptors: List =\n builder.networkInterceptors.toImmutableList()\n\n @get:JvmName(\"eventListenerFactory\")\n val eventListenerFactory: EventListener.Factory =\n builder.eventListenerFactory\n\n @get:JvmName(\"retryOnConnectionFailure\")\n val retryOnConnectionFailure: Boolean =\n builder.retryOnConnec"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":310,"symbol":"address","kind":"function","lang":"kotlin","doc":"Creates an [Address] of out of the provided [HttpUrl] that uses this client’s DNS, TLS, and proxy configuration.","code":"fun address(url: HttpUrl): Address {\n var useSslSocketFactory: SSLSocketFactory? = null\n var useHostnameVerifier: HostnameVerifier? = null\n var useCertificatePinner: CertificatePinner? = null\n if (url.isHttps) {\n useSslSocketFactory = sslSocketFactory\n useHostnameVerifier = hostnameVerifier\n useCertificatePinner = certificatePinner\n }\n\n return Address(\n uriHost = url.host,\n uriPort = url.port,\n dns = dns,\n socketFactory = socketFactory,\n sslSocketFactory = useSslSocketFactory,\n hostnameVerifier = useHostnameVerifier,\n certificatePinner = useCertificatePinner,\n proxyAuthenticator = proxyAuthenticator,\n proxy = proxy,\n protocols = protocols,\n connectionSpecs = connectionSpecs,\n proxySelector = proxySelector,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":336,"symbol":"verifyClientState","kind":"function","lang":"kotlin","code":"private fun verifyClientState() {\n check(null !in (interceptors as List)) {\n \"Null interceptor: $interceptors\"\n }\n check(null !in (networkInterceptors as List)) {\n \"Null network interceptor: $networkInterceptors\"\n }\n\n if (connectionSpecs.none { it.isTls }) {\n check(sslSocketFactoryOrNull == null)\n check(certificateChainCleaner == null)\n check(x509TrustManager == null)\n check(certificatePinner == CertificatePinner.DEFAULT)\n } else {\n checkNotNull(sslSocketFactoryOrNull) { \"sslSocketFactory == null\" }\n checkNotNull(certificateChainCleaner) { \"certificateChainCleaner == null\" }\n checkNotNull(x509TrustManager) { \"x509TrustManager == null\" }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":357,"symbol":"newCall","kind":"function","lang":"kotlin","doc":"Prepares the [request] to be executed at some point in the future.","code":"override fun newCall(request: Request): Call = RealCall(this, request, forWebSocket = false)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":360,"symbol":"newWebSocket","kind":"function","lang":"kotlin","doc":"Uses [request] to connect a new web socket.","code":"override fun newWebSocket(\n request: Request,\n listener: WebSocketListener,\n ): WebSocket {\n val webSocket =\n RealWebSocket(\n taskRunner = taskRunner,\n originalRequest = request,\n listener = listener,\n random = Random(),\n pingIntervalMillis = pingIntervalMillis.toLong(),\n // extensions is always null for clients:\n extensions = null,\n minimumDeflateSize = minWebSocketMessageToCompress,\n webSocketCloseTimeout = webSocketCloseTimeout.toLong(),\n )\n webSocket.connect(this)\n return webSocket\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":380,"symbol":"newBuilder","kind":"function","lang":"kotlin","code":"open fun newBuilder(): Builder = Builder(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":382,"symbol":"dispatcher","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_dispatcher\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"dispatcher\"),\n level = DeprecationLevel.ERROR,\n )\n fun dispatcher(): Dispatcher = dispatcher"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":390,"symbol":"connectionPool","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_connectionPool\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"connectionPool\"),\n level = DeprecationLevel.ERROR,\n )\n fun connectionPool(): ConnectionPool = connectionPool"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":398,"symbol":"interceptors","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_interceptors\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"interceptors\"),\n level = DeprecationLevel.ERROR,\n )\n fun interceptors(): List = interceptors"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":406,"symbol":"networkInterceptors","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_networkInterceptors\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"networkInterceptors\"),\n level = DeprecationLevel.ERROR,\n )\n fun networkInterceptors(): List = networkInterceptors"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":414,"symbol":"eventListenerFactory","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_eventListenerFactory\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"eventListenerFactory\"),\n level = DeprecationLevel.ERROR,\n )\n fun eventListenerFactory(): EventListener.Factory = eventListenerFactory"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":422,"symbol":"retryOnConnectionFailure","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_retryOnConnectionFailure\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"retryOnConnectionFailure\"),\n level = DeprecationLevel.ERROR,\n )\n fun retryOnConnectionFailure(): Boolean = retryOnConnectionFailure"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":430,"symbol":"authenticator","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_authenticator\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"authenticator\"),\n level = DeprecationLevel.ERROR,\n )\n fun authenticator(): Authenticator = authenticator"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":438,"symbol":"followRedirects","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_followRedirects\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"followRedirects\"),\n level = DeprecationLevel.ERROR,\n )\n fun followRedirects(): Boolean = followRedirects"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":446,"symbol":"followSslRedirects","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_followSslRedirects\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"followSslRedirects\"),\n level = DeprecationLevel.ERROR,\n )\n fun followSslRedirects(): Boolean = followSslRedirects"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":454,"symbol":"cookieJar","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_cookieJar\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"cookieJar\"),\n level = DeprecationLevel.ERROR,\n )\n fun cookieJar(): CookieJar = cookieJar"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":462,"symbol":"cache","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_cache\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"cache\"),\n level = DeprecationLevel.ERROR,\n )\n fun cache(): Cache? = cache"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":470,"symbol":"dns","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_dns\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"dns\"),\n level = DeprecationLevel.ERROR,\n )\n fun dns(): Dns = dns"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":478,"symbol":"proxy","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_proxy\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"proxy\"),\n level = DeprecationLevel.ERROR,\n )\n fun proxy(): Proxy? = proxy"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":486,"symbol":"proxySelector","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_proxySelector\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"proxySelector\"),\n level = DeprecationLevel.ERROR,\n )\n fun proxySelector(): ProxySelector = proxySelector"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":494,"symbol":"proxyAuthenticator","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_proxyAuthenticator\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"proxyAuthenticator\"),\n level = DeprecationLevel.ERROR,\n )\n fun proxyAuthenticator(): Authenticator = proxyAuthenticator"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":502,"symbol":"socketFactory","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_socketFactory\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"socketFactory\"),\n level = DeprecationLevel.ERROR,\n )\n fun socketFactory(): SocketFactory = socketFactory"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":510,"symbol":"sslSocketFactory","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_sslSocketFactory\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"sslSocketFactory\"),\n level = DeprecationLevel.ERROR,\n )\n fun sslSocketFactory(): SSLSocketFactory = sslSocketFactory"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":518,"symbol":"connectionSpecs","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_connectionSpecs\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"connectionSpecs\"),\n level = DeprecationLevel.ERROR,\n )\n fun connectionSpecs(): List = connectionSpecs"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":526,"symbol":"protocols","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_protocols\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"protocols\"),\n level = DeprecationLevel.ERROR,\n )\n fun protocols(): List = protocols"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":534,"symbol":"hostnameVerifier","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_hostnameVerifier\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"hostnameVerifier\"),\n level = DeprecationLevel.ERROR,\n )\n fun hostnameVerifier(): HostnameVerifier = hostnameVerifier"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":542,"symbol":"certificatePinner","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_certificatePinner\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"certificatePinner\"),\n level = DeprecationLevel.ERROR,\n )\n fun certificatePinner(): CertificatePinner = certificatePinner"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":550,"symbol":"callTimeoutMillis","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_callTimeoutMillis\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"callTimeoutMillis\"),\n level = DeprecationLevel.ERROR,\n )\n fun callTimeoutMillis(): Int = callTimeoutMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":558,"symbol":"connectTimeoutMillis","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_connectTimeoutMillis\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"connectTimeoutMillis\"),\n level = DeprecationLevel.ERROR,\n )\n fun connectTimeoutMillis(): Int = connectTimeoutMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":566,"symbol":"readTimeoutMillis","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_readTimeoutMillis\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"readTimeoutMillis\"),\n level = DeprecationLevel.ERROR,\n )\n fun readTimeoutMillis(): Int = readTimeoutMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":574,"symbol":"writeTimeoutMillis","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_writeTimeoutMillis\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"writeTimeoutMillis\"),\n level = DeprecationLevel.ERROR,\n )\n fun writeTimeoutMillis(): Int = writeTimeoutMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":582,"symbol":"pingIntervalMillis","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_pingIntervalMillis\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"pingIntervalMillis\"),\n level = DeprecationLevel.ERROR,\n )\n fun pingIntervalMillis(): Int = pingIntervalMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":590,"symbol":"Builder","kind":"class","lang":"kotlin","code":"class Builder() {\n internal var dispatcher: Dispatcher = Dispatcher()\n internal var connectionPool: ConnectionPool? = null\n internal val interceptors: MutableList = mutableListOf()\n internal val networkInterceptors: MutableList = mutableListOf()\n internal var eventListenerFactory: EventListener.Factory = EventListener.NONE.asFactory()\n internal var retryOnConnectionFailure = true\n internal var fastFallback = true\n internal var authenticator: Authenticator = Authenticator.NONE\n internal var followRedirects = true\n internal var followSslRedirects = true\n internal var cookieJar: CookieJar = CookieJar.NO_COOKIES\n internal var cache: Cache? = null\n internal var dns: Dns = Dns.SYSTEM\n internal var proxy: Proxy? = null\n internal var proxySelector: ProxySelector? = null\n internal var proxyAuthenticator: Authenticator = Authenticator.NONE\n internal var socketFactory: SocketFactory = Platform.get().socketFactory\n internal var sslSocketFactoryOrNull: SSLSocketFactory? = null\n internal var x509TrustManagerOrNull: X509TrustManager? = null\n internal var connectionSpecs: List = DEFAULT_CONNECTION"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":664,"symbol":"dispatcher","kind":"function","lang":"kotlin","doc":"Sets the dispatcher used to set policy and execute asynchronous requests. Must not be null.","code":"fun dispatcher(dispatcher: Dispatcher) =\n apply {\n this.dispatcher = dispatcher\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":674,"symbol":"connectionPool","kind":"function","lang":"kotlin","doc":"Sets the connection pool used to recycle HTTP and HTTPS connections. If unset, a new connection pool will be used.","code":"fun connectionPool(connectionPool: ConnectionPool) =\n apply {\n this.connectionPool = connectionPool\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":684,"symbol":"interceptors","kind":"function","lang":"kotlin","doc":"Returns a modifiable list of interceptors that observe the full span of each call: from before the connection is established (if any) until after the response source is selected (either the origin server, cache, or both).","code":"fun interceptors(): MutableList = interceptors"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":686,"symbol":"addInterceptor","kind":"function","lang":"kotlin","code":"fun addInterceptor(interceptor: Interceptor) =\n apply {\n interceptors += interceptor\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":691,"symbol":"addInterceptor","kind":"function","lang":"kotlin","code":"@JvmName(\"-addInterceptor\") // Prefix with '-' to prevent ambiguous overloads from Java.\n inline fun addInterceptor(crossinline block: (chain: Interceptor.Chain) -> Response) =\n addInterceptor(Interceptor { chain -> block(chain) })"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":700,"symbol":"networkInterceptors","kind":"function","lang":"kotlin","doc":"Returns a modifiable list of interceptors that observe a single network request and response. These interceptors must call [Interceptor.Chain.proceed] exactly once: it is an error for a network interceptor to short-circuit or repeat a network request.","code":"fun networkInterceptors(): MutableList = networkInterceptors"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":702,"symbol":"addNetworkInterceptor","kind":"function","lang":"kotlin","code":"fun addNetworkInterceptor(interceptor: Interceptor) =\n apply {\n networkInterceptors += interceptor\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":707,"symbol":"addNetworkInterceptor","kind":"function","lang":"kotlin","code":"@JvmName(\"-addNetworkInterceptor\") // Prefix with '-' to prevent ambiguous overloads from Java.\n inline fun addNetworkInterceptor(crossinline block: (chain: Interceptor.Chain) -> Response) =\n addNetworkInterceptor(Interceptor { chain -> block(chain) })"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":717,"symbol":"eventListener","kind":"function","lang":"kotlin","doc":"Configure a single client scoped listener that will receive all analytic events for this client. @see EventListener for semantics and restrictions on listener implementations.","code":"fun eventListener(eventListener: EventListener) =\n apply {\n this.eventListenerFactory = eventListener.asFactory()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":728,"symbol":"eventListenerFactory","kind":"function","lang":"kotlin","doc":"Configure a factory to provide per-call scoped listeners that will receive analytic events for this client. @see EventListener for semantics and restrictions on listener implementations.","code":"fun eventListenerFactory(eventListenerFactory: EventListener.Factory) =\n apply {\n this.eventListenerFactory = eventListenerFactory\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":751,"symbol":"retryOnConnectionFailure","kind":"function","lang":"kotlin","doc":"attempt multiple proxy servers in sequence, eventually falling back to a direct connection. Set this to false to avoid retrying requests when doing so is destructive. In this case the calling application should do its own recovery of connectivity failures.","code":"fun retryOnConnectionFailure(retryOnConnectionFailure: Boolean) =\n apply {\n this.retryOnConnectionFailure = retryOnConnectionFailure\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":767,"symbol":"fastFallback","kind":"function","lang":"kotlin","doc":"wasted resources. Defaults to enabled, call with [fastFallback] = false to revert to 4.x behaviour. [rfc_6555]: https://datatracker.ietf.org/doc/html/rfc6555","code":"fun fastFallback(fastFallback: Boolean) =\n apply {\n this.fastFallback = fastFallback\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":778,"symbol":"authenticator","kind":"function","lang":"kotlin","doc":"Sets the authenticator used to respond to challenges from origin servers. Use [proxyAuthenticator] to set the authenticator for proxy servers. If unset, the [no authentication will be attempted][Authenticator.NONE].","code":"fun authenticator(authenticator: Authenticator) =\n apply {\n this.authenticator = authenticator\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":784,"symbol":"followRedirects","kind":"function","lang":"kotlin","doc":"Configure this client to follow redirects. If unset, redirects will be followed.","code":"fun followRedirects(followRedirects: Boolean) =\n apply {\n this.followRedirects = followRedirects\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":795,"symbol":"followSslRedirects","kind":"function","lang":"kotlin","doc":"Configure this client to allow protocol redirects from HTTPS to HTTP and from HTTP to HTTPS. Redirects are still first restricted by [followRedirects]. Defaults to true. @param followProtocolRedirects whether to follow redirects between HTTPS and HTTP.","code":"fun followSslRedirects(followProtocolRedirects: Boolean) =\n apply {\n this.followSslRedirects = followProtocolRedirects\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":806,"symbol":"cookieJar","kind":"function","lang":"kotlin","doc":"Sets the handler that can accept cookies from incoming HTTP responses and provides cookies to outgoing HTTP requests. If unset, [no cookies][CookieJar.NO_COOKIES] will be accepted nor provided.","code":"fun cookieJar(cookieJar: CookieJar) =\n apply {\n this.cookieJar = cookieJar\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":812,"symbol":"cache","kind":"function","lang":"kotlin","doc":"Sets the response cache to be used to read and write cached responses.","code":"fun cache(cache: Cache?) =\n apply {\n this.cache = cache\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":817,"symbol":"taskRunner","kind":"function","lang":"kotlin","code":"internal fun taskRunner(taskRunner: TaskRunner) =\n apply {\n this.taskRunner = taskRunner\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":827,"symbol":"dns","kind":"function","lang":"kotlin","doc":"Sets the DNS service used to lookup IP addresses for hostnames. If unset, the [system-wide default][Dns.SYSTEM] DNS will be used.","code":"fun dns(dns: Dns) =\n apply {\n if (dns != this.dns) {\n this.routeDatabase = null\n }\n this.dns = dns\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":840,"symbol":"proxy","kind":"function","lang":"kotlin","doc":"Sets the HTTP proxy that will be used by connections created by this client. This takes precedence over [proxySelector], which is only honored when this proxy is null (which it is by default). To disable proxy use completely, call `proxy(Proxy.NO_PROXY)`.","code":"fun proxy(proxy: Proxy?) =\n apply {\n if (proxy != this.proxy) {\n this.routeDatabase = null\n }\n this.proxy = proxy\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":855,"symbol":"proxySelector","kind":"function","lang":"kotlin","doc":"Sets the proxy selection policy to be used if no [proxy][proxy] is specified explicitly. The proxy selector may return multiple proxies; in that case they will be tried in sequence until a successful connection is established. If unset, the [system-wide default][ProxySelector.getDefault] proxy selector will be used.","code":"fun proxySelector(proxySelector: ProxySelector) =\n apply {\n if (proxySelector != this.proxySelector) {\n this.routeDatabase = null\n }\n\n this.proxySelector = proxySelector\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":870,"symbol":"proxyAuthenticator","kind":"function","lang":"kotlin","doc":"Sets the authenticator used to respond to challenges from proxy servers. Use [authenticator] to set the authenticator for origin servers. If unset, the [no authentication will be attempted][Authenticator.NONE].","code":"fun proxyAuthenticator(proxyAuthenticator: Authenticator) =\n apply {\n if (proxyAuthenticator != this.proxyAuthenticator) {\n this.routeDatabase = null\n }\n\n this.proxyAuthenticator = proxyAuthenticator\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":886,"symbol":"socketFactory","kind":"function","lang":"kotlin","doc":"Sets the socket factory used to create connections. OkHttp only uses the parameterless [SocketFactory.createSocket] method to create unconnected sockets. Overriding this method, e. g., allows the socket to be bound to a specific local address. If unset, the [system-wide default][SocketFactory.getDefault] socket factory will be used.","code":"fun socketFactory(socketFactory: SocketFactory) =\n apply {\n require(socketFactory !is SSLSocketFactory) { \"socketFactory instanceof SSLSocketFactory\" }\n\n if (socketFactory != this.socketFactory) {\n this.routeDatabase = null\n }\n\n this.socketFactory = socketFactory\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":906,"symbol":"sslSocketFactory","kind":"function","lang":"kotlin","doc":"@deprecated [SSLSocketFactory] does not expose its [X509TrustManager], which is a field that OkHttp needs to build a clean certificate chain. This method instead must use reflection to extract the trust manager. Applications should prefer to call `sslSocketFactory(SSLSocketFactory, X509TrustManager)`, which avoids such reflection.","code":"@Deprecated(\n message = \"Use the sslSocketFactory overload that accepts a X509TrustManager.\",\n level = DeprecationLevel.ERROR,\n )\n fun sslSocketFactory(sslSocketFactory: SSLSocketFactory) =\n apply {\n if (sslSocketFactory != this.sslSocketFactoryOrNull) {\n this.routeDatabase = null\n }\n\n this.sslSocketFactoryOrNull = sslSocketFactory\n this.x509TrustManagerOrNull =\n Platform.get().trustManager(sslSocketFactory) ?: throw IllegalStateException(\n \"Unable to extract the trust manager on ${Platform.get()}, \" +\n \"sslSocketFactory is ${sslSocketFactory.javaClass}\",\n )\n this.certificateChainCleaner =\n Platform.get().buildCertificateChainCleaner(x509TrustManagerOrNull!!)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":971,"symbol":"sslSocketFactory","kind":"function","lang":"kotlin","doc":"This method works like [X509TrustManager.checkServerTrusted] but it receives the hostname of the server as an extra parameter. Regardless of what checks this method performs, OkHttp will always check that the server's certificates match its hostname using the [HostnameVerifier]. See [android.net.http.X509TrustManagerExtensions] for more information.","code":"fun sslSocketFactory(\n sslSocketFactory: SSLSocketFactory,\n trustManager: X509TrustManager,\n ) = apply {\n if (sslSocketFactory != this.sslSocketFactoryOrNull || trustManager != this.x509TrustManagerOrNull) {\n this.routeDatabase = null\n }\n\n this.sslSocketFactoryOrNull = sslSocketFactory\n this.certificateChainCleaner = CertificateChainCleaner.get(trustManager)\n this.x509TrustManagerOrNull = trustManager\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":984,"symbol":"connectionSpecs","kind":"function","lang":"kotlin","code":"fun connectionSpecs(connectionSpecs: List) =\n apply {\n if (connectionSpecs != this.connectionSpecs) {\n this.routeDatabase = null\n }\n\n this.connectionSpecs = connectionSpecs.toImmutableList()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt","line":1024,"symbol":"protocols","kind":"function","lang":"kotlin","doc":"@param protocols the protocols to use, in order of preference. If the list contains [Protocol.H2_PRIOR_KNOWLEDGE] then that must be the only protocol and HTTPS URLs will not be supported. Otherwise the list must contain [Protocol.HTTP_1_1]. The list must not contain null or [Protocol.HTTP_1_0].","code":"fun protocols(protocols: List) =\n apply {\n // Create a private copy of the list.\n val protocolsCopy = protocols.toMutableList()\n\n // Validate that the list has everything we require and nothing we forbid.\n require(Protocol.H2_PRIOR_KNOWLEDGE in protocolsCopy || HTTP_1_1 in protocolsCopy) {\n \"protocols must contain h2_prior_knowledge or http/1.1: $protocolsCopy\"\n }\n require(Protocol.H2_PRIOR_KNOWLEDGE !in protocolsCopy || protocolsCopy.size <= 1) {\n \"protocols containing h2_prior_knowledge cannot use other protocols: $protocolsCopy\"\n }\n require(Protocol.HTTP_1_0 !in protocolsCopy) {\n \"protocols must not contain http/1.0: $protocolsCopy\"\n }\n require(null !in (protocolsCopy as List)) {\n \"protocols must not contain null\"\n }\n\n // Remove protocols that we no longer support.\n @Suppress(\"DEPRECATION\")\n protocolsCopy.remove(Protocol.SPDY_3)\n\n if (protocolsCopy != this.protocols) {\n this.routeDatabase = null\n }\n\n // Assign as an unmodifiable list. This is effectively immutable.\n this.protocols = pr"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":31,"symbol":"Protocol","kind":"enum","lang":"kotlin","doc":"Despite its name, [java.net.URL.getProtocol] returns the [scheme][java.net.URI.getScheme] (http, https, etc.) of the URL, not the protocol (http/1.1, spdy/3.1, etc.). OkHttp uses the word *protocol* to identify how HTTP messages are framed. [ietf_alpn]: http://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg","code":"enum class Protocol(\n private val protocol: String,\n) {\n /**\n * An obsolete plaintext framing that does not use persistent sockets by default.\n */\n HTTP_1_0(\"http/1.0\"),\n\n /**\n * A plaintext framing that includes persistent connections.\n *\n * This version of OkHttp implements [RFC 7230][rfc_7230], and tracks revisions to that spec.\n *\n * [rfc_7230]: https://tools.ietf.org/html/rfc7230\n */\n HTTP_1_1(\"http/1.1\"),\n\n /**\n * Chromium's binary-framed protocol that includes header compression, multiplexing multiple\n * requests on the same socket, and server-push. HTTP/1.1 semantics are layered on SPDY/3.\n *\n * Current versions of OkHttp do not support this protocol.\n */\n @Deprecated(\"OkHttp has dropped support for SPDY. Prefer {@link #HTTP_2}.\")\n SPDY_3(\"spdy/3.1\"),\n\n /**\n * The IETF's binary-framed protocol that includes header compression, multiplexing multiple\n * requests on the same socket, and server-push. HTTP/1.1 semantics are layered on HTTP/2.\n *\n * HTTP/2 requires deployments of HTTP/2 that use TLS 1.2 support\n * [CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256], present in Java 8+ and Android 5+.\n * Servers that enforce this may "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":37,"symbol":"HTTP_1_0","kind":"enum_member","lang":"kotlin","doc":"An obsolete plaintext framing that does not use persistent sockets by default.","code":"HTTP_1_0(\"http/1.0\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":46,"symbol":"HTTP_1_1","kind":"enum_member","lang":"kotlin","doc":"A plaintext framing that includes persistent connections. This version of OkHttp implements [RFC 7230][rfc_7230], and tracks revisions to that spec. [rfc_7230]: https://tools.ietf.org/html/rfc7230","code":"HTTP_1_1(\"http/1.1\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":54,"symbol":"SPDY_3","kind":"enum_member","lang":"kotlin","doc":"Chromium's binary-framed protocol that includes header compression, multiplexing multiple requests on the same socket, and server-push. HTTP/1.1 semantics are layered on SPDY/3. Current versions of OkHttp do not support this protocol.","code":"@Deprecated(\"OkHttp has dropped support for SPDY. Prefer {@link #HTTP_2}.\")\n SPDY_3(\"spdy/3.1\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":66,"symbol":"HTTP_2","kind":"enum_member","lang":"kotlin","doc":"HTTP/2 requires deployments of HTTP/2 that use TLS 1.2 support [CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256], present in Java 8+ and Android 5+. Servers that enforce this may send an exception message including the string `INADEQUATE_SECURITY`.","code":"HTTP_2(\"h2\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":76,"symbol":"H2_PRIOR_KNOWLEDGE","kind":"enum_member","lang":"kotlin","doc":"knowledge that the server supports cleartext HTTP/2. See also [Starting HTTP/2 with Prior Knowledge][rfc_7540_34]. [rfc_7540_34]: https://datatracker.ietf.org/doc/html/rfc7540#autoid-10","code":"H2_PRIOR_KNOWLEDGE(\"h2_prior_knowledge\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":86,"symbol":"QUIC","kind":"enum_member","lang":"kotlin","doc":"designed from the ground up and optimized for HTTP/2 semantics. HTTP/1.1 semantics are layered on HTTP/2. QUIC is not natively supported by OkHttp, but provided to allow a theoretical interceptor that provides support.","code":"QUIC(\"quic\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":95,"symbol":"HTTP_3","kind":"enum_member","lang":"kotlin","doc":"HTTP/3 is the third and upcoming major version of the Hypertext Transfer Protocol used to exchange information. HTTP/3 runs over QUIC, which is published as RFC 9000. HTTP/3 is not natively supported by OkHttp, but provided to allow a theoretical interceptor that provides support.","code":"HTTP_3(\"h3\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":106,"symbol":"toString","kind":"function","lang":"kotlin","doc":"\"h2\". See also [IANA tls-extensiontype-values][iana]. [iana]: https://www.iana.org/assignments/tls-extensiontype-values","code":"override fun toString(): String = protocol"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Protocol.kt","line":114,"symbol":"get","kind":"function","lang":"kotlin","doc":"Returns the protocol identified by `protocol`. @throws IOException if `protocol` is unknown.","code":"@JvmStatic\n @Throws(IOException::class)\n fun get(protocol: String): Protocol {\n // Unroll the loop over values() to save an allocation.\n @Suppress(\"DEPRECATION\")\n return when (protocol) {\n HTTP_1_0.protocol -> {\n HTTP_1_0\n }\n\n HTTP_1_1.protocol -> {\n HTTP_1_1\n }\n\n H2_PRIOR_KNOWLEDGE.protocol -> {\n H2_PRIOR_KNOWLEDGE\n }\n\n HTTP_2.protocol -> {\n HTTP_2\n }\n\n SPDY_3.protocol -> {\n SPDY_3\n }\n\n QUIC.protocol -> {\n QUIC\n }\n\n else -> {\n // Support HTTP3 draft like h3-29\n if (protocol.startsWith(HTTP_3.protocol)) HTTP_3 else throw IOException(\"Unexpected protocol: $protocol\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":34,"symbol":"Request","kind":"class","lang":"kotlin","doc":"An HTTP request. Instances of this class are immutable if their [body] is null or itself immutable.","code":"class Request internal constructor(\n builder: Builder,\n) {\n @get:JvmName(\"url\")\n val url: HttpUrl = checkNotNull(builder.url) { \"url == null\" }\n\n @get:JvmName(\"method\")\n val method: String = builder.method\n\n @get:JvmName(\"headers\")\n val headers: Headers = builder.headers.build()\n\n @get:JvmName(\"body\")\n val body: RequestBody? = builder.body\n\n @get:JvmName(\"cacheUrlOverride\")\n val cacheUrlOverride: HttpUrl? = builder.cacheUrlOverride\n\n internal val tags = builder.tags\n\n private var lazyCacheControl: CacheControl? = null\n\n val isHttps: Boolean\n get() = url.isHttps\n\n /**\n * Constructs a new request.\n *\n * Use [Builder] for more fluent construction, including helper methods for various HTTP methods.\n *\n * @param method defaults to \"GET\" if [body] is null, and \"POST\" otherwise.\n */\n constructor(\n url: HttpUrl,\n headers: Headers = headersOf(),\n // '\\u0000' is a sentinel value that'll choose based on what the body is:\n method: String = \"\\u0000\",\n body: RequestBody? = null,\n ) : this(\n Builder()\n .url(url)\n .headers(headers)\n .method(\n when {\n method != \"\\u0000\" -> method\n body != null -> \"POST\"\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":86,"symbol":"header","kind":"function","lang":"kotlin","code":"fun header(name: String): String? = headers[name]"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":88,"symbol":"headers","kind":"function","lang":"kotlin","code":"fun headers(name: String): List = headers.values(name)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":91,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Returns the tag attached with [T] as a key, or null if no tag is attached with that key.","code":"@JvmName(\"reifiedTag\")\n inline fun tag(): T? = tag(T::class)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":95,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Returns the tag attached with [type] as a key, or null if no tag is attached with that key.","code":"fun tag(type: KClass): T? = type.java.cast(tags[type])"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":107,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Prior to OkHttp 3.11, this method never returned null if no tag was attached. Instead it returned either this request, or the request upon which this request was derived with [newBuilder]. @suppress this method breaks Dokka! https://github.com/Kotlin/dokka/issues/2473","code":"fun tag(): Any? = tag()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":113,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Returns the tag attached with [type] as a key, or null if no tag is attached with that key.","code":"fun tag(type: Class): T? = tag(type.kotlin)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":115,"symbol":"newBuilder","kind":"function","lang":"kotlin","code":"fun newBuilder(): Builder = Builder(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":132,"symbol":"url","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_url\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"url\"),\n level = DeprecationLevel.ERROR,\n )\n fun url(): HttpUrl = url"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":140,"symbol":"method","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_method\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"method\"),\n level = DeprecationLevel.ERROR,\n )\n fun method(): String = method"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":148,"symbol":"headers","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_headers\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"headers\"),\n level = DeprecationLevel.ERROR,\n )\n fun headers(): Headers = headers"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":156,"symbol":"body","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_body\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"body\"),\n level = DeprecationLevel.ERROR,\n )\n fun body(): RequestBody? = body"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":164,"symbol":"cacheControl","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_cacheControl\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"cacheControl\"),\n level = DeprecationLevel.ERROR,\n )\n fun cacheControl(): CacheControl = cacheControl"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":172,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n buildString(32) {\n append(\"Request{method=\")\n append(method)\n append(\", url=\")\n append(url)\n if (headers.size != 0) {\n append(\", headers=[\")\n headers.forEachIndexed { index, (name, value) ->\n if (index > 0) {\n append(\", \")\n }\n append(name)\n append(':')\n append(if (isSensitiveHeader(name)) \"██\" else value)\n }\n append(']')\n }\n if (tags != EmptyTags) {\n append(\", tags=\")\n append(tags)\n }\n append('}')\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":197,"symbol":"Builder","kind":"class","lang":"kotlin","code":"open class Builder {\n internal var url: HttpUrl? = null\n internal var method: String\n internal var headers: Headers.Builder\n internal var body: RequestBody? = null\n internal var cacheUrlOverride: HttpUrl? = null\n internal var tags: Tags = EmptyTags\n\n constructor() {\n this.method = \"GET\"\n this.headers = Headers.Builder()\n }\n\n internal constructor(request: Request) {\n this.url = request.url\n this.method = request.method\n this.body = request.body\n this.tags = request.tags\n this.headers = request.headers.newBuilder()\n this.cacheUrlOverride = request.cacheUrlOverride\n }\n\n open fun url(url: HttpUrl): Builder =\n apply {\n this.url = url\n }\n\n /**\n * Sets the URL target of this request.\n *\n * @throws IllegalArgumentException if [url] is not a valid HTTP or HTTPS URL. Avoid this\n * exception by calling [HttpUrl.parse]; it returns null for invalid URLs.\n */\n open fun url(url: String): Builder = url(canonicalUrl(url).toHttpUrl())\n\n // Silently replace web socket URLs with HTTP URLs.\n private fun canonicalUrl(url: String) =\n when {\n url.startsWith(\"ws:\", ignor"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":219,"symbol":"url","kind":"function","lang":"kotlin","code":"open fun url(url: HttpUrl): Builder =\n apply {\n this.url = url\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":230,"symbol":"url","kind":"function","lang":"kotlin","doc":"Sets the URL target of this request. @throws IllegalArgumentException if [url] is not a valid HTTP or HTTPS URL. Avoid this exception by calling [HttpUrl.parse]; it returns null for invalid URLs.","code":"open fun url(url: String): Builder = url(canonicalUrl(url).toHttpUrl())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":233,"symbol":"canonicalUrl","kind":"function","lang":"kotlin","doc":"Silently replace web socket URLs with HTTP URLs.","code":"private fun canonicalUrl(url: String) =\n when {\n url.startsWith(\"ws:\", ignoreCase = true) -> \"http:${url.substring(3)}\"\n url.startsWith(\"wss:\", ignoreCase = true) -> \"https:${url.substring(4)}\"\n else -> url\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":245,"symbol":"url","kind":"function","lang":"kotlin","doc":"Sets the URL target of this request. @throws IllegalArgumentException if the scheme of [url] is not `http` or `https`.","code":"open fun url(url: URL) = url(url.toString().toHttpUrl())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":251,"symbol":"header","kind":"function","lang":"kotlin","doc":"Sets the header named [name] to [value]. If this request already has any headers with that name, they are all replaced.","code":"open fun header(\n name: String,\n value: String,\n ) = apply {\n headers[name] = value\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":265,"symbol":"addHeader","kind":"function","lang":"kotlin","doc":"Adds a header with [name] and [value]. Prefer this method for multiply-valued headers like \"Cookie\". Note that for some headers including `Content-Length` and `Content-Encoding`, OkHttp may replace [value] with a header derived from the request body.","code":"open fun addHeader(\n name: String,\n value: String,\n ) = apply {\n headers.add(name, value)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":273,"symbol":"removeHeader","kind":"function","lang":"kotlin","doc":"Removes all headers named [name] on this builder.","code":"open fun removeHeader(name: String) =\n apply {\n headers.removeAll(name)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":279,"symbol":"headers","kind":"function","lang":"kotlin","doc":"Removes all headers on this builder and adds [headers].","code":"open fun headers(headers: Headers) =\n apply {\n this.headers = headers.newBuilder()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":289,"symbol":"cacheControl","kind":"function","lang":"kotlin","doc":"Sets this request's `Cache-Control` header, replacing any cache control headers already present. If [cacheControl] doesn't define any directives, this clears this request's cache-control headers.","code":"open fun cacheControl(cacheControl: CacheControl): Builder {\n val value = cacheControl.toString()\n return when {\n value.isEmpty() -> removeHeader(\"Cache-Control\")\n else -> header(\"Cache-Control\", value)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":297,"symbol":"get","kind":"function","lang":"kotlin","code":"open fun get(): Builder = method(\"GET\", null)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":299,"symbol":"head","kind":"function","lang":"kotlin","code":"open fun head(): Builder = method(\"HEAD\", null)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":301,"symbol":"post","kind":"function","lang":"kotlin","code":"open fun post(body: RequestBody): Builder = method(\"POST\", body)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":303,"symbol":"delete","kind":"function","lang":"kotlin","code":"@JvmOverloads\n open fun delete(body: RequestBody? = RequestBody.EMPTY): Builder = method(\"DELETE\", body)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":306,"symbol":"put","kind":"function","lang":"kotlin","code":"open fun put(body: RequestBody): Builder = method(\"PUT\", body)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":308,"symbol":"patch","kind":"function","lang":"kotlin","code":"open fun patch(body: RequestBody): Builder = method(\"PATCH\", body)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":330,"symbol":"query","kind":"function","lang":"kotlin","doc":".cacheUrlOverride(\"https://example.com/query/$hash\".toHttpUrl()) .build() ``` @see cacheUrlOverride","code":"open fun query(body: RequestBody): Builder = method(\"QUERY\", body)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":332,"symbol":"method","kind":"function","lang":"kotlin","code":"open fun method(\n method: String,\n body: RequestBody?,\n ): Builder =\n apply {\n require(method.isNotEmpty()) {\n \"method.isEmpty() == true\"\n }\n if (body == null) {\n require(!HttpMethod.requiresRequestBody(method)) {\n \"method $method must have a request body.\"\n }\n } else {\n require(HttpMethod.permitsRequestBody(method)) {\n \"method $method must not have a request body.\"\n }\n }\n this.method = method\n this.body = body\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":360,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Attaches [tag] to the request using [T] as a key. Tags can be read from a request using [Request.tag]. Use null to remove any existing tag assigned for [T]. Use this API to attach timing, debugging, or other application data to a request so that you may read it in interceptors, event listeners, or callbacks.","code":"@JvmName(\"reifiedTag\")\n inline fun tag(tag: T?): Builder = tag(T::class, tag)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":370,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Attaches [tag] to the request using [type] as a key. Tags can be read from a request using [Request.tag]. Use null to remove any existing tag assigned for [type]. Use this API to attach timing, debugging, or other application data to a request so that you may read it in interceptors, event listeners, or callbacks.","code":"fun tag(\n type: KClass,\n tag: T?,\n ): Builder =\n apply {\n tags = tags.plus(type, tag)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":379,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Attaches [tag] to the request using `Object.class` as a key.","code":"open fun tag(tag: Any?): Builder = tag(Any::class, tag)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":388,"symbol":"tag","kind":"function","lang":"kotlin","doc":"Attaches [tag] to the request using [type] as a key. Tags can be read from a request using [Request.tag]. Use null to remove any existing tag assigned for [type]. Use this API to attach timing, debugging, or other application data to a request so that you may read it in interceptors, event listeners, or callbacks.","code":"open fun tag(\n type: Class,\n tag: T?,\n ) = tag(type.kotlin, tag)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":400,"symbol":"cacheUrlOverride","kind":"function","lang":"kotlin","doc":"Override the [Request.url] for caching, if it is either polluted with transient query params, or has a canonical URL possibly for a CDN. Note that POST requests will not be sent to the server if this URL is set and matches a cached response.","code":"fun cacheUrlOverride(cacheUrlOverride: HttpUrl?) =\n apply {\n this.cacheUrlOverride = cacheUrlOverride\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":417,"symbol":"gzip","kind":"function","lang":"kotlin","doc":"It is an error to call this multiple times on the same instance. @throws IllegalStateException if this request doesn't have a request body, or if it already has a 'Content-Encoding' header.","code":"fun gzip() =\n apply {\n val identityBody =\n body\n ?: throw IllegalStateException(\"cannot gzip a request that has no body\")\n\n val contentEncoding = headers[\"Content-Encoding\"]\n check(contentEncoding == null) {\n \"Content-Encoding already set: $contentEncoding\"\n }\n\n headers.add(\"Content-Encoding\", \"gzip\")\n body = GzipRequestBody(identityBody)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":432,"symbol":"build","kind":"function","lang":"kotlin","code":"open fun build(): Request = Request(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":453,"symbol":"toCurl","kind":"function","lang":"kotlin","doc":"--data '{\\\"key\\\":\\\"value\\\"}' ``` **Note:** This will consume the request body. This may have side effects if the [RequestBody] is streaming or can be consumed only once.","code":"@JvmOverloads\n fun toCurl(includeBody: Boolean = true): String =\n buildString {\n append(\"curl ${url.toString().shellEscape()}\")\n\n val contentType = body?.contentType()?.toString()\n\n // Add method if not the default.\n val defaultMethod =\n when {\n includeBody && body != null -> \"POST\"\n else -> \"GET\"\n }\n if (method != defaultMethod) {\n append(\" \\\\\\n -X ${method.shellEscape()}\")\n }\n\n // Append headers.\n for ((name, value) in headers) {\n if (contentType != null && name.equals(\"Content-Type\", ignoreCase = true)) continue\n append(\" \\\\\\n -H ${\"$name: $value\".shellEscape()}\")\n }\n\n if (contentType != null) {\n append(\" \\\\\\n -H ${\"Content-Type: $contentType\".shellEscape()}\")\n }\n\n // Append body if present.\n if (includeBody && body != null) {\n val bodyBuffer = Buffer()\n body.writeTo(bodyBuffer)\n\n if (bodyBuffer.isProbablyUtf8()) {\n append(\" \\\\\\n --data ${bodyBuffer.readUtf8().shellEscape()}\")\n } else {\n append(\" \\\\\\n --data-binary ${bodyBuffer.readByteString().hex().shellEscape()}\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt","line":493,"symbol":"shellEscape","kind":"function","lang":"kotlin","code":"private fun String.shellEscape(): String = \"'${replace(\"'\", \"'\\\\''\")}'\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":33,"symbol":"RequestBody","kind":"class","lang":"kotlin","code":"abstract class RequestBody {\n /** Returns the Content-Type header for this body. */\n abstract fun contentType(): MediaType?\n\n /**\n * Returns the number of bytes that will be written to sink in a call to [writeTo],\n * or -1 if that count is unknown.\n */\n @Throws(IOException::class)\n open fun contentLength(): Long = -1L\n\n /** Writes the content of this request to [sink]. This should not close [sink]. */\n @Throws(IOException::class)\n abstract fun writeTo(sink: BufferedSink)\n\n /**\n * A duplex request body is special in how it is **transmitted** on the network and\n * in the **API contract** between OkHttp and the application.\n *\n * This method returns false unless it is overridden by a subclass.\n *\n * ### Duplex Transmission\n *\n * With regular HTTP calls the request always completes sending before the response may begin\n * receiving. With duplex the request and response may be interleaved! That is, request body bytes\n * may be sent after response headers or body bytes have been received.\n *\n * Though any call may be initiated as a duplex call, only web servers that are specially\n * designed for this nonstandard interaction will use it. As of 2019"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":35,"symbol":"contentType","kind":"function","lang":"kotlin","doc":"Returns the Content-Type header for this body.","code":"abstract fun contentType(): MediaType?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":41,"symbol":"contentLength","kind":"function","lang":"kotlin","doc":"Returns the number of bytes that will be written to sink in a call to [writeTo], or -1 if that count is unknown.","code":"@Throws(IOException::class)\n open fun contentLength(): Long = -1L"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":45,"symbol":"writeTo","kind":"function","lang":"kotlin","doc":"Writes the content of this request to [sink]. This should not close [sink].","code":"@Throws(IOException::class)\n abstract fun writeTo(sink: BufferedSink)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":80,"symbol":"isDuplex","kind":"function","lang":"kotlin","doc":"reads of the [ResponseBody]. For duplex request bodies, [writeTo] should return quickly, possibly by handing off the provided request body to another thread to perform writing. [grpc]: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md","code":"open fun isDuplex(): Boolean = false"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":99,"symbol":"isOneShot","kind":"function","lang":"kotlin","doc":"has since been closed by the server. * A client timeout (HTTP 408). * A authorization challenge (HTTP 401 and 407) that is satisfied by the [Authenticator]. * A retryable server failure (HTTP 503 with a `Retry-After: 0` response header). * A misdirected request (HTTP 421) on a coalesced connection.","code":"open fun isOneShot(): Boolean = false"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":104,"symbol":"sha256","kind":"function","lang":"kotlin","doc":"Returns the SHA-256 hash of this [RequestBody]","code":"@Throws(IOException::class)\n fun sha256(): ByteString {\n val hashingSink = HashingSink.sha256(blackholeSink())\n hashingSink.buffer().use {\n this.writeTo(it)\n }\n return hashingSink.hash\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":122,"symbol":"toRequestBody","kind":"function","lang":"kotlin","doc":"Returns a new request body that transmits this string. If [contentType] is non-null and lacks a charset, this will use UTF-8.","code":"@JvmStatic\n @JvmName(\"create\")\n fun String.toRequestBody(contentType: MediaType? = null): RequestBody {\n val (charset, finalContentType) = contentType.chooseCharset()\n val bytes = toByteArray(charset)\n return bytes.toRequestBody(finalContentType, 0, bytes.size)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":130,"symbol":"toRequestBody","kind":"function","lang":"kotlin","code":"@JvmStatic\n @JvmName(\"create\")\n fun ByteString.toRequestBody(contentType: MediaType? = null): RequestBody =\n object : RequestBody() {\n override fun contentType() = contentType\n\n override fun contentLength() = size.toLong()\n\n override fun writeTo(sink: BufferedSink) {\n sink.write(this@toRequestBody)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":134,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = contentType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":136,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = size.toLong()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":138,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.write(this@toRequestBody)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":144,"symbol":"toRequestBody","kind":"function","lang":"kotlin","doc":"Returns a new request body that transmits this.","code":"@JvmStatic\n @JvmName(\"create\")\n fun FileDescriptor.toRequestBody(contentType: MediaType? = null): RequestBody =\n object : RequestBody() {\n override fun contentType() = contentType\n\n override fun isOneShot(): Boolean = true\n\n override fun writeTo(sink: BufferedSink) {\n FileInputStream(this@toRequestBody).use {\n sink.buffer.writeAll(it.source())\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":148,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = contentType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":150,"symbol":"isOneShot","kind":"function","lang":"kotlin","code":"override fun isOneShot(): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":152,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n FileInputStream(this@toRequestBody).use {\n sink.buffer.writeAll(it.source())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":160,"symbol":"toRequestBody","kind":"function","lang":"kotlin","doc":"Returns a new request body that transmits this.","code":"@JvmOverloads\n @JvmStatic\n @JvmName(\"create\")\n fun ByteArray.toRequestBody(\n contentType: MediaType? = null,\n offset: Int = 0,\n byteCount: Int = size,\n ): RequestBody {\n checkOffsetAndCount(size.toLong(), offset.toLong(), byteCount.toLong())\n return object : RequestBody() {\n override fun contentType() = contentType\n\n override fun contentLength() = byteCount.toLong()\n\n override fun writeTo(sink: BufferedSink) {\n sink.write(this@toRequestBody, offset, byteCount)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":170,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = contentType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":172,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = byteCount.toLong()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":174,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.write(this@toRequestBody, offset, byteCount)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":181,"symbol":"asRequestBody","kind":"function","lang":"kotlin","doc":"Returns a new request body that transmits the content of this.","code":"@JvmStatic\n @JvmName(\"create\")\n fun File.asRequestBody(contentType: MediaType? = null): RequestBody =\n object : RequestBody() {\n override fun contentType() = contentType\n\n override fun contentLength() = length()\n\n override fun writeTo(sink: BufferedSink) {\n source().use { source -> sink.writeAll(source) }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":185,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = contentType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":187,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = length()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":189,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n source().use { source -> sink.writeAll(source) }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":195,"symbol":"asRequestBody","kind":"function","lang":"kotlin","doc":"Returns a new request body that transmits the content of this.","code":"@JvmStatic\n @JvmName(\"create\")\n fun Path.asRequestBody(\n fileSystem: FileSystem,\n contentType: MediaType? = null,\n ): RequestBody =\n object : RequestBody() {\n override fun contentType() = contentType\n\n override fun contentLength() = fileSystem.metadata(this@asRequestBody).size ?: -1\n\n override fun writeTo(sink: BufferedSink) {\n fileSystem.source(this@asRequestBody).use { source -> sink.writeAll(source) }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":202,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = contentType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":204,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = fileSystem.metadata(this@asRequestBody).size ?: -1"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":206,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n fileSystem.source(this@asRequestBody).use { source -> sink.writeAll(source) }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":211,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n @Deprecated(\n message = \"Moved to extension function. Put the 'content' argument first to fix Java\",\n replaceWith =\n ReplaceWith(\n expression = \"content.toRequestBody(contentType)\",\n imports = [\"okhttp3.RequestBody.Companion.toRequestBody\"],\n ),\n level = DeprecationLevel.WARNING,\n )\n fun create(\n contentType: MediaType?,\n content: String,\n ): RequestBody = content.toRequestBody(contentType)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":226,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n @Deprecated(\n message = \"Moved to extension function. Put the 'content' argument first to fix Java\",\n replaceWith =\n ReplaceWith(\n expression = \"content.toRequestBody(contentType)\",\n imports = [\"okhttp3.RequestBody.Companion.toRequestBody\"],\n ),\n level = DeprecationLevel.WARNING,\n )\n fun create(\n contentType: MediaType?,\n content: ByteString,\n ): RequestBody = content.toRequestBody(contentType)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":241,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmOverloads\n @JvmStatic\n @Deprecated(\n message = \"Moved to extension function. Put the 'content' argument first to fix Java\",\n replaceWith =\n ReplaceWith(\n expression = \"content.toRequestBody(contentType, offset, byteCount)\",\n imports = [\"okhttp3.RequestBody.Companion.toRequestBody\"],\n ),\n level = DeprecationLevel.WARNING,\n )\n fun create(\n contentType: MediaType?,\n content: ByteArray,\n offset: Int = 0,\n byteCount: Int = content.size,\n ): RequestBody = content.toRequestBody(contentType, offset, byteCount)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/RequestBody.kt","line":259,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n @Deprecated(\n message = \"Moved to extension function. Put the 'file' argument first to fix Java\",\n replaceWith =\n ReplaceWith(\n expression = \"file.asRequestBody(contentType)\",\n imports = [\"okhttp3.RequestBody.Companion.asRequestBody\"],\n ),\n level = DeprecationLevel.WARNING,\n )\n fun create(\n contentType: MediaType?,\n file: File,\n ): RequestBody = file.asRequestBody(contentType)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":41,"symbol":"Response","kind":"class","lang":"kotlin","doc":"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.","code":"class Response internal constructor(\n /**\n * The request that initiated this HTTP response. This is not necessarily the same request issued\n * by the application:\n *\n * * It may be transformed by the user's interceptors. For example, an application interceptor\n * may add headers like `User-Agent`.\n * * It may be the request generated in response to an HTTP redirect or authentication\n * challenge. In this case the request URL may be different than the initial request URL.\n *\n * Use the `request` of the [networkResponse] field to get the wire-level request that was\n * transmitted. In the case of follow-ups and redirects, also look at the `request` of the\n * [priorResponse] objects, which have its own [priorResponse].\n */\n @get:JvmName(\"request\") val request: Request,\n /** Returns the HTTP protocol, such as [Protocol.HTTP_1_1] or [Protocol.HTTP_1_0]. */\n @get:JvmName(\"protocol\") val protocol: Protocol,\n /** Returns the HTTP status message. */\n @get:JvmName(\"message\") val message: String,\n /** Returns the HTTP status code. */\n @get:JvmName(\"code\") val code: Int,\n /**\n * Returns the TLS handshake of the connection that carried this response, or nul"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":121,"symbol":"request","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_request\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"request\"),\n level = DeprecationLevel.ERROR,\n )\n fun request(): Request = request"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":129,"symbol":"protocol","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_protocol\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"protocol\"),\n level = DeprecationLevel.ERROR,\n )\n fun protocol(): Protocol = protocol"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":137,"symbol":"code","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_code\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"code\"),\n level = DeprecationLevel.ERROR,\n )\n fun code(): Int = code"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":151,"symbol":"message","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_message\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"message\"),\n level = DeprecationLevel.ERROR,\n )\n fun message(): String = message"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":159,"symbol":"handshake","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_handshake\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"handshake\"),\n level = DeprecationLevel.ERROR,\n )\n fun handshake(): Handshake? = handshake"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":167,"symbol":"headers","kind":"function","lang":"kotlin","code":"fun headers(name: String): List = headers.values(name)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":169,"symbol":"header","kind":"function","lang":"kotlin","code":"@JvmOverloads\n fun header(\n name: String,\n defaultValue: String? = null,\n ): String? = headers[name] ?: defaultValue"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":175,"symbol":"headers","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_headers\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"headers\"),\n level = DeprecationLevel.ERROR,\n )\n fun headers(): Headers = headers"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":197,"symbol":"trailers","kind":"function","lang":"kotlin","doc":"If [Call.cancel] is called while this is blocking, this call will immediately throw. @throws IllegalStateException if the response is closed. @throws IOException if the trailers cannot be loaded, such as if the network connection is dropped.","code":"@Throws(IOException::class)\n fun trailers(): Headers = trailersSource.get()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":217,"symbol":"peekTrailers","kind":"function","lang":"kotlin","doc":"It is not safe to call this concurrently with code that is processing the response body. @throws IOException if the trailers cannot be loaded, such as if the network connection is dropped.","code":"@Throws(IOException::class)\n fun peekTrailers(): Headers? = trailersSource.peek()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":231,"symbol":"peekBody","kind":"function","lang":"kotlin","doc":"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.","code":"@Throws(IOException::class)\n fun peekBody(byteCount: Long): ResponseBody {\n val peeked = body.source().peek()\n val buffer = Buffer()\n peeked.request(byteCount)\n buffer.write(peeked, minOf(byteCount, peeked.buffer.size))\n return buffer.asResponseBody(body.contentType(), buffer.size)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":240,"symbol":"body","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_body\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"body\"),\n level = DeprecationLevel.ERROR,\n )\n fun body() = body"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":248,"symbol":"newBuilder","kind":"function","lang":"kotlin","code":"fun newBuilder(): Builder = Builder(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":257,"symbol":"networkResponse","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_networkResponse\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"networkResponse\"),\n level = DeprecationLevel.ERROR,\n )\n fun networkResponse(): Response? = networkResponse"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":265,"symbol":"cacheResponse","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_cacheResponse\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"cacheResponse\"),\n level = DeprecationLevel.ERROR,\n )\n fun cacheResponse(): Response? = cacheResponse"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":273,"symbol":"priorResponse","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_priorResponse\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"priorResponse\"),\n level = DeprecationLevel.ERROR,\n )\n fun priorResponse(): Response? = priorResponse"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":292,"symbol":"challenges","kind":"function","lang":"kotlin","doc":"If a challenge uses the `token68` variant instead of auth params, there is exactly one auth param in the challenge at key null. Invalid headers and challenges are ignored. No semantic validation is done, for example that `Basic` auth must have a `realm` auth param, this is up to the caller that interprets these challenges.","code":"fun challenges(): List {\n return headers.parseChallenges(\n when (code) {\n HTTP_UNAUTHORIZED -> \"WWW-Authenticate\"\n HTTP_PROXY_AUTH -> \"Proxy-Authenticate\"\n else -> return emptyList()\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":317,"symbol":"cacheControl","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_cacheControl\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"cacheControl\"),\n level = DeprecationLevel.ERROR,\n )\n fun cacheControl(): CacheControl = cacheControl"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":325,"symbol":"sentRequestAtMillis","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_sentRequestAtMillis\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"sentRequestAtMillis\"),\n level = DeprecationLevel.ERROR,\n )\n fun sentRequestAtMillis(): Long = sentRequestAtMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":333,"symbol":"receivedResponseAtMillis","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_receivedResponseAtMillis\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"receivedResponseAtMillis\"),\n level = DeprecationLevel.ERROR,\n )\n fun receivedResponseAtMillis(): Long = receivedResponseAtMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":347,"symbol":"close","kind":"function","lang":"kotlin","doc":"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].","code":"override fun close() {\n body.close()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":351,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"Response{protocol=$protocol, code=$code, message=$message, url=${request.url}}\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":353,"symbol":"Builder","kind":"class","lang":"kotlin","code":"open class Builder {\n internal var request: Request? = null\n internal var protocol: Protocol? = null\n internal var code = -1\n internal var message: String? = null\n internal var handshake: Handshake? = null\n internal var headers: Headers.Builder\n internal var body: ResponseBody = ResponseBody.EMPTY\n internal var socket: Socket? = null\n internal var networkResponse: Response? = null\n internal var cacheResponse: Response? = null\n internal var priorResponse: Response? = null\n internal var sentRequestAtMillis: Long = 0\n internal var receivedResponseAtMillis: Long = 0\n internal var exchange: Exchange? = null\n internal var trailersSource: TrailersSource = TrailersSource.EMPTY\n\n constructor() {\n headers = Headers.Builder()\n }\n\n internal constructor(response: Response) {\n this.request = response.request\n this.protocol = response.protocol\n this.code = response.code\n this.message = response.message\n this.handshake = response.handshake\n this.headers = response.headers.newBuilder()\n this.body = response.body\n this.socket = response.socket\n this.networkResponse = response.networkResponse\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":392,"symbol":"request","kind":"function","lang":"kotlin","code":"open fun request(request: Request) =\n apply {\n this.request = request\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":397,"symbol":"protocol","kind":"function","lang":"kotlin","code":"open fun protocol(protocol: Protocol) =\n apply {\n this.protocol = protocol\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":402,"symbol":"code","kind":"function","lang":"kotlin","code":"open fun code(code: Int) =\n apply {\n this.code = code\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":407,"symbol":"message","kind":"function","lang":"kotlin","code":"open fun message(message: String) =\n apply {\n this.message = message\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":412,"symbol":"handshake","kind":"function","lang":"kotlin","code":"open fun handshake(handshake: Handshake?) =\n apply {\n this.handshake = handshake\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":421,"symbol":"header","kind":"function","lang":"kotlin","doc":"Sets the header named [name] to [value]. If this request already has any headers with that name, they are all replaced.","code":"open fun header(\n name: String,\n value: String,\n ) = apply {\n headers[name] = value\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":432,"symbol":"addHeader","kind":"function","lang":"kotlin","doc":"Adds a header with [name] to [value]. Prefer this method for multiply-valued headers like \"Set-Cookie\".","code":"open fun addHeader(\n name: String,\n value: String,\n ) = apply {\n headers.add(name, value)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":440,"symbol":"removeHeader","kind":"function","lang":"kotlin","doc":"Removes all headers named [name] on this builder.","code":"open fun removeHeader(name: String) =\n apply {\n headers.removeAll(name)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":446,"symbol":"headers","kind":"function","lang":"kotlin","doc":"Removes all headers on this builder and adds [headers].","code":"open fun headers(headers: Headers) =\n apply {\n this.headers = headers.newBuilder()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":451,"symbol":"body","kind":"function","lang":"kotlin","code":"open fun body(body: ResponseBody) =\n apply {\n this.body = body\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":456,"symbol":"socket","kind":"function","lang":"kotlin","code":"open fun socket(socket: Socket) =\n apply {\n this.socket = socket\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":461,"symbol":"networkResponse","kind":"function","lang":"kotlin","code":"open fun networkResponse(networkResponse: Response?) =\n apply {\n checkSupportResponse(\"networkResponse\", networkResponse)\n this.networkResponse = networkResponse\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":467,"symbol":"cacheResponse","kind":"function","lang":"kotlin","code":"open fun cacheResponse(cacheResponse: Response?) =\n apply {\n checkSupportResponse(\"cacheResponse\", cacheResponse)\n this.cacheResponse = cacheResponse\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":473,"symbol":"checkSupportResponse","kind":"function","lang":"kotlin","code":"private fun checkSupportResponse(\n name: String,\n response: Response?,\n ) {\n response?.apply {\n require(networkResponse == null) { \"$name.networkResponse != null\" }\n require(cacheResponse == null) { \"$name.cacheResponse != null\" }\n require(priorResponse == null) { \"$name.priorResponse != null\" }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":484,"symbol":"priorResponse","kind":"function","lang":"kotlin","code":"open fun priorResponse(priorResponse: Response?) =\n apply {\n this.priorResponse = priorResponse\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":489,"symbol":"trailers","kind":"function","lang":"kotlin","code":"open fun trailers(trailersSource: TrailersSource): Builder =\n apply {\n this.trailersSource = trailersSource\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":494,"symbol":"sentRequestAtMillis","kind":"function","lang":"kotlin","code":"open fun sentRequestAtMillis(sentRequestAtMillis: Long) =\n apply {\n this.sentRequestAtMillis = sentRequestAtMillis\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":499,"symbol":"receivedResponseAtMillis","kind":"function","lang":"kotlin","code":"open fun receivedResponseAtMillis(receivedResponseAtMillis: Long) =\n apply {\n this.receivedResponseAtMillis = receivedResponseAtMillis\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":504,"symbol":"initExchange","kind":"function","lang":"kotlin","code":"internal fun initExchange(exchange: Exchange) {\n this.exchange = exchange\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Response.kt","line":508,"symbol":"build","kind":"function","lang":"kotlin","code":"open fun build(): Response {\n check(code >= 0) { \"code < 0: $code\" }\n return Response(\n checkNotNull(request) { \"request == null\" },\n checkNotNull(protocol) { \"protocol == null\" },\n checkNotNull(message) { \"message == null\" },\n code,\n handshake,\n headers.build(),\n body,\n socket,\n networkResponse,\n cacheResponse,\n priorResponse,\n sentRequestAtMillis,\n receivedResponseAtMillis,\n exchange,\n trailersSource,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":101,"symbol":"ResponseBody","kind":"class","lang":"kotlin","doc":"common requirement for video streaming applications. Because this class does not buffer the full response in memory, the application may not re-read the bytes of the response. Use this one shot to read the entire response into memory with [bytes] or [string]. Or stream the response with either [source], [byteStream], or [charStream].","code":"abstract class ResponseBody : Closeable {\n /** Multiple calls to [charStream] must return the same instance. */\n private var reader: Reader? = null\n\n abstract fun contentType(): MediaType?\n\n /**\n * Returns the number of bytes in that will returned by [bytes], or [byteStream], or -1 if\n * unknown.\n */\n abstract fun contentLength(): Long\n\n fun byteStream(): InputStream = source().inputStream()\n\n abstract fun source(): BufferedSource\n\n /**\n * Returns the response as a byte array.\n *\n * This method loads entire response body into memory. If the response body is very large this\n * may trigger an [OutOfMemoryError]. Prefer to stream the response body if this is a\n * possibility for your response.\n */\n @Throws(IOException::class)\n fun bytes() = consumeSource(BufferedSource::readByteArray) { it.size }\n\n /**\n * Returns the response as a [ByteString].\n *\n * This method loads entire response body into memory. If the response body is very large this\n * may trigger an [OutOfMemoryError]. Prefer to stream the response body if this is a\n * possibility for your response.\n */\n @Throws(IOException::class)\n fun byteString() = consumeSource(BufferedSource::re"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":105,"symbol":"contentType","kind":"function","lang":"kotlin","code":"abstract fun contentType(): MediaType?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":111,"symbol":"contentLength","kind":"function","lang":"kotlin","doc":"Returns the number of bytes in that will returned by [bytes], or [byteStream], or -1 if unknown.","code":"abstract fun contentLength(): Long"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":113,"symbol":"byteStream","kind":"function","lang":"kotlin","code":"fun byteStream(): InputStream = source().inputStream()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":115,"symbol":"source","kind":"function","lang":"kotlin","code":"abstract fun source(): BufferedSource"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":124,"symbol":"bytes","kind":"function","lang":"kotlin","doc":"Returns the response as a byte array. This method loads entire response body into memory. If the response body is very large this may trigger an [OutOfMemoryError]. Prefer to stream the response body if this is a possibility for your response.","code":"@Throws(IOException::class)\n fun bytes() = consumeSource(BufferedSource::readByteArray) { it.size }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":134,"symbol":"byteString","kind":"function","lang":"kotlin","doc":"Returns the response as a [ByteString]. This method loads entire response body into memory. If the response body is very large this may trigger an [OutOfMemoryError]. Prefer to stream the response body if this is a possibility for your response.","code":"@Throws(IOException::class)\n fun byteString() = consumeSource(BufferedSource::readByteString) { it.size }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":137,"symbol":"consumeSource","kind":"function","lang":"kotlin","code":"private inline fun ResponseBody.consumeSource(\n consumer: (BufferedSource) -> T,\n sizeMapper: (T) -> Int,\n ): T {\n val contentLength = contentLength()\n if (contentLength > Int.MAX_VALUE) {\n throw IOException(\"Cannot buffer entire body for content length: $contentLength\")\n }\n\n val bytes = source().use(consumer)\n val size = sizeMapper(bytes)\n if (contentLength != -1L && contentLength != size.toLong()) {\n throw IOException(\"Content-Length ($contentLength) and stream length ($size) disagree\")\n }\n return bytes\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":166,"symbol":"charStream","kind":"function","lang":"kotlin","doc":"Otherwise if the response has a `Content-Type` header that specifies a charset, that is used to determine the charset of the response bytes. Otherwise the response bytes are decoded as UTF-8.","code":"fun charStream(): Reader =\n reader ?: BomAwareReader(source(), charset()).also {\n reader = it\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":187,"symbol":"string","kind":"function","lang":"kotlin","doc":"Otherwise the response bytes are decoded as UTF-8. This method loads entire response body into memory. If the response body is very large this may trigger an [OutOfMemoryError]. Prefer to stream the response body if this is a possibility for your response.","code":"@Throws(IOException::class)\n fun string(): String =\n source().use { source ->\n source.readString(charset = source.readBomAsCharset(charset()))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":193,"symbol":"charset","kind":"function","lang":"kotlin","code":"private fun charset() = contentType().charsetOrUtf8()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":195,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() = source().closeQuietly()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":197,"symbol":"BomAwareReader","kind":"class","lang":"kotlin","code":"internal class BomAwareReader(\n private val source: BufferedSource,\n private val charset: Charset,\n ) : Reader() {\n private var closed: Boolean = false\n private var delegate: Reader? = null\n\n @Throws(IOException::class)\n override fun read(\n cbuf: CharArray,\n off: Int,\n len: Int,\n ): Int {\n if (closed) throw IOException(\"Stream closed\")\n\n val finalDelegate =\n delegate ?: InputStreamReader(\n source.inputStream(),\n source.readBomAsCharset(charset),\n ).also {\n delegate = it\n }\n return finalDelegate.read(cbuf, off, len)\n }\n\n @Throws(IOException::class)\n override fun close() {\n closed = true\n delegate?.close() ?: run { source.close() }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":204,"symbol":"read","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun read(\n cbuf: CharArray,\n off: Int,\n len: Int,\n ): Int {\n if (closed) throw IOException(\"Stream closed\")\n\n val finalDelegate =\n delegate ?: InputStreamReader(\n source.inputStream(),\n source.readBomAsCharset(charset),\n ).also {\n delegate = it\n }\n return finalDelegate.read(cbuf, off, len)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":222,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n closed = true\n delegate?.close() ?: run { source.close() }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":242,"symbol":"toResponseBody","kind":"function","lang":"kotlin","doc":"has a charset other than utf-8 the behaviour differs by platform. On the JVM the encoding will be used instead of utf-8. On non JVM platforms, this method will fail for encodings other than utf-8.","code":"@JvmStatic\n @JvmName(\"create\")\n fun String.toResponseBody(contentType: MediaType? = null): ResponseBody {\n val (charset, finalContentType) = contentType.chooseCharset()\n val buffer = Buffer().writeString(this, charset)\n return buffer.asResponseBody(finalContentType, buffer.size)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":251,"symbol":"toResponseBody","kind":"function","lang":"kotlin","doc":"Returns a new response body that transmits this byte array.","code":"@JvmStatic\n @JvmName(\"create\")\n fun ByteArray.toResponseBody(contentType: MediaType? = null): ResponseBody =\n Buffer()\n .write(this)\n .asResponseBody(contentType, size.toLong())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":259,"symbol":"toResponseBody","kind":"function","lang":"kotlin","doc":"Returns a new response body that transmits this byte string.","code":"@JvmStatic\n @JvmName(\"create\")\n fun ByteString.toResponseBody(contentType: MediaType? = null): ResponseBody =\n Buffer()\n .write(this)\n .asResponseBody(contentType, size.toLong())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":267,"symbol":"asResponseBody","kind":"function","lang":"kotlin","doc":"Returns a new response body that transmits this source.","code":"@JvmStatic\n @JvmName(\"create\")\n fun BufferedSource.asResponseBody(\n contentType: MediaType? = null,\n contentLength: Long = -1L,\n ): ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = contentType\n\n override fun contentLength(): Long = contentLength\n\n override fun source(): BufferedSource = this@asResponseBody\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":274,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = contentType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":276,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = contentLength"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":278,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource = this@asResponseBody"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":281,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n @Deprecated(\n message = \"Moved to extension function. Put the 'content' argument first to fix Java\",\n replaceWith =\n ReplaceWith(\n expression = \"content.toResponseBody(contentType)\",\n imports = [\"okhttp3.ResponseBody.Companion.toResponseBody\"],\n ),\n level = DeprecationLevel.WARNING,\n )\n fun create(\n contentType: MediaType?,\n content: String,\n ): ResponseBody = content.toResponseBody(contentType)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":296,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n @Deprecated(\n message = \"Moved to extension function. Put the 'content' argument first to fix Java\",\n replaceWith =\n ReplaceWith(\n expression = \"content.toResponseBody(contentType)\",\n imports = [\"okhttp3.ResponseBody.Companion.toResponseBody\"],\n ),\n level = DeprecationLevel.WARNING,\n )\n fun create(\n contentType: MediaType?,\n content: ByteArray,\n ): ResponseBody = content.toResponseBody(contentType)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":311,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n @Deprecated(\n message = \"Moved to extension function. Put the 'content' argument first to fix Java\",\n replaceWith =\n ReplaceWith(\n expression = \"content.toResponseBody(contentType)\",\n imports = [\"okhttp3.ResponseBody.Companion.toResponseBody\"],\n ),\n level = DeprecationLevel.WARNING,\n )\n fun create(\n contentType: MediaType?,\n content: ByteString,\n ): ResponseBody = content.toResponseBody(contentType)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/ResponseBody.kt","line":326,"symbol":"create","kind":"function","lang":"kotlin","code":"@JvmStatic\n @Deprecated(\n message = \"Moved to extension function. Put the 'content' argument first to fix Java\",\n replaceWith =\n ReplaceWith(\n expression = \"content.asResponseBody(contentType, contentLength)\",\n imports = [\"okhttp3.ResponseBody.Companion.asResponseBody\"],\n ),\n level = DeprecationLevel.WARNING,\n )\n fun create(\n contentType: MediaType?,\n contentLength: Long,\n content: BufferedSource,\n ): ResponseBody = content.asResponseBody(contentType, contentLength)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Route.kt","line":34,"symbol":"Route","kind":"class","lang":"kotlin","doc":"[proxy selector][java.net.ProxySelector] is used. It may return multiple proxies to attempt. * **IP address:** whether connecting directly to an origin server or a proxy, opening a socket requires an IP address. The DNS server may return multiple IP addresses to attempt. Each route is a specific selection of these options.","code":"class Route(\n @get:JvmName(\"address\") val address: Address,\n /**\n * Returns the [Proxy] of this route.\n *\n * **Warning:** This may disagree with [Address.proxy] when it is null. When the address's proxy\n * is null, the proxy selector is used.\n */\n @get:JvmName(\"proxy\") val proxy: Proxy,\n @get:JvmName(\"socketAddress\") val socketAddress: InetSocketAddress,\n @get:JvmName(\"echConfigList\") val echConfigList: ByteString?,\n) {\n constructor(\n address: Address,\n proxy: Proxy,\n socketAddress: InetSocketAddress,\n ) : this(address, proxy, socketAddress, null)\n\n @JvmName(\"-deprecated_address\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"address\"),\n level = DeprecationLevel.ERROR,\n )\n fun address(): Address = address\n\n @JvmName(\"-deprecated_proxy\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"proxy\"),\n level = DeprecationLevel.ERROR,\n )\n fun proxy(): Proxy = proxy\n\n @JvmName(\"-deprecated_socketAddress\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"socketAddress\"),\n level = DeprecationLevel.ERROR,\n )\n fun socketAddress(): "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Route.kt","line":52,"symbol":"address","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_address\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"address\"),\n level = DeprecationLevel.ERROR,\n )\n fun address(): Address = address"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Route.kt","line":60,"symbol":"proxy","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_proxy\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"proxy\"),\n level = DeprecationLevel.ERROR,\n )\n fun proxy(): Proxy = proxy"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Route.kt","line":68,"symbol":"socketAddress","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_socketAddress\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"socketAddress\"),\n level = DeprecationLevel.ERROR,\n )\n fun socketAddress(): InetSocketAddress = socketAddress"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Route.kt","line":82,"symbol":"requiresTunnel","kind":"function","lang":"kotlin","doc":"Returns true if this route tunnels HTTPS or HTTP/2 through an HTTP proxy. See [RFC 2817, Section 5.2][rfc_2817]. [rfc_2817]: http://www.ietf.org/rfc/rfc2817.txt","code":"fun requiresTunnel(): Boolean {\n if (proxy.type() != Proxy.Type.HTTP) return false\n return (address.sslSocketFactory != null) ||\n (Protocol.H2_PRIOR_KNOWLEDGE in address.protocols)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Route.kt","line":88,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other is Route &&\n other.address == address &&\n other.proxy == proxy &&\n other.socketAddress == socketAddress &&\n other.echConfigList == echConfigList"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Route.kt","line":95,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int {\n var result = 17\n result = 31 * result + address.hashCode()\n result = 31 * result + proxy.hashCode()\n result = 31 * result + socketAddress.hashCode()\n result = 31 * result + echConfigList.hashCode()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/Route.kt","line":112,"symbol":"toString","kind":"function","lang":"kotlin","doc":"* `example.com:80 at 1.2.3.4:8888` * `example.com:443 via proxy [::1]:8888` This omits duplicate information when possible.","code":"override fun toString(): String =\n buildString {\n val addressHostname = address.url.host // Already in canonical form.\n val socketHostname = socketAddress.address?.hostAddress?.toCanonicalHost()\n\n when {\n ':' in addressHostname -> append(\"[\").append(addressHostname).append(\"]\")\n else -> append(addressHostname)\n }\n if (address.url.port != socketAddress.port || addressHostname == socketHostname) {\n append(\":\")\n append(address.url.port)\n }\n\n if (addressHostname != socketHostname) {\n when (proxy) {\n Proxy.NO_PROXY -> append(\" at \")\n else -> append(\" via proxy \")\n }\n\n when {\n socketHostname == null -> append(\"\")\n ':' in socketHostname -> append(\"[\").append(socketHostname).append(\"]\")\n else -> append(socketHostname)\n }\n append(\":\")\n append(socketAddress.port)\n }\n\n if (echConfigList != null) {\n append(\" with ECH\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TlsVersion.kt","line":22,"symbol":"TlsVersion","kind":"enum","lang":"kotlin","doc":"Versions of TLS that can be offered when negotiating a secure socket. See [javax.net.ssl.SSLSocket.setEnabledProtocols].","code":"enum class TlsVersion(\n @get:JvmName(\"javaName\") val javaName: String,\n) {\n TLS_1_3(\"TLSv1.3\"), // 2016.\n TLS_1_2(\"TLSv1.2\"), // 2008.\n TLS_1_1(\"TLSv1.1\"), // 2006.\n TLS_1_0(\"TLSv1\"), // 1999.\n SSL_3_0(\"SSLv3\"), // 1996.\n ;\n\n @JvmName(\"-deprecated_javaName\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"javaName\"),\n level = DeprecationLevel.ERROR,\n )\n fun javaName(): String = javaName\n\n companion object {\n @JvmStatic\n fun forJavaName(javaName: String): TlsVersion =\n when (javaName) {\n \"TLSv1.3\" -> TLS_1_3\n \"TLSv1.2\" -> TLS_1_2\n \"TLSv1.1\" -> TLS_1_1\n \"TLSv1\" -> TLS_1_0\n \"SSLv3\" -> SSL_3_0\n else -> throw IllegalArgumentException(\"Unexpected TLS version: $javaName\")\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TlsVersion.kt","line":25,"symbol":"TLS_1_3","kind":"enum_member","lang":"kotlin","code":"TLS_1_3(\"TLSv1.3\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TlsVersion.kt","line":26,"symbol":"TLS_1_2","kind":"enum_member","lang":"kotlin","code":"TLS_1_2(\"TLSv1.2\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TlsVersion.kt","line":27,"symbol":"TLS_1_1","kind":"enum_member","lang":"kotlin","code":"TLS_1_1(\"TLSv1.1\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TlsVersion.kt","line":28,"symbol":"TLS_1_0","kind":"enum_member","lang":"kotlin","code":"TLS_1_0(\"TLSv1\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TlsVersion.kt","line":29,"symbol":"SSL_3_0","kind":"enum_member","lang":"kotlin","code":"SSL_3_0(\"SSLv3\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TlsVersion.kt","line":32,"symbol":"javaName","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_javaName\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"javaName\"),\n level = DeprecationLevel.ERROR,\n )\n fun javaName(): String = javaName"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TlsVersion.kt","line":41,"symbol":"forJavaName","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun forJavaName(javaName: String): TlsVersion =\n when (javaName) {\n \"TLSv1.3\" -> TLS_1_3\n \"TLSv1.2\" -> TLS_1_2\n \"TLSv1.1\" -> TLS_1_1\n \"TLSv1\" -> TLS_1_0\n \"SSLv3\" -> SSL_3_0\n else -> throw IllegalArgumentException(\"Unexpected TLS version: $javaName\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TrailersSource.kt","line":30,"symbol":"TrailersSource","kind":"interface","lang":"kotlin","doc":"Most callers won't need this interface, and should use [Response.trailers] instead. This interface is for test and production code that creates [Response] instances without making an HTTP call to a remote server.","code":"interface TrailersSource {\n @Throws(IOException::class)\n fun peek(): Headers? = null\n\n @Throws(IOException::class)\n fun get(): Headers\n\n companion object {\n @JvmField\n val EMPTY: TrailersSource =\n object : TrailersSource {\n override fun peek() = Headers.EMPTY\n\n override fun get() = Headers.EMPTY\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TrailersSource.kt","line":31,"symbol":"peek","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun peek(): Headers? = null"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TrailersSource.kt","line":34,"symbol":"get","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun get(): Headers"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TrailersSource.kt","line":41,"symbol":"peek","kind":"function","lang":"kotlin","code":"override fun peek() = Headers.EMPTY"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/TrailersSource.kt","line":43,"symbol":"get","kind":"function","lang":"kotlin","code":"override fun get() = Headers.EMPTY"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":63,"symbol":"WebSocket","kind":"interface","lang":"kotlin","doc":"thrown and no [WebSocketListener.onFailure] callback is triggered, so callers should always check the return value of `send()`. Use [queueSize] to monitor backpressure before sending. For large payloads, consider breaking them into smaller messages or using HTTP requests instead.","code":"interface WebSocket {\n /** Returns the original request that initiated this web socket. */\n fun request(): Request\n\n /**\n * Returns the size in bytes of all messages enqueued to be transmitted to the server. This\n * doesn't include framing overhead. If compression is enabled, uncompressed messages size\n * is used to calculate this value. It also doesn't include any bytes buffered by the operating\n * system or network intermediaries. This method returns 0 if no messages are waiting in the\n * queue. If may return a nonzero value after the web socket has been canceled; this indicates\n * that enqueued messages were not transmitted.\n *\n * Use this to monitor backpressure and avoid exceeding the 16 MiB outgoing message buffer limit.\n * When that limit is exceeded, the web socket is gracefully shut down.\n */\n fun queueSize(): Long\n\n /**\n * Attempts to enqueue `text` to be UTF-8 encoded and sent as a the data of a text (type `0x1`)\n * message.\n *\n * This method returns true if the message was enqueued. Messages that would overflow the outgoing\n * message buffer (16 MiB) will be rejected and trigger a [graceful shutdown][close] of this web\n * socket. Thi"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":65,"symbol":"request","kind":"function","lang":"kotlin","doc":"Returns the original request that initiated this web socket.","code":"fun request(): Request"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":78,"symbol":"queueSize","kind":"function","lang":"kotlin","doc":"queue. If may return a nonzero value after the web socket has been canceled; this indicates that enqueued messages were not transmitted. Use this to monitor backpressure and avoid exceeding the 16 MiB outgoing message buffer limit. When that limit is exceeded, the web socket is gracefully shut down.","code":"fun queueSize(): Long"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":91,"symbol":"send","kind":"function","lang":"kotlin","doc":"message buffer (16 MiB) will be rejected and trigger a [graceful shutdown][close] of this web socket. This method returns false in that case, and in any other case where this web socket is closing, closed, or canceled. This method returns immediately.","code":"fun send(text: String): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":103,"symbol":"send","kind":"function","lang":"kotlin","doc":"message buffer (16 MiB) will be rejected and trigger a [graceful shutdown][close] of this web socket. This method returns false in that case, and in any other case where this web socket is closing, closed, or canceled. This method returns immediately.","code":"fun send(bytes: ByteString): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":118,"symbol":"close","kind":"function","lang":"kotlin","doc":"@param code Status code as defined by [Section 7.4 of RFC 6455](http://tools.ietf.org/html/rfc6455#section-7.4). @param reason Reason for shutting down, no longer than 123 bytes of UTF-8 encoded data (**not** characters) or null. @throws IllegalArgumentException if [code] is invalid or [reason] is too long.","code":"fun close(\n code: Int,\n reason: String?,\n ): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":127,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"Immediately and violently release resources held by this web socket, discarding any enqueued messages. This does nothing if the web socket has already been closed or canceled.","code":"fun cancel()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":129,"symbol":"Factory","kind":"interface","lang":"kotlin","code":"fun interface Factory {\n /**\n * Creates a new web socket and immediately returns it. Creating a web socket initiates an\n * asynchronous process to connect the socket. Once that succeeds or fails, `listener` will be\n * notified. The caller must either close or cancel the returned web socket when it is no longer\n * in use.\n */\n fun newWebSocket(\n request: Request,\n listener: WebSocketListener,\n ): WebSocket\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocket.kt","line":136,"symbol":"newWebSocket","kind":"function","lang":"kotlin","doc":"Creates a new web socket and immediately returns it. Creating a web socket initiates an asynchronous process to connect the socket. Once that succeeds or fails, `listener` will be notified. The caller must either close or cancel the returned web socket when it is no longer in use.","code":"fun newWebSocket(\n request: Request,\n listener: WebSocketListener,\n ): WebSocket"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocketListener.kt","line":20,"symbol":"WebSocketListener","kind":"class","lang":"kotlin","code":"abstract class WebSocketListener {\n /**\n * Invoked when a web socket has been accepted by the remote peer and may begin transmitting\n * messages.\n */\n open fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n }\n\n /** Invoked when a text (type `0x1`) message has been received. */\n open fun onMessage(\n webSocket: WebSocket,\n text: String,\n ) {\n }\n\n /** Invoked when a binary (type `0x2`) message has been received. */\n open fun onMessage(\n webSocket: WebSocket,\n bytes: ByteString,\n ) {\n }\n\n /**\n * Invoked when the remote peer has indicated that no more incoming messages will be transmitted.\n */\n open fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n }\n\n /**\n * Invoked when both peers have indicated that no more messages will be transmitted and the\n * connection has been successfully released. No further calls to this listener will be made.\n */\n open fun onClosed(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n }\n\n /**\n * Invoked when a web socket has been closed due to an error reading from or writing to the\n * network. Both outgoing and incoming messages may have been"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocketListener.kt","line":25,"symbol":"onOpen","kind":"function","lang":"kotlin","doc":"Invoked when a web socket has been accepted by the remote peer and may begin transmitting messages.","code":"open fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocketListener.kt","line":32,"symbol":"onMessage","kind":"function","lang":"kotlin","doc":"Invoked when a text (type `0x1`) message has been received.","code":"open fun onMessage(\n webSocket: WebSocket,\n text: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocketListener.kt","line":39,"symbol":"onMessage","kind":"function","lang":"kotlin","doc":"Invoked when a binary (type `0x2`) message has been received.","code":"open fun onMessage(\n webSocket: WebSocket,\n bytes: ByteString,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocketListener.kt","line":48,"symbol":"onClosing","kind":"function","lang":"kotlin","doc":"Invoked when the remote peer has indicated that no more incoming messages will be transmitted.","code":"open fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocketListener.kt","line":59,"symbol":"onClosed","kind":"function","lang":"kotlin","doc":"Invoked when both peers have indicated that no more messages will be transmitted and the connection has been successfully released. No further calls to this listener will be made.","code":"open fun onClosed(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/WebSocketListener.kt","line":71,"symbol":"onFailure","kind":"function","lang":"kotlin","doc":"Invoked when a web socket has been closed due to an error reading from or writing to the network. Both outgoing and incoming messages may have been lost. No further calls to this listener will be made.","code":"open fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":24,"symbol":"commonToString","kind":"function","lang":"kotlin","code":"internal fun CacheControl.commonToString(): String {\n var result = headerValue\n if (result == null) {\n result =\n buildString {\n if (noCache) append(\"no-cache, \")\n if (noStore) append(\"no-store, \")\n if (maxAgeSeconds != -1) append(\"max-age=\").append(maxAgeSeconds).append(\", \")\n if (sMaxAgeSeconds != -1) append(\"s-maxage=\").append(sMaxAgeSeconds).append(\", \")\n if (isPrivate) append(\"private, \")\n if (isPublic) append(\"public, \")\n if (mustRevalidate) append(\"must-revalidate, \")\n if (maxStaleSeconds != -1) append(\"max-stale=\").append(maxStaleSeconds).append(\", \")\n if (minFreshSeconds != -1) append(\"min-fresh=\").append(minFreshSeconds).append(\", \")\n if (onlyIfCached) append(\"only-if-cached, \")\n if (noTransform) append(\"no-transform, \")\n if (immutable) append(\"immutable, \")\n if (isEmpty()) return \"\"\n deleteRange(length - 2, length)\n }\n headerValue = result\n }\n return result\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":49,"symbol":"commonClampToInt","kind":"function","lang":"kotlin","code":"internal fun Long.commonClampToInt(): Int =\n when {\n this > Int.MAX_VALUE -> Int.MAX_VALUE\n else -> toInt()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":55,"symbol":"commonForceNetwork","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Companion.commonForceNetwork() =\n CacheControl\n .Builder()\n .noCache()\n .build()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":61,"symbol":"commonForceCache","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Companion.commonForceCache() =\n CacheControl\n .Builder()\n .onlyIfCached()\n .maxStale(Int.MAX_VALUE.seconds)\n .build()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":68,"symbol":"commonBuild","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Builder.commonBuild(): CacheControl =\n CacheControl(\n noCache = noCache,\n noStore = noStore,\n maxAgeSeconds = maxAgeSeconds,\n sMaxAgeSeconds = -1,\n isPrivate = false,\n isPublic = false,\n mustRevalidate = false,\n maxStaleSeconds = maxStaleSeconds,\n minFreshSeconds = minFreshSeconds,\n onlyIfCached = onlyIfCached,\n noTransform = noTransform,\n immutable = immutable,\n headerValue = null,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":85,"symbol":"commonNoCache","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Builder.commonNoCache() =\n apply {\n this.noCache = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":90,"symbol":"commonNoStore","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Builder.commonNoStore() =\n apply {\n this.noStore = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":95,"symbol":"commonOnlyIfCached","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Builder.commonOnlyIfCached() =\n apply {\n this.onlyIfCached = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":100,"symbol":"commonNoTransform","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Builder.commonNoTransform() =\n apply {\n this.noTransform = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":105,"symbol":"commonImmutable","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Builder.commonImmutable() =\n apply {\n this.immutable = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":110,"symbol":"commonParse","kind":"function","lang":"kotlin","code":"internal fun CacheControl.Companion.commonParse(headers: Headers): CacheControl {\n var noCache = false\n var noStore = false\n var maxAgeSeconds = -1\n var sMaxAgeSeconds = -1\n var isPrivate = false\n var isPublic = false\n var mustRevalidate = false\n var maxStaleSeconds = -1\n var minFreshSeconds = -1\n var onlyIfCached = false\n var noTransform = false\n var immutable = false\n\n var canUseHeaderValue = true\n var headerValue: String? = null\n\n loop@ for (i in 0 until headers.size) {\n val name = headers.name(i)\n val value = headers.value(i)\n\n when {\n name.equals(\"Cache-Control\", ignoreCase = true) -> {\n if (headerValue != null) {\n // Multiple cache-control headers means we can't use the raw value.\n canUseHeaderValue = false\n } else {\n headerValue = value\n }\n }\n\n name.equals(\"Pragma\", ignoreCase = true) -> {\n // Might specify additional cache-control params. We invalidate just in case.\n canUseHeaderValue = false\n }\n\n else -> {\n continue@loop\n }\n }\n\n var pos = 0\n while (pos < value.length) {\n val tokenStart = pos\n pos = value.indexOfElement(\"=,;\", pos)\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-CacheControlCommon.kt","line":257,"symbol":"indexOfElement","kind":"function","lang":"kotlin","doc":"Returns the next index in this at or after [startIndex] that is a character from [characters]. Returns the input length if none of the requested characters can be found.","code":"private fun String.indexOfElement(\n characters: String,\n startIndex: Int = 0,\n): Int {\n for (i in startIndex until length) {\n if (this[i] in characters) {\n return i\n }\n }\n return length\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":26,"symbol":"commonName","kind":"function","lang":"kotlin","code":"internal fun Headers.commonName(index: Int): String = namesAndValues.getOrNull(index * 2) ?: throw IndexOutOfBoundsException(\"name[$index]\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":28,"symbol":"commonValue","kind":"function","lang":"kotlin","code":"internal fun Headers.commonValue(index: Int): String =\n namesAndValues.getOrNull(index * 2 + 1) ?: throw IndexOutOfBoundsException(\"value[$index]\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":31,"symbol":"commonValues","kind":"function","lang":"kotlin","code":"internal fun Headers.commonValues(name: String): List {\n var result: MutableList? = null\n for (i in 0 until size) {\n if (name.equals(name(i), ignoreCase = true)) {\n if (result == null) result = ArrayList(2)\n result.add(value(i))\n }\n }\n return result?.unmodifiable().orEmpty()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":42,"symbol":"commonIterator","kind":"function","lang":"kotlin","code":"internal fun Headers.commonIterator(): Iterator> = Array(size) { name(it) to value(it) }.iterator()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":44,"symbol":"commonNewBuilder","kind":"function","lang":"kotlin","code":"internal fun Headers.commonNewBuilder(): Headers.Builder {\n val result = Headers.Builder()\n result.namesAndValues += namesAndValues\n return result\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":50,"symbol":"commonEquals","kind":"function","lang":"kotlin","code":"internal fun Headers.commonEquals(other: Any?): Boolean = other is Headers && namesAndValues.contentEquals(other.namesAndValues)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":52,"symbol":"commonHashCode","kind":"function","lang":"kotlin","code":"internal fun Headers.commonHashCode(): Int = namesAndValues.contentHashCode()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":54,"symbol":"commonToString","kind":"function","lang":"kotlin","code":"internal fun Headers.commonToString(): String =\n buildString {\n for (i in 0 until size) {\n val name = name(i)\n val value = value(i)\n append(name)\n append(\": \")\n append(if (isSensitiveHeader(name)) \"██\" else value)\n append(\"\\n\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":66,"symbol":"commonHeadersGet","kind":"function","lang":"kotlin","code":"internal fun commonHeadersGet(\n namesAndValues: Array,\n name: String,\n): String? {\n for (i in namesAndValues.size - 2 downTo 0 step 2) {\n if (name.equals(namesAndValues[i], ignoreCase = true)) {\n return namesAndValues[i + 1]\n }\n }\n return null\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":78,"symbol":"commonAdd","kind":"function","lang":"kotlin","code":"internal fun Headers.Builder.commonAdd(\n name: String,\n value: String,\n) = apply {\n headersCheckName(name)\n headersCheckValue(value, name)\n commonAddLenient(name, value)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":87,"symbol":"commonAddAll","kind":"function","lang":"kotlin","code":"internal fun Headers.Builder.commonAddAll(headers: Headers) =\n apply {\n for (i in 0 until headers.size) {\n commonAddLenient(headers.name(i), headers.value(i))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":94,"symbol":"commonAddLenient","kind":"function","lang":"kotlin","code":"internal fun Headers.Builder.commonAddLenient(\n name: String,\n value: String,\n) = apply {\n namesAndValues.add(name)\n namesAndValues.add(value.trim())\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":102,"symbol":"commonRemoveAll","kind":"function","lang":"kotlin","code":"internal fun Headers.Builder.commonRemoveAll(name: String) =\n apply {\n var i = 0\n while (i < namesAndValues.size) {\n if (name.equals(namesAndValues[i], ignoreCase = true)) {\n namesAndValues.removeAt(i) // name\n namesAndValues.removeAt(i) // value\n i -= 2\n }\n i += 2\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":119,"symbol":"commonSet","kind":"function","lang":"kotlin","doc":"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.","code":"internal fun Headers.Builder.commonSet(\n name: String,\n value: String,\n) = apply {\n headersCheckName(name)\n headersCheckValue(value, name)\n removeAll(name)\n commonAddLenient(name, value)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":130,"symbol":"commonGet","kind":"function","lang":"kotlin","doc":"Equivalent to `build().get(name)`, but potentially faster.","code":"internal fun Headers.Builder.commonGet(name: String): String? {\n for (i in namesAndValues.size - 2 downTo 0 step 2) {\n if (name.equals(namesAndValues[i], ignoreCase = true)) {\n return namesAndValues[i + 1]\n }\n }\n return null\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":139,"symbol":"commonBuild","kind":"function","lang":"kotlin","code":"internal fun Headers.Builder.commonBuild(): Headers = Headers(namesAndValues.toTypedArray())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":141,"symbol":"headersCheckName","kind":"function","lang":"kotlin","code":"internal fun headersCheckName(name: String) {\n require(name.isNotEmpty()) { \"name is empty\" }\n for (i in name.indices) {\n val c = name[i]\n require(c in '\\u0021'..'\\u007e') {\n \"Unexpected char 0x${c.charCode()} at $i in header name: $name\"\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":151,"symbol":"headersCheckValue","kind":"function","lang":"kotlin","code":"internal fun headersCheckValue(\n value: String,\n name: String,\n) {\n for (i in value.indices) {\n val c = value[i]\n require(c == '\\t' || c in '\\u0020'..'\\u007e') {\n \"Unexpected char 0x${c.charCode()} at $i in $name value\" +\n (if (isSensitiveHeader(name)) \"\" else \": $value\")\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":164,"symbol":"charCode","kind":"function","lang":"kotlin","code":"private fun Char.charCode() =\n code.toString(16).let {\n if (it.length < 2) {\n \"0$it\"\n } else {\n it\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":173,"symbol":"commonHeadersOf","kind":"function","lang":"kotlin","code":"internal fun commonHeadersOf(vararg inputNamesAndValues: String): Headers {\n require(inputNamesAndValues.size % 2 == 0) { \"Expected alternating header names and values\" }\n\n // Make a defensive copy and clean it up.\n val namesAndValues: Array = arrayOf(*inputNamesAndValues)\n for (i in namesAndValues.indices) {\n @Suppress(\"SENSELESS_COMPARISON\")\n require(namesAndValues[i] != null) { \"Headers cannot be null\" }\n namesAndValues[i] = inputNamesAndValues[i].trim()\n }\n\n // Check for malformed headers.\n for (i in namesAndValues.indices step 2) {\n val name = namesAndValues[i]\n val value = namesAndValues[i + 1]\n headersCheckName(name)\n headersCheckValue(value, name)\n }\n\n return Headers(namesAndValues)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HeadersCommon.kt","line":195,"symbol":"commonToHeaders","kind":"function","lang":"kotlin","code":"internal fun Map.commonToHeaders(): Headers {\n // Make a defensive copy and clean it up.\n val namesAndValues = arrayOfNulls(size * 2)\n var i = 0\n for ((k, v) in this) {\n val name = k.trim()\n val value = v.trim()\n headersCheckName(name)\n headersCheckValue(value, name)\n namesAndValues[i] = name\n namesAndValues[i + 1] = value\n i += 2\n }\n\n @Suppress(\"UNCHECKED_CAST\")\n return Headers(namesAndValues as Array)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":37,"symbol":"canParseAsIpAddress","kind":"function","lang":"kotlin","doc":"Returns true if this string is not a host name and might be an IP address.","code":"fun String.canParseAsIpAddress(): Boolean = VERIFY_AS_IP_ADDRESS.matches(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":43,"symbol":"containsInvalidLabelLengths","kind":"function","lang":"kotlin","doc":"Returns true if the length is not valid for DNS (empty or greater than 253 characters), or if any label is longer than 63 characters. Trailing dots are okay.","code":"internal fun String.containsInvalidLabelLengths(): Boolean {\n if (length !in 1..253) return true\n\n var labelStart = 0\n while (true) {\n val dot = indexOf('.', startIndex = labelStart)\n val labelLength =\n when (dot) {\n -1 -> length - labelStart\n else -> dot - labelStart\n }\n if (labelLength !in 1..63) return true\n if (dot == -1) break\n if (dot == length - 1) break // Trailing '.' is allowed.\n labelStart = dot + 1\n }\n\n return false\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":63,"symbol":"containsInvalidHostnameAsciiCodes","kind":"function","lang":"kotlin","code":"internal fun String.containsInvalidHostnameAsciiCodes(): Boolean {\n for (i in 0 until length) {\n val c = this[i]\n // The WHATWG Host parsing rules accepts some character codes which are invalid by\n // definition for OkHttp's host header checks (and the WHATWG Host syntax definition). Here\n // we rule out characters that would cause problems in host headers.\n if (c <= '\\u001f' || c >= '\\u007f') {\n return true\n }\n // Check for the characters mentioned in the WHATWG Host parsing spec:\n // U+0000, U+0009, U+000A, U+000D, U+0020, \"#\", \"%\", \"/\", \":\", \"?\", \"@\", \"[\", \"\\\", and \"]\"\n // (excluding the characters covered above).\n if (\" #%/:?@[\\\\]\".indexOf(c) != -1) {\n return true\n }\n }\n return false\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":83,"symbol":"decodeIpv6","kind":"function","lang":"kotlin","doc":"Decodes an IPv6 address like 1111:2222:3333:4444:5555:6666:7777:8888 or ::1.","code":"internal fun decodeIpv6(\n input: String,\n pos: Int,\n limit: Int,\n): ByteArray? {\n val address = ByteArray(16)\n var b = 0\n var compress = -1\n var groupOffset = -1\n\n var i = pos\n while (i < limit) {\n if (b == address.size) return null // Too many groups.\n\n // Read a delimiter.\n if (i + 2 <= limit && input.startsWith(\"::\", startIndex = i)) {\n // Compression \"::\" delimiter, which is anywhere in the input, including its prefix.\n if (compress != -1) return null // Multiple \"::\" delimiters.\n i += 2\n b += 2\n compress = b\n if (i == limit) break\n } else if (b != 0) {\n // Group separator \":\" delimiter.\n if (input.startsWith(\":\", startIndex = i)) {\n i++\n } else if (input.startsWith(\".\", startIndex = i)) {\n // If we see a '.', rewind to the beginning of the previous group and parse as IPv4.\n if (!decodeIpv4Suffix(input, groupOffset, limit, address, b - 2)) return null\n b += 2 // We rewound two bytes and then added four.\n break\n } else {\n return null // Wrong delimiter.\n }\n }\n\n // Read a group, one to four hex digits.\n var value = 0\n groupOffset = i\n while (i < lim"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":155,"symbol":"decodeIpv4Suffix","kind":"function","lang":"kotlin","doc":"Decodes an IPv4 address suffix of an IPv6 address, like 1111::5555:6666:192.168.0.1.","code":"internal fun decodeIpv4Suffix(\n input: String,\n pos: Int,\n limit: Int,\n address: ByteArray,\n addressOffset: Int,\n): Boolean {\n var b = addressOffset\n\n var i = pos\n while (i < limit) {\n if (b == address.size) return false // Too many groups.\n\n // Read a delimiter.\n if (b != addressOffset) {\n if (input[i] != '.') return false // Wrong delimiter.\n i++\n }\n\n // Read 1 or more decimal digits for a value in 0..255.\n var value = 0\n val groupOffset = i\n while (i < limit) {\n val c = input[i]\n if (c < '0' || c > '9') break\n if (value == 0 && groupOffset != i) return false // Reject unnecessary leading '0's.\n value = value * 10 + c.code - '0'.code\n if (value > 255) return false // Value out of range.\n i++\n }\n val groupLength = i - groupOffset\n if (groupLength == 0) return false // No digits.\n\n // We've successfully read a byte.\n address[b++] = value.toByte()\n }\n\n // Check for too few groups. We wanted exactly four.\n return b == addressOffset + 4\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":197,"symbol":"inet6AddressToAscii","kind":"function","lang":"kotlin","doc":"Encodes an IPv6 address in canonical form according to RFC 5952.","code":"internal fun inet6AddressToAscii(address: ByteArray): String {\n // Go through the address looking for the longest run of 0s. Each group is 2-bytes.\n // A run must be longer than one group (section 4.2.2).\n // If there are multiple equal runs, the first one must be used (section 4.2.3).\n var longestRunOffset = -1\n var longestRunLength = 0\n run {\n var i = 0\n while (i < address.size) {\n val currentRunOffset = i\n while (i < 16 && address[i].toInt() == 0 && address[i + 1].toInt() == 0) {\n i += 2\n }\n val currentRunLength = i - currentRunOffset\n if (currentRunLength > longestRunLength && currentRunLength >= 4) {\n longestRunOffset = currentRunOffset\n longestRunLength = currentRunLength\n }\n i += 2\n }\n }\n\n // Emit each 2-byte group in hex, separated by ':'. The longest run of zeroes is \"::\".\n val result = Buffer()\n var i = 0\n while (i < address.size) {\n if (i == longestRunOffset) {\n result.writeByte(':'.code)\n i += longestRunLength\n if (i == 16) result.writeByte(':'.code)\n } else {\n if (i > 0) result.writeByte(':'.code)\n val group = address[i] and 0xff shl 8 or (address[i + 1] and 0xff)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":243,"symbol":"canonicalizeInetAddress","kind":"function","lang":"kotlin","doc":"Returns the canonical address for [address]. If [address] is an IPv6 address that is mapped to an IPv4 address, this returns the IPv4-mapped address. Otherwise, this returns [address]. https://en.wikipedia.org/wiki/IPv6#IPv4-mapped_IPv6_addresses","code":"internal fun canonicalizeInetAddress(address: ByteArray): ByteArray =\n when {\n isMappedIpv4Address(address) -> address.sliceArray(12 until 16)\n else -> address\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":250,"symbol":"isMappedIpv4Address","kind":"function","lang":"kotlin","doc":"Returns true for IPv6 addresses like `0000:0000:0000:0000:0000:ffff:XXXX:XXXX`.","code":"private fun isMappedIpv4Address(address: ByteArray): Boolean {\n if (address.size != 16) return false\n\n for (i in 0 until 10) {\n if (address[i] != 0.toByte()) return false\n }\n\n if (address[10] != 255.toByte()) return false\n if (address[11] != 255.toByte()) return false\n\n return true\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":264,"symbol":"inet4AddressToAscii","kind":"function","lang":"kotlin","doc":"Encodes an IPv4 address in canonical form according to RFC 4001.","code":"internal fun inet4AddressToAscii(address: ByteArray): String {\n require(address.size == 4)\n return Buffer()\n .writeDecimalLong((address[0] and 0xff).toLong())\n .writeByte('.'.code)\n .writeDecimalLong((address[1] and 0xff).toLong())\n .writeByte('.'.code)\n .writeDecimalLong((address[2] and 0xff).toLong())\n .writeByte('.'.code)\n .writeDecimalLong((address[3] and 0xff).toLong())\n .readUtf8()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":285,"symbol":"toCanonicalHost","kind":"function","lang":"kotlin","doc":"Otherwise, this performs IDN ToASCII encoding and canonicalize the result to lowercase. For example this converts `☃.net` to `xn--n3h.net`, and `WwW.GoOgLe.cOm` to `www.google.com`. `null` will be returned if the host cannot be ToASCII encoded or if the result contains unsupported ASCII characters.","code":"internal fun String.toCanonicalHost(): String? {\n val host: String = this\n\n // If the input contains a :, it’s an IPv6 address.\n if (\":\" in host) {\n // If the input is encased in square braces \"[...]\", drop 'em.\n val inetAddressByteArray =\n (\n if (host.startsWith(\"[\") && host.endsWith(\"]\")) {\n decodeIpv6(host, 1, host.length - 1)\n } else {\n decodeIpv6(host, 0, host.length)\n }\n ) ?: return null\n\n val address = canonicalizeInetAddress(inetAddressByteArray)\n if (address.size == 16) return inet6AddressToAscii(address)\n if (address.size == 4) return inet4AddressToAscii(address) // An IPv4-mapped IPv6 address.\n throw AssertionError(\"Invalid IPv6 address: '$host'\")\n }\n\n val result = idnToAscii(host) ?: return null\n if (result.isEmpty()) return null\n if (result.containsInvalidHostnameAsciiCodes()) return null\n if (result.containsInvalidLabelLengths()) return null\n\n return result\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-HostnamesCommon.kt","line":314,"symbol":"idnToAscii","kind":"function","lang":"kotlin","code":"internal fun idnToAscii(host: String): String? {\n val bufferA = Buffer().writeUtf8(host)\n val bufferB = Buffer()\n\n // 1. Map, from bufferA to bufferB.\n while (!bufferA.exhausted()) {\n val codePoint = bufferA.readUtf8CodePoint()\n if (!IDNA_MAPPING_TABLE.map(codePoint, bufferB)) return null\n }\n\n // 2. Normalize, from bufferB to bufferA.\n val normalized = normalizeNfc(bufferB.readUtf8())\n bufferA.writeUtf8(normalized)\n\n // 3. For each label, convert/validate Punycode.\n val decoded = Punycode.decode(bufferA.readUtf8()) ?: return null\n\n // 4.1 Validate.\n\n // Must be NFC.\n if (decoded != normalizeNfc(decoded)) return null\n\n // TODO: Must not begin with a combining mark.\n // TODO: Each character must be 'valid' or 'deviation'. Not mapped.\n // TODO: CheckJoiners from IDNA 2008\n // TODO: CheckBidi from IDNA 2008, RFC 5893, Section 2.\n\n return Punycode.encode(decoded)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-NormalizeJvm.kt","line":23,"symbol":"normalizeNfc","kind":"function","lang":"kotlin","code":"internal fun normalizeNfc(string: String): String = Normalizer.normalize(string, NFC)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":55,"symbol":"intersect","kind":"function","lang":"kotlin","doc":"Returns an array containing only elements found in this array and also in [other]. The returned elements are in the same order as in this.","code":"internal fun Array.intersect(\n other: Array,\n comparator: Comparator,\n): Array {\n val result = mutableListOf()\n for (a in this) {\n for (b in other) {\n if (comparator.compare(a, b) == 0) {\n result.add(a)\n break\n }\n }\n }\n return result.toTypedArray()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":77,"symbol":"hasIntersection","kind":"function","lang":"kotlin","doc":"Returns true if there is an element in this array that is also in [other]. This method terminates if any intersection is found. The sizes of both arguments are assumed to be so small, and the likelihood of an intersection so great, that it is not worth the CPU cost of sorting or the memory cost of hashing.","code":"internal fun Array.hasIntersection(\n other: Array?,\n comparator: Comparator,\n): Boolean {\n if (isEmpty() || other == null || other.isEmpty()) {\n return false\n }\n for (a in this) {\n for (b in other) {\n if (comparator.compare(a, b) == 0) {\n return true\n }\n }\n }\n return false\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":94,"symbol":"indexOf","kind":"function","lang":"kotlin","code":"internal fun Array.indexOf(\n value: String,\n comparator: Comparator,\n): Int = indexOfFirst { comparator.compare(it, value) == 0 }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":100,"symbol":"concat","kind":"function","lang":"kotlin","code":"internal fun Array.concat(value: String): Array {\n val result = copyOf(size + 1)\n result[result.lastIndex] = value\n return result as Array\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":107,"symbol":"indexOfFirstNonAsciiWhitespace","kind":"function","lang":"kotlin","doc":"Increments [startIndex] until this string is not ASCII whitespace. Stops at [endIndex].","code":"internal fun String.indexOfFirstNonAsciiWhitespace(\n startIndex: Int = 0,\n endIndex: Int = length,\n): Int {\n for (i in startIndex until endIndex) {\n when (this[i]) {\n '\\t', '\\n', '\\u000C', '\\r', ' ' -> Unit\n else -> return i\n }\n }\n return endIndex\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":123,"symbol":"indexOfLastNonAsciiWhitespace","kind":"function","lang":"kotlin","doc":"Decrements [endIndex] until `input[endIndex - 1]` is not ASCII whitespace. Stops at [startIndex].","code":"internal fun String.indexOfLastNonAsciiWhitespace(\n startIndex: Int = 0,\n endIndex: Int = length,\n): Int {\n for (i in endIndex - 1 downTo startIndex) {\n when (this[i]) {\n '\\t', '\\n', '\\u000C', '\\r', ' ' -> Unit\n else -> return i + 1\n }\n }\n return startIndex\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":137,"symbol":"trimSubstring","kind":"function","lang":"kotlin","doc":"Equivalent to `string.substring(startIndex, endIndex).trim()`.","code":"fun String.trimSubstring(\n startIndex: Int = 0,\n endIndex: Int = length,\n): String {\n val start = indexOfFirstNonAsciiWhitespace(startIndex, endIndex)\n val end = indexOfLastNonAsciiWhitespace(start, endIndex)\n return substring(start, end)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":150,"symbol":"delimiterOffset","kind":"function","lang":"kotlin","doc":"Returns the index of the first character in this string that contains a character in [delimiters]. Returns endIndex if there is no such character.","code":"fun String.delimiterOffset(\n delimiters: String,\n startIndex: Int = 0,\n endIndex: Int = length,\n): Int {\n for (i in startIndex until endIndex) {\n if (this[i] in delimiters) return i\n }\n return endIndex\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":165,"symbol":"delimiterOffset","kind":"function","lang":"kotlin","doc":"Returns the index of the first character in this string that is [delimiter]. Returns [endIndex] if there is no such character.","code":"fun String.delimiterOffset(\n delimiter: Char,\n startIndex: Int = 0,\n endIndex: Int = length,\n): Int {\n for (i in startIndex until endIndex) {\n if (this[i] == delimiter) return i\n }\n return endIndex\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":180,"symbol":"indexOfControlOrNonAscii","kind":"function","lang":"kotlin","doc":"Returns the index of the first character in this string that is either a control character (like `\\u0000` or `\\n`) or a non-ASCII character. Returns -1 if this string has no such characters.","code":"internal fun String.indexOfControlOrNonAscii(): Int {\n for (i in 0 until length) {\n val c = this[i]\n if (c <= '\\u001f' || c >= '\\u007f') {\n return i\n }\n }\n return -1\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":191,"symbol":"isSensitiveHeader","kind":"function","lang":"kotlin","doc":"Returns true if we should void putting this this header in an exception or toString().","code":"internal fun isSensitiveHeader(name: String): Boolean =\n name.equals(\"Authorization\", ignoreCase = true) ||\n name.equals(\"Cookie\", ignoreCase = true) ||\n name.equals(\"Proxy-Authorization\", ignoreCase = true) ||\n name.equals(\"Set-Cookie\", ignoreCase = true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":197,"symbol":"parseHexDigit","kind":"function","lang":"kotlin","code":"internal fun Char.parseHexDigit(): Int =\n when (this) {\n in '0'..'9' -> this - '0'\n in 'a'..'f' -> this - 'a' + 10\n in 'A'..'F' -> this - 'A' + 10\n else -> -1\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":205,"symbol":"and","kind":"function","lang":"kotlin","code":"internal infix fun Byte.and(mask: Int): Int = toInt() and mask"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":207,"symbol":"and","kind":"function","lang":"kotlin","code":"internal infix fun Short.and(mask: Int): Int = toInt() and mask"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":209,"symbol":"and","kind":"function","lang":"kotlin","code":"internal infix fun Int.and(mask: Long): Long = toLong() and mask"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":212,"symbol":"writeMedium","kind":"function","lang":"kotlin","code":"internal fun BufferedSink.writeMedium(medium: Int) {\n writeByte(medium.ushr(16) and 0xff)\n writeByte(medium.ushr(8) and 0xff)\n writeByte(medium and 0xff)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":219,"symbol":"readMedium","kind":"function","lang":"kotlin","code":"internal fun BufferedSource.readMedium(): Int =\n (\n readByte() and 0xff shl 16\n or (readByte() and 0xff shl 8)\n or (readByte() and 0xff)\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":227,"symbol":"ignoreIoExceptions","kind":"function","lang":"kotlin","doc":"Run [block] until it either throws an [IOException] or completes.","code":"internal inline fun ignoreIoExceptions(block: () -> Unit) {\n try {\n block()\n } catch (_: IOException) {\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":234,"symbol":"skipAll","kind":"function","lang":"kotlin","code":"internal fun Buffer.skipAll(b: Byte): Int {\n var count = 0\n while (!exhausted() && this[0] == b) {\n count++\n readByte()\n }\n return count\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":247,"symbol":"indexOfNonWhitespace","kind":"function","lang":"kotlin","doc":"Returns the index of the next non-whitespace character in this. Result is undefined if input contains newline characters.","code":"internal fun String.indexOfNonWhitespace(startIndex: Int = 0): Int {\n for (i in startIndex until length) {\n val c = this[i]\n if (c != ' ' && c != '\\t') {\n return i\n }\n }\n return length\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":257,"symbol":"toLongOrDefault","kind":"function","lang":"kotlin","code":"fun String.toLongOrDefault(defaultValue: Long): Long =\n try {\n toLong()\n } catch (_: NumberFormatException) {\n defaultValue\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":268,"symbol":"toNonNegativeInt","kind":"function","lang":"kotlin","doc":"Returns this as a non-negative integer, or 0 if it is negative, or [Int.MAX_VALUE] if it is too large, or [defaultValue] if it cannot be parsed.","code":"internal fun String?.toNonNegativeInt(defaultValue: Int): Int {\n try {\n val value = this?.toLong() ?: return defaultValue\n return when {\n value > Int.MAX_VALUE -> Int.MAX_VALUE\n value < 0 -> 0\n else -> value.toInt()\n }\n } catch (_: NumberFormatException) {\n return defaultValue\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":282,"symbol":"closeQuietly","kind":"function","lang":"kotlin","doc":"Closes this, ignoring any checked exceptions.","code":"fun Closeable.closeQuietly() {\n try {\n close()\n } catch (rethrown: RuntimeException) {\n throw rethrown\n } catch (_: Exception) {\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":302,"symbol":"isCivilized","kind":"function","lang":"kotlin","doc":"If this returns false we won't permit simultaneous reads and writes. When writes commit we need to delete the previous snapshots, and that won't succeed if the file is open. (We do permit multiple simultaneous reads.) @param file a file in the directory to check. This file shouldn't already exist!","code":"internal fun FileSystem.isCivilized(file: Path): Boolean {\n sink(file).use {\n try {\n delete(file)\n return true\n } catch (_: IOException) {\n }\n }\n delete(file)\n return false\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":315,"symbol":"deleteIfExists","kind":"function","lang":"kotlin","doc":"Delete file we expect but don't require to exist.","code":"internal fun FileSystem.deleteIfExists(path: Path) {\n try {\n delete(path)\n } catch (fnfe: FileNotFoundException) {\n return\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":324,"symbol":"deleteContents","kind":"function","lang":"kotlin","doc":"Tolerant delete, try to clear as many files as possible even after a failure.","code":"internal fun FileSystem.deleteContents(directory: Path) {\n var exception: IOException? = null\n val files =\n try {\n list(directory)\n } catch (fnfe: FileNotFoundException) {\n return\n }\n for (file in files) {\n try {\n if (metadata(file).isDirectory) {\n deleteContents(file)\n }\n\n delete(file)\n } catch (ioe: IOException) {\n if (exception == null) {\n exception = ioe\n }\n }\n }\n if (exception != null) {\n throw exception\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":350,"symbol":"addIfAbsent","kind":"function","lang":"kotlin","code":"internal fun MutableList.addIfAbsent(element: E) {\n if (!contains(element)) add(element)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":354,"symbol":"withSuppressed","kind":"function","lang":"kotlin","code":"internal fun Exception.withSuppressed(suppressed: List): Throwable =\n apply {\n for (e in suppressed) addSuppressed(e)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":359,"symbol":"filterList","kind":"function","lang":"kotlin","code":"internal inline fun Iterable.filterList(predicate: T.() -> Boolean): List {\n var result: List = emptyList()\n for (i in this) {\n if (predicate(i)) {\n if (result.isEmpty()) result = mutableListOf()\n (result as MutableList).add(i)\n }\n }\n return result\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":372,"symbol":"checkOffsetAndCount","kind":"function","lang":"kotlin","code":"internal fun checkOffsetAndCount(\n arrayLength: Long,\n offset: Long,\n count: Long,\n) {\n if (offset or count < 0L || offset > arrayLength || arrayLength - offset < count) {\n throw ArrayIndexOutOfBoundsException(\"length=$arrayLength, offset=$offset, count=$offset\")\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilCommon.kt","line":382,"symbol":"interleave","kind":"function","lang":"kotlin","code":"internal fun interleave(\n a: Iterable,\n b: Iterable,\n): List {\n val ia = a.iterator()\n val ib = b.iterator()\n\n return buildList {\n while (ia.hasNext() || ib.hasNext()) {\n if (ia.hasNext()) {\n add(ia.next())\n }\n if (ib.hasNext()) {\n add(ib.next())\n }\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":54,"symbol":"threadFactory","kind":"function","lang":"kotlin","code":"internal fun threadFactory(\n name: String,\n daemon: Boolean,\n): ThreadFactory =\n ThreadFactory { runnable ->\n Thread(runnable, name).apply {\n isDaemon = daemon\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":64,"symbol":"toHostHeader","kind":"function","lang":"kotlin","code":"internal fun HttpUrl.toHostHeader(includeDefaultPort: Boolean = false): String {\n val host =\n if (\":\" in host) {\n \"[$host]\"\n } else {\n host\n }\n return if (includeDefaultPort || port != defaultPort(scheme)) {\n \"$host:$port\"\n } else {\n host\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":79,"symbol":"format","kind":"function","lang":"kotlin","doc":"Returns a [Locale.US] formatted [String].","code":"internal fun format(\n format: String,\n vararg args: Any,\n): String = String.format(Locale.US, format, *args)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":88,"symbol":"readBomAsCharset","kind":"function","lang":"kotlin","doc":"will also strip BOM from the source","code":"internal fun BufferedSource.readBomAsCharset(default: Charset): Charset =\n when (select(UNICODE_BOMS)) {\n // a mapping from the index of encoding methods in UNICODE_BOMS to its corresponding encoding method\n 0 -> UTF_8\n\n 1 -> UTF_16BE\n\n 2 -> UTF_32LE\n\n 3 -> UTF_16LE\n\n 4 -> UTF_32BE\n\n -1 -> default\n\n else -> throw AssertionError()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":106,"symbol":"checkDuration","kind":"function","lang":"kotlin","code":"internal fun checkDuration(\n name: String,\n duration: Long,\n unit: TimeUnit,\n): Int {\n check(duration >= 0L) { \"$name < 0\" }\n val millis = unit.toMillis(duration)\n require(millis <= Integer.MAX_VALUE) { \"$name too large\" }\n require(millis != 0L || duration <= 0L) { \"$name too small\" }\n return millis.toInt()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":118,"symbol":"checkDuration","kind":"function","lang":"kotlin","code":"internal fun checkDuration(\n name: String,\n duration: Duration,\n): Int {\n check(!duration.isNegative()) { \"$name < 0\" }\n val millis = duration.inWholeMilliseconds\n require(millis <= Integer.MAX_VALUE) { \"$name too large\" }\n require(millis != 0L || !duration.isPositive()) { \"$name too small\" }\n return millis.toInt()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":129,"symbol":"toHeaders","kind":"function","lang":"kotlin","code":"internal fun List
.toHeaders(): Headers {\n val builder = Headers.Builder()\n for ((name, value) in this) {\n builder.addLenient(name.utf8(), value.utf8())\n }\n return builder.build()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":137,"symbol":"toHeaderList","kind":"function","lang":"kotlin","code":"internal fun Headers.toHeaderList(): List
=\n (0 until size).map {\n Header(name(it), value(it))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":143,"symbol":"canReuseConnectionFor","kind":"function","lang":"kotlin","doc":"Returns true if an HTTP request for this URL and [other] can reuse a connection.","code":"internal fun HttpUrl.canReuseConnectionFor(other: HttpUrl): Boolean =\n host == other.host &&\n port == other.port &&\n scheme == other.scheme"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":148,"symbol":"asFactory","kind":"function","lang":"kotlin","code":"internal fun EventListener.asFactory() = EventListener.Factory { this }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":155,"symbol":"skipAll","kind":"function","lang":"kotlin","doc":"Reads until this is exhausted or the deadline has been reached. This is careful to not extend the deadline if one exists already.","code":"internal fun Source.skipAll(\n duration: Int,\n timeUnit: TimeUnit,\n): Boolean {\n val nowNs = System.nanoTime()\n val originalDurationNs =\n if (timeout().hasDeadline()) {\n timeout().deadlineNanoTime() - nowNs\n } else {\n Long.MAX_VALUE\n }\n timeout().deadlineNanoTime(nowNs + minOf(originalDurationNs, timeUnit.toNanos(duration.toLong())))\n return try {\n val skipBuffer = Buffer()\n while (read(skipBuffer, 8192) != -1L) {\n skipBuffer.clear()\n }\n true // Success! The source has been exhausted.\n } catch (_: InterruptedIOException) {\n false // We ran out of time before exhausting the source.\n } finally {\n if (originalDurationNs == Long.MAX_VALUE) {\n timeout().clearDeadline()\n } else {\n timeout().deadlineNanoTime(nowNs + originalDurationNs)\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":185,"symbol":"skipAll","kind":"function","lang":"kotlin","code":"internal fun BufferedSource.skipAll() {\n while (!exhausted()) {\n skip(buffer.size)\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":196,"symbol":"discard","kind":"function","lang":"kotlin","doc":"Attempts to exhaust this, returning true if successful. This is useful when reading a complete source is helpful, such as when doing so completes a cache body or frees a socket connection for reuse.","code":"internal fun Source.discard(\n timeout: Int,\n timeUnit: TimeUnit,\n): Boolean =\n try {\n this.skipAll(timeout, timeUnit)\n } catch (_: IOException) {\n false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":215,"symbol":"isHealthy","kind":"function","lang":"kotlin","doc":"Unfortunately Java's networking APIs don't offer a good health check, so we go on our own by attempting to read with a short timeout. If the fails immediately we know the socket is unhealthy. @param source the source used to read bytes from the socket.","code":"internal fun Socket.isHealthy(source: BufferedSource): Boolean =\n try {\n val readTimeout = soTimeout\n try {\n soTimeout = 1\n !source.exhausted()\n } finally {\n soTimeout = readTimeout\n }\n } catch (_: SocketTimeoutException) {\n true // Read timed out; socket is good.\n } catch (_: IOException) {\n false // Couldn't read; socket is closed.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":230,"symbol":"threadName","kind":"function","lang":"kotlin","code":"internal inline fun threadName(\n name: String,\n block: () -> Unit,\n) {\n val currentThread = Thread.currentThread()\n val oldName = currentThread.name\n currentThread.name = name\n try {\n block()\n } finally {\n currentThread.name = oldName\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":245,"symbol":"headersContentLength","kind":"function","lang":"kotlin","doc":"Returns the Content-Length as reported by the response headers.","code":"internal fun Response.headersContentLength(): Long = headers[\"Content-Length\"]?.toLongOrDefault(-1L) ?: -1L"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":249,"symbol":"unmodifiable","kind":"function","lang":"kotlin","doc":"Returns an immutable wrap of this.","code":"internal inline fun List.unmodifiable(): List = Collections.unmodifiableList(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":252,"symbol":"unmodifiable","kind":"function","lang":"kotlin","doc":"Returns an immutable wrap of this.","code":"@Suppress(\"NOTHING_TO_INLINE\")\ninternal inline fun Set.unmodifiable(): Set = Collections.unmodifiableSet(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":257,"symbol":"unmodifiable","kind":"function","lang":"kotlin","doc":"Returns an immutable wrap of this.","code":"internal inline fun Map.unmodifiable(): Map = Collections.unmodifiableMap(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":260,"symbol":"toImmutableList","kind":"function","lang":"kotlin","doc":"Returns an immutable copy of this.","code":"@Suppress(\"UNCHECKED_CAST\")\ninternal fun List.toImmutableList(): List =\n when {\n this.isEmpty() -> emptyList()\n\n this.size == 1 -> Collections.singletonList(this[0])\n\n // Collection.toArray returns Object[] (covariant).\n // It is faster than creating real T[] via reflection (Arrays.copyOf).\n else -> (this as java.util.Collection<*>).toArray().asList().unmodifiable() as List\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":273,"symbol":"immutableListOf","kind":"function","lang":"kotlin","doc":"Returns an immutable list containing [elements].","code":"@SafeVarargs\ninternal fun immutableListOf(vararg elements: T): List = elements.toImmutableList()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":277,"symbol":"toImmutableList","kind":"function","lang":"kotlin","doc":"Returns an immutable list from copy of this.","code":"internal fun Array?.toImmutableList(): List =\n when {\n this.isNullOrEmpty() -> emptyList()\n this.size == 1 -> Collections.singletonList(this[0])\n else -> this.clone().asList().unmodifiable()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":285,"symbol":"closeQuietly","kind":"function","lang":"kotlin","doc":"Closes this, ignoring any checked exceptions.","code":"internal fun Socket.closeQuietly() {\n try {\n close()\n } catch (e: AssertionError) {\n throw e\n } catch (rethrown: RuntimeException) {\n if (rethrown.message == \"bio == null\") {\n // Conscrypt in Android 10 and 11 may throw closing an SSLSocket. This is safe to ignore.\n // https://issuetracker.google.com/issues/177450597\n return\n }\n throw rethrown\n } catch (_: Exception) {\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":302,"symbol":"closeQuietly","kind":"function","lang":"kotlin","doc":"Closes this, ignoring any checked exceptions.","code":"internal fun ServerSocket.closeQuietly() {\n try {\n close()\n } catch (rethrown: RuntimeException) {\n throw rethrown\n } catch (_: Exception) {\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":311,"symbol":"toHexString","kind":"function","lang":"kotlin","code":"internal fun Long.toHexString(): String = java.lang.Long.toHexString(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":313,"symbol":"toHexString","kind":"function","lang":"kotlin","code":"internal fun Int.toHexString(): String = Integer.toHexString(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":315,"symbol":"readFieldOrNull","kind":"function","lang":"kotlin","code":"internal fun readFieldOrNull(\n instance: Any,\n fieldType: Class,\n fieldName: String,\n): T? {\n var c: Class<*> = instance.javaClass\n while (c != Any::class.java) {\n try {\n val field = c.getDeclaredField(fieldName)\n field.isAccessible = true\n val value = field.get(instance)\n return if (!fieldType.isInstance(value)) null else fieldType.cast(value)\n } catch (_: NoSuchFieldException) {\n }\n\n c = c.superclass\n }\n\n // Didn't find the field we wanted. As a last gasp attempt,\n // try to find the value on a delegate.\n if (fieldName != \"delegate\") {\n val delegate = readFieldOrNull(instance, Any::class.java, \"delegate\")\n if (delegate != null) return readFieldOrNull(delegate, fieldType, fieldName)\n }\n\n return null\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":347,"symbol":"assertLockNotHeld","kind":"function","lang":"kotlin","doc":"Dispatcher is not [Lockable] because we don't want that type in our public API.","code":"internal fun Dispatcher.assertLockNotHeld() {\n if (assertionsEnabled && Thread.holdsLock(this)) {\n throw AssertionError(\"Thread ${Thread.currentThread().name} MUST NOT hold lock on $this\")\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/-UtilJvm.kt","line":373,"symbol":"testAndSet","kind":"function","lang":"kotlin","doc":"It is possible that a [condition] is invoked multiple times in a single call to this function. This will occur if this state object is updated between fetching previous value and replacing it. Returns the previous value. This will always be the replaced value if the value was updated.","code":"@OkHttpInternalApi\ntailrec fun AtomicReference.testAndSet(\n newValue: T,\n condition: (T) -> Boolean,\n): T {\n val previous = get()\n if (!condition(previous)) return previous\n if (compareAndSet(previous, newValue)) return previous\n return testAndSet(newValue, condition) // Lost a race, retry.\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/IsProbablyUtf8.kt","line":28,"symbol":"isProbablyUtf8","kind":"function","lang":"kotlin","doc":"Returns true if the body in question probably contains human-readable text. Uses a small sample of code points to detect Unicode control characters commonly used in binary file signatures. @param codePointLimit the number of code points to read in order to make a decision.","code":"internal fun BufferedSource.isProbablyUtf8(codePointLimit: Long = Long.MAX_VALUE): Boolean {\n try {\n val peek = peek()\n for (i in 0 until codePointLimit) {\n if (peek.exhausted()) {\n break\n }\n val codePoint = peek.readUtf8CodePoint()\n if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {\n return false\n }\n }\n return true\n } catch (_: EOFException) {\n return false // Truncated UTF-8 sequence.\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/NativeImageTestsAccessors.kt","line":29,"symbol":"buildCache","kind":"function","lang":"kotlin","code":"internal fun buildCache(\n file: Path,\n maxSize: Long,\n fileSystem: FileSystem,\n): Cache = Cache(fileSystem, file, maxSize)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/NativeImageTestsAccessors.kt","line":47,"symbol":"finishedAccessor","kind":"function","lang":"kotlin","code":"internal fun Dispatcher.finishedAccessor(call: RealCall.AsyncCall) = this.finished(call)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":32,"symbol":"Tags","kind":"class","lang":"kotlin","doc":"This collection is optimized for safe concurrent access over a very small number of elements. This collection and is expected to hold fewer than 10 elements. Each operation is _O(N)_, and so building an instance with _N_ elements is _O(N**2)_.","code":"internal sealed class Tags {\n /**\n * Returns a tags instance that maps [key] to [value]. If [value] is null, this returns a tags\n * instance that does not have any mapping for [key].\n */\n abstract fun plus(\n key: KClass,\n value: T?,\n ): Tags\n\n abstract operator fun get(key: KClass): T?\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":37,"symbol":"plus","kind":"function","lang":"kotlin","doc":"Returns a tags instance that maps [key] to [value]. If [value] is null, this returns a tags instance that does not have any mapping for [key].","code":"abstract fun plus(\n key: KClass,\n value: T?,\n ): Tags"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":42,"symbol":"get","kind":"function","lang":"kotlin","code":"abstract operator fun get(key: KClass): T?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":46,"symbol":"EmptyTags","kind":"object","lang":"kotlin","doc":"An empty tags. This is always the tail of a [LinkedTags] chain.","code":"internal object EmptyTags : Tags() {\n override fun plus(\n key: KClass,\n value: T?,\n ): Tags =\n when {\n value != null -> LinkedTags(key, value, this)\n else -> this\n }\n\n override fun get(key: KClass): T? = null\n\n override fun toString() = \"{}\"\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":47,"symbol":"plus","kind":"function","lang":"kotlin","code":"override fun plus(\n key: KClass,\n value: T?,\n ): Tags =\n when {\n value != null -> LinkedTags(key, value, this)\n else -> this\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":56,"symbol":"get","kind":"function","lang":"kotlin","code":"override fun get(key: KClass): T? = null"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":58,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"{}\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":65,"symbol":"LinkedTags","kind":"class","lang":"kotlin","doc":"An invariant of this implementation is that [next] must not contain a mapping for [key]. Otherwise, we would have two values for the same key.","code":"private class LinkedTags(\n private val key: KClass,\n private val value: K,\n private val next: Tags,\n) : Tags() {\n override fun plus(\n key: KClass,\n value: T?,\n ): Tags {\n // Create a copy of this `LinkedTags` that doesn't have a mapping for `key`.\n val thisMinusKey =\n when {\n key == this.key -> {\n next\n }\n\n // Subtract this!\n\n else -> {\n val nextMinusKey = next.plus(key, null)\n when {\n nextMinusKey === next -> this\n\n // Same as the following line, but with fewer allocations.\n else -> LinkedTags(this.key, this.value, nextMinusKey)\n }\n }\n }\n\n // Return a new `Tags` that maps `key` to `value`.\n return when {\n value != null -> LinkedTags(key, value, thisMinusKey)\n else -> thisMinusKey\n }\n }\n\n override fun get(key: KClass): T? =\n when {\n key == this.key -> key.java.cast(value)\n else -> next[key]\n }\n\n /** Returns a [toString] consistent with [Map], with elements in insertion order. */\n override fun toString(): String =\n generateSequence>(seed = this) { it.next as? Li"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":70,"symbol":"plus","kind":"function","lang":"kotlin","code":"override fun plus(\n key: KClass,\n value: T?,\n ): Tags {\n // Create a copy of this `LinkedTags` that doesn't have a mapping for `key`.\n val thisMinusKey =\n when {\n key == this.key -> {\n next\n }\n\n // Subtract this!\n\n else -> {\n val nextMinusKey = next.plus(key, null)\n when {\n nextMinusKey === next -> this\n\n // Same as the following line, but with fewer allocations.\n else -> LinkedTags(this.key, this.value, nextMinusKey)\n }\n }\n }\n\n // Return a new `Tags` that maps `key` to `value`.\n return when {\n value != null -> LinkedTags(key, value, thisMinusKey)\n else -> thisMinusKey\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":101,"symbol":"get","kind":"function","lang":"kotlin","code":"override fun get(key: KClass): T? =\n when {\n key == this.key -> key.java.cast(value)\n else -> next[key]\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":108,"symbol":"toString","kind":"function","lang":"kotlin","doc":"Returns a [toString] consistent with [Map], with elements in insertion order.","code":"override fun toString(): String =\n generateSequence>(seed = this) { it.next as? LinkedTags<*> }\n .toList()\n .reversed()\n .joinToString(prefix = \"{\", postfix = \"}\") { \"${it.key}=${it.value}\" }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/Tags.kt","line":115,"symbol":"computeIfAbsent","kind":"function","lang":"kotlin","code":"internal fun AtomicReference.computeIfAbsent(\n type: KClass,\n compute: () -> T,\n): T {\n var computed: T? = null\n\n while (true) {\n val tags = get()\n\n // If the element is already present. Return it.\n val existing = tags[type]\n if (existing != null) return existing\n\n if (computed == null) {\n computed = compute()\n }\n\n // If we successfully add the computed element, we're done.\n val newTags = tags.plus(type, computed)\n if (compareAndSet(tags, newTags)) return computed\n\n // We lost the race. Possibly to other code that was putting a *different* key. Try again!\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/UnreadableResponseBody.kt","line":26,"symbol":"UnreadableResponseBody","kind":"class","lang":"kotlin","code":"internal class UnreadableResponseBody(\n private val mediaType: MediaType?,\n private val contentLength: Long,\n) : ResponseBody(),\n Source {\n override fun contentType() = mediaType\n\n override fun contentLength() = contentLength\n\n override fun source() = buffer()\n\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long =\n throw IllegalStateException(\n \"\"\"\n |Unreadable ResponseBody! These Response objects have bodies that are stripped:\n | * Response.cacheResponse\n | * Response.networkResponse\n | * Response.priorResponse\n | * EventSourceListener\n | * WebSocketListener\n |(It is safe to call contentType() and contentLength() on these response bodies.)\n \"\"\".trimMargin(),\n )\n\n override fun timeout() = Timeout.NONE\n\n override fun close() {\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/UnreadableResponseBody.kt","line":31,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = mediaType"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/UnreadableResponseBody.kt","line":33,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = contentLength"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/UnreadableResponseBody.kt","line":35,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source() = buffer()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/UnreadableResponseBody.kt","line":37,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long =\n throw IllegalStateException(\n \"\"\"\n |Unreadable ResponseBody! These Response objects have bodies that are stripped:\n | * Response.cacheResponse\n | * Response.networkResponse\n | * Response.priorResponse\n | * EventSourceListener\n | * WebSocketListener\n |(It is safe to call contentType() and contentLength() on these response bodies.)\n \"\"\".trimMargin(),\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/UnreadableResponseBody.kt","line":53,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout() = Timeout.NONE"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/UnreadableResponseBody.kt","line":55,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/UnreadableResponseBody.kt","line":59,"symbol":"stripBody","kind":"function","lang":"kotlin","code":"fun Response.stripBody(): Response =\n newBuilder()\n .body(UnreadableResponseBody(body.contentType(), body.contentLength()))\n .build()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/authenticator/JavaNetAuthenticator.kt","line":34,"symbol":"JavaNetAuthenticator","kind":"class","lang":"kotlin","doc":"Adapts [Authenticator] to [okhttp3.Authenticator]. Configure OkHttp to use [Authenticator] with [okhttp3.OkHttpClient.Builder.authenticator] or [okhttp3.OkHttpClient.Builder.proxyAuthenticator].","code":"class JavaNetAuthenticator(\n private val defaultDns: Dns = Dns.SYSTEM,\n) : okhttp3.Authenticator {\n @Throws(IOException::class)\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? {\n val challenges = response.challenges()\n val request = response.request\n val url = request.url\n val proxyAuthorization = response.code == 407\n val proxy = route?.proxy ?: Proxy.NO_PROXY\n\n for (challenge in challenges) {\n if (!\"Basic\".equals(challenge.scheme, ignoreCase = true)) {\n continue\n }\n\n val dns = route?.address?.dns ?: defaultDns\n val auth =\n if (proxyAuthorization) {\n val proxyAddress = proxy.address() as InetSocketAddress\n Authenticator.requestPasswordAuthentication(\n proxyAddress.hostName,\n proxy.connectToInetAddress(url, dns),\n proxyAddress.port,\n url.scheme,\n challenge.realm,\n challenge.scheme,\n url.toUrl(),\n Authenticator.RequestorType.PROXY,\n )\n } else {\n Authenticator.requestPasswordAuthentication(\n url.host,\n proxy.connectToInetAddress(url, dns),\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/authenticator/JavaNetAuthenticator.kt","line":37,"symbol":"authenticate","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? {\n val challenges = response.challenges()\n val request = response.request\n val url = request.url\n val proxyAuthorization = response.code == 407\n val proxy = route?.proxy ?: Proxy.NO_PROXY\n\n for (challenge in challenges) {\n if (!\"Basic\".equals(challenge.scheme, ignoreCase = true)) {\n continue\n }\n\n val dns = route?.address?.dns ?: defaultDns\n val auth =\n if (proxyAuthorization) {\n val proxyAddress = proxy.address() as InetSocketAddress\n Authenticator.requestPasswordAuthentication(\n proxyAddress.hostName,\n proxy.connectToInetAddress(url, dns),\n proxyAddress.port,\n url.scheme,\n challenge.realm,\n challenge.scheme,\n url.toUrl(),\n Authenticator.RequestorType.PROXY,\n )\n } else {\n Authenticator.requestPasswordAuthentication(\n url.host,\n proxy.connectToInetAddress(url, dns),\n url.port,\n url.scheme,\n challenge.realm,\n challenge.scheme,\n"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/authenticator/JavaNetAuthenticator.kt","line":98,"symbol":"connectToInetAddress","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun Proxy.connectToInetAddress(\n url: HttpUrl,\n dns: Dns,\n ): InetAddress =\n when (type()) {\n Proxy.Type.DIRECT -> dns.lookup(url.host).first()\n else -> (address() as InetSocketAddress).address\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":43,"symbol":"CacheInterceptor","kind":"class","lang":"kotlin","doc":"Serves requests from the cache and writes responses to the cache.","code":"class CacheInterceptor : Interceptor {\n @Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val call = chain.call()\n val cache = chain.cache\n val cacheCandidate = cache?.get(chain.request().requestForCache())\n\n val now = System.currentTimeMillis()\n\n val strategy = CacheStrategy.Factory(now, chain.request(), cacheCandidate).compute()\n val networkRequest = strategy.networkRequest\n val cacheResponse = strategy.cacheResponse\n\n cache?.trackResponse(strategy)\n\n if (cacheCandidate != null && cacheResponse == null) {\n // The cache candidate wasn't applicable. Close it.\n cacheCandidate.body.closeQuietly()\n }\n\n // If we're forbidden from using the network and the cache is insufficient, fail.\n if (networkRequest == null && cacheResponse == null) {\n return Response\n .Builder()\n .request(chain.request())\n .protocol(Protocol.HTTP_1_1)\n .code(HTTP_GATEWAY_TIMEOUT)\n .message(\"Unsatisfiable Request (only-if-cached)\")\n .sentRequestAtMillis(-1L)\n .receivedResponseAtMillis(System.currentTimeMillis())\n .build()\n .also {\n chain.eventListener."} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":44,"symbol":"intercept","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val call = chain.call()\n val cache = chain.cache\n val cacheCandidate = cache?.get(chain.request().requestForCache())\n\n val now = System.currentTimeMillis()\n\n val strategy = CacheStrategy.Factory(now, chain.request(), cacheCandidate).compute()\n val networkRequest = strategy.networkRequest\n val cacheResponse = strategy.cacheResponse\n\n cache?.trackResponse(strategy)\n\n if (cacheCandidate != null && cacheResponse == null) {\n // The cache candidate wasn't applicable. Close it.\n cacheCandidate.body.closeQuietly()\n }\n\n // If we're forbidden from using the network and the cache is insufficient, fail.\n if (networkRequest == null && cacheResponse == null) {\n return Response\n .Builder()\n .request(chain.request())\n .protocol(Protocol.HTTP_1_1)\n .code(HTTP_GATEWAY_TIMEOUT)\n .message(\"Unsatisfiable Request (only-if-cached)\")\n .sentRequestAtMillis(-1L)\n .receivedResponseAtMillis(System.currentTimeMillis())\n .build()\n .also {\n chain.eventListener.satisfactionFailure(call, it)\n }\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":171,"symbol":"cacheWritingResponse","kind":"function","lang":"kotlin","doc":"Returns a new source that writes bytes to [cacheRequest] as they are read by the source consumer. This is careful to discard bytes left over when the stream is closed; otherwise we may never exhaust the source stream and therefore not complete the cached response.","code":"@Throws(IOException::class)\n private fun cacheWritingResponse(\n cacheRequest: CacheRequest?,\n response: Response,\n ): Response {\n // Some apps return a null body; for compatibility we treat that like a null cache request.\n if (cacheRequest == null) return response\n val cacheBodyUnbuffered = cacheRequest.body()\n\n val source = response.body.source()\n val cacheBody = cacheBodyUnbuffered.buffer()\n\n val cacheWritingSource =\n object : Source {\n private var cacheRequestClosed = false\n\n @Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val bytesRead: Long\n try {\n bytesRead = source.read(sink, byteCount)\n } catch (e: IOException) {\n if (!cacheRequestClosed) {\n cacheRequestClosed = true\n cacheRequest.abort() // Failed to write a complete cache response.\n }\n throw e\n }\n\n if (bytesRead == -1L) {\n if (!cacheRequestClosed) {\n cacheRequestClosed = true\n cacheBody.close() // The cache response is complete!\n }\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":187,"symbol":"read","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val bytesRead: Long\n try {\n bytesRead = source.read(sink, byteCount)\n } catch (e: IOException) {\n if (!cacheRequestClosed) {\n cacheRequestClosed = true\n cacheRequest.abort() // Failed to write a complete cache response.\n }\n throw e\n }\n\n if (bytesRead == -1L) {\n if (!cacheRequestClosed) {\n cacheRequestClosed = true\n cacheBody.close() // The cache response is complete!\n }\n return -1\n }\n\n sink.copyTo(cacheBody.buffer, sink.size - bytesRead, bytesRead)\n cacheBody.emitCompleteSegments()\n return bytesRead\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":216,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = source.timeout()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":218,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n if (!cacheRequestClosed &&\n !discard(ExchangeCodec.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)\n ) {\n cacheRequestClosed = true\n cacheRequest.abort()\n }\n source.close()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":240,"symbol":"combine","kind":"function","lang":"kotlin","doc":"Combines cached headers with a network headers as defined by RFC 7234, 4.3.4.","code":"private fun combine(\n cachedHeaders: Headers,\n networkHeaders: Headers,\n ): Headers {\n val result = Headers.Builder()\n\n for (index in 0 until cachedHeaders.size) {\n val fieldName = cachedHeaders.name(index)\n val value = cachedHeaders.value(index)\n if (\"Warning\".equals(fieldName, ignoreCase = true) && value.startsWith(\"1\")) {\n // Drop 100-level freshness warnings.\n continue\n }\n if (isContentSpecificHeader(fieldName) ||\n !isEndToEnd(fieldName) ||\n networkHeaders[fieldName] == null\n ) {\n result.addLenient(fieldName, value)\n }\n }\n\n for (index in 0 until networkHeaders.size) {\n val fieldName = networkHeaders.name(index)\n if (!isContentSpecificHeader(fieldName) && isEndToEnd(fieldName)) {\n result.addLenient(fieldName, networkHeaders.value(index))\n }\n }\n\n return result.build()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":275,"symbol":"isEndToEnd","kind":"function","lang":"kotlin","doc":"Returns true if [fieldName] is an end-to-end HTTP header, as defined by RFC 2616, 13.5.1.","code":"private fun isEndToEnd(fieldName: String): Boolean =\n !\"Connection\".equals(fieldName, ignoreCase = true) &&\n !\"Keep-Alive\".equals(fieldName, ignoreCase = true) &&\n !\"Proxy-Authenticate\".equals(fieldName, ignoreCase = true) &&\n !\"Proxy-Authorization\".equals(fieldName, ignoreCase = true) &&\n !\"TE\".equals(fieldName, ignoreCase = true) &&\n !\"Trailers\".equals(fieldName, ignoreCase = true) &&\n !\"Transfer-Encoding\".equals(fieldName, ignoreCase = true) &&\n !\"Upgrade\".equals(fieldName, ignoreCase = true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":289,"symbol":"isContentSpecificHeader","kind":"function","lang":"kotlin","doc":"Returns true if [fieldName] is content specific and therefore should always be used from cached headers.","code":"private fun isContentSpecificHeader(fieldName: String): Boolean =\n \"Content-Length\".equals(fieldName, ignoreCase = true) ||\n \"Content-Encoding\".equals(fieldName, ignoreCase = true) ||\n \"Content-Type\".equals(fieldName, ignoreCase = true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheInterceptor.kt","line":296,"symbol":"requestForCache","kind":"function","lang":"kotlin","code":"private fun Request.requestForCache(): Request {\n val cacheUrlOverride = cacheUrlOverride\n\n // Allow POST and QUERY caching only when there is a cacheUrlOverride\n return if (cacheUrlOverride != null && (HttpMethod.isCacheable(method) || method == \"POST\")) {\n newBuilder()\n .get()\n .url(cacheUrlOverride)\n .cacheUrlOverride(null)\n .build()\n } else {\n this\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheRequest.kt","line":21,"symbol":"CacheRequest","kind":"interface","lang":"kotlin","code":"interface CacheRequest {\n @Throws(IOException::class)\n fun body(): Sink\n\n fun abort()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheRequest.kt","line":22,"symbol":"body","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun body(): Sink"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheRequest.kt","line":25,"symbol":"abort","kind":"function","lang":"kotlin","code":"fun abort()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":46,"symbol":"CacheStrategy","kind":"class","lang":"kotlin","doc":"both. Selecting a cache strategy may add conditions to the request (like the \"If-Modified-Since\" header for conditional GETs) or warnings to the cached response (if the cached data is potentially stale).","code":"class CacheStrategy internal constructor(\n /** The request to send on the network, or null if this call doesn't use the network. */\n val networkRequest: Request?,\n /** The cached response to return or validate; or null if this call doesn't use a cache. */\n val cacheResponse: Response?,\n) {\n class Factory(\n private val nowMillis: Long,\n internal val request: Request,\n private val cacheResponse: Response?,\n ) {\n /** The server's time when the cached response was served, if known. */\n private var servedDate: Date? = null\n private var servedDateString: String? = null\n\n /** The last modified date of the cached response, if known. */\n private var lastModified: Date? = null\n private var lastModifiedString: String? = null\n\n /**\n * The expiration date of the cached response, if known. If both this field and the max age are\n * set, the max age is preferred.\n */\n private var expires: Date? = null\n\n /**\n * Extension header set by OkHttp specifying the timestamp when the cached HTTP request was\n * first initiated.\n */\n private var sentRequestMillis = 0L\n\n /**\n * Extension header set by OkHttp specifying the timestamp wh"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":52,"symbol":"Factory","kind":"class","lang":"kotlin","code":"class Factory(\n private val nowMillis: Long,\n internal val request: Request,\n private val cacheResponse: Response?,\n ) {\n /** The server's time when the cached response was served, if known. */\n private var servedDate: Date? = null\n private var servedDateString: String? = null\n\n /** The last modified date of the cached response, if known. */\n private var lastModified: Date? = null\n private var lastModifiedString: String? = null\n\n /**\n * The expiration date of the cached response, if known. If both this field and the max age are\n * set, the max age is preferred.\n */\n private var expires: Date? = null\n\n /**\n * Extension header set by OkHttp specifying the timestamp when the cached HTTP request was\n * first initiated.\n */\n private var sentRequestMillis = 0L\n\n /**\n * Extension header set by OkHttp specifying the timestamp when the cached HTTP response was\n * first received.\n */\n private var receivedResponseMillis = 0L\n\n /** Etag of the cached response. */\n private var etag: String? = null\n\n /** Age of the cached response. */\n private var ageSeconds = -1\n\n /**\n * Returns true if computeF"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":93,"symbol":"isFreshnessLifetimeHeuristic","kind":"function","lang":"kotlin","doc":"Returns true if computeFreshnessLifetime used a heuristic. If we used a heuristic to serve a cached response older than 24 hours, we are required to attach a warning.","code":"private fun isFreshnessLifetimeHeuristic(): Boolean = cacheResponse!!.cacheControl.maxAgeSeconds == -1 && expires == null"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":131,"symbol":"compute","kind":"function","lang":"kotlin","doc":"Returns a strategy to satisfy [request] using [cacheResponse].","code":"fun compute(): CacheStrategy {\n val candidate = computeCandidate()\n\n // We're forbidden from using the network and the cache is insufficient.\n if (candidate.networkRequest != null && request.cacheControl.onlyIfCached) {\n return CacheStrategy(null, null)\n }\n\n return candidate\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":143,"symbol":"computeCandidate","kind":"function","lang":"kotlin","doc":"Returns a strategy to use assuming the request can use the network.","code":"private fun computeCandidate(): CacheStrategy {\n // No cached response.\n if (cacheResponse == null) {\n return CacheStrategy(request, null)\n }\n\n // Drop the cached response if it's missing a required handshake.\n if (request.isHttps && cacheResponse.handshake == null) {\n return CacheStrategy(request, null)\n }\n\n // If this response shouldn't have been stored, it should never be used as a response source.\n // This check should be redundant as long as the persistence store is well-behaved and the\n // rules are constant.\n if (!isCacheable(cacheResponse, request)) {\n return CacheStrategy(request, null)\n }\n\n val requestCaching = request.cacheControl\n if (requestCaching.noCache || hasConditions(request)) {\n return CacheStrategy(request, null)\n }\n\n val responseCaching = cacheResponse.cacheControl\n\n val ageMillis = cacheResponseAge()\n var freshMillis = computeFreshnessLifetime()\n\n if (requestCaching.maxAgeSeconds != -1) {\n freshMillis = minOf(freshMillis, SECONDS.toMillis(requestCaching.maxAgeSeconds.toLong()))\n }\n\n var minFreshMillis: Long = 0\n if (reque"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":237,"symbol":"computeFreshnessLifetime","kind":"function","lang":"kotlin","doc":"Returns the number of milliseconds that the response was fresh for, starting from the served date.","code":"private fun computeFreshnessLifetime(): Long {\n val responseCaching = cacheResponse!!.cacheControl\n if (responseCaching.maxAgeSeconds != -1) {\n return SECONDS.toMillis(responseCaching.maxAgeSeconds.toLong())\n }\n\n val expires = this.expires\n if (expires != null) {\n val servedMillis = servedDate?.time ?: receivedResponseMillis\n val delta = expires.time - servedMillis\n return if (delta > 0L) delta else 0L\n }\n\n if (lastModified != null && cacheResponse.request.url.query == null) {\n // As recommended by the HTTP RFC and implemented in Firefox, the max age of a document\n // should be defaulted to 10% of the document's age at the time it was served. Default\n // expiration dates aren't used for URIs containing a query.\n val servedMillis = servedDate?.time ?: sentRequestMillis\n val delta = servedMillis - lastModified!!.time\n return if (delta > 0L) delta / 10 else 0L\n }\n\n return 0L\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":266,"symbol":"cacheResponseAge","kind":"function","lang":"kotlin","doc":"Returns the current age of the response, in milliseconds. The calculation is specified by RFC 7234, 4.2.3 Calculating Age.","code":"private fun cacheResponseAge(): Long {\n val servedDate = this.servedDate\n val apparentReceivedAge =\n if (servedDate != null) {\n maxOf(0, receivedResponseMillis - servedDate.time)\n } else {\n 0\n }\n\n val receivedAge =\n if (ageSeconds != -1) {\n maxOf(apparentReceivedAge, SECONDS.toMillis(ageSeconds.toLong()))\n } else {\n apparentReceivedAge\n }\n\n val responseDuration = maxOf(0, receivedResponseMillis - sentRequestMillis)\n val residentDuration = maxOf(0, nowMillis - receivedResponseMillis)\n return receivedAge + responseDuration + residentDuration\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":292,"symbol":"hasConditions","kind":"function","lang":"kotlin","doc":"Returns true if the request contains conditions that save the server from sending a response that the client has locally. When a request is enqueued with its own conditions, the built-in response cache won't be used.","code":"private fun hasConditions(request: Request): Boolean =\n request.header(\"If-Modified-Since\") != null || request.header(\"If-None-Match\") != null"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/CacheStrategy.kt","line":298,"symbol":"isCacheable","kind":"function","lang":"kotlin","doc":"Returns true if [response] can be stored to later serve another request.","code":"fun isCacheable(\n response: Response,\n request: Request,\n ): Boolean {\n // Always go to network for uncacheable response codes (RFC 7231 section 6.1), This\n // implementation doesn't support caching partial content.\n when (response.code) {\n HTTP_OK,\n HTTP_NOT_AUTHORITATIVE,\n HTTP_NO_CONTENT,\n HTTP_MULT_CHOICE,\n HTTP_MOVED_PERM,\n HTTP_NOT_FOUND,\n HTTP_BAD_METHOD,\n HTTP_GONE,\n HTTP_REQ_TOO_LONG,\n HTTP_NOT_IMPLEMENTED,\n HTTP_PERM_REDIRECT,\n -> {\n // These codes can be cached unless headers forbid it.\n }\n\n HTTP_MOVED_TEMP,\n HTTP_TEMP_REDIRECT,\n -> {\n // These codes can only be cached with the right response headers.\n // http://tools.ietf.org/html/rfc7234#section-3\n // s-maxage is not checked because OkHttp is a private cache that should ignore s-maxage.\n if (response.header(\"Expires\") == null &&\n response.cacheControl.maxAgeSeconds == -1 &&\n !response.cacheControl.isPublic &&\n !response.cacheControl.isPrivate\n ) {\n return false\n }\n }\n\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":88,"symbol":"DiskLruCache","kind":"class","lang":"kotlin","doc":"@constructor Create a cache which will reside in [directory]. This cache is lazily initialized on first access and will be created if it does not exist. @param directory a writable directory. @param valueCount the number of values per cache entry. Must be positive. @param maxSize the maximum number of bytes this cache should use to store.","code":"class DiskLruCache(\n fileSystem: FileSystem,\n /** Returns the directory where this cache stores its data. */\n val directory: Path,\n private val appVersion: Int,\n internal val valueCount: Int,\n /** Returns the maximum number of bytes that this cache should use to store its data. */\n maxSize: Long,\n /** Used for asynchronous journal rebuilds. */\n taskRunner: TaskRunner,\n) : Closeable,\n Flushable,\n Lockable {\n internal val fileSystem: FileSystem =\n object : ForwardingFileSystem(fileSystem) {\n override fun sink(\n file: Path,\n mustCreate: Boolean,\n ): Sink {\n file.parent?.let {\n createDirectories(it)\n }\n return super.sink(file, mustCreate)\n }\n }\n\n /** The maximum number of bytes that this cache should use to store its data. */\n @get:Synchronized @set:Synchronized\n var maxSize: Long = maxSize\n set(value) {\n field = value\n if (initialized) {\n cleanupQueue.schedule(cleanupTask) // Trim the existing store if necessary.\n }\n }\n\n /*\n * This cache uses a journal file named \"journal\". A typical journal file looks like this:\n *\n * libcore.io.DiskLruCache\n * 1\n * 100\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":103,"symbol":"sink","kind":"function","lang":"kotlin","code":"override fun sink(\n file: Path,\n mustCreate: Boolean,\n ): Sink {\n file.parent?.let {\n createDirectories(it)\n }\n return super.sink(file, mustCreate)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":190,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n synchronized(this@DiskLruCache) {\n if (!initialized || closed) {\n return -1L // Nothing to do.\n }\n\n try {\n trimToSize()\n } catch (_: IOException) {\n mostRecentTrimFailed = true\n }\n\n try {\n if (journalRebuildRequired()) {\n rebuildJournal()\n redundantOpCount = 0\n }\n } catch (_: IOException) {\n mostRecentRebuildFailed = true\n journalWriter?.closeQuietly()\n journalWriter = blackholeSink().buffer()\n }\n\n return -1L\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":227,"symbol":"initialize","kind":"function","lang":"kotlin","code":"@Synchronized\n @Throws(IOException::class)\n fun initialize() {\n assertLockHeld()\n\n if (initialized) {\n return // Already initialized.\n }\n\n // If a bkp file exists, use it instead.\n if (fileSystem.exists(journalFileBackup)) {\n // If journal file also exists just delete backup file.\n if (fileSystem.exists(journalFile)) {\n fileSystem.delete(journalFileBackup)\n } else {\n fileSystem.atomicMove(journalFileBackup, journalFile)\n }\n }\n\n civilizedFileSystem = fileSystem.isCivilized(journalFileBackup)\n\n // Prefer to pick up where we left off.\n if (fileSystem.exists(journalFile)) {\n try {\n readJournal()\n processJournal()\n initialized = true\n return\n } catch (journalIsCorrupt: IOException) {\n Platform.get().log(\n \"DiskLruCache $directory is corrupt: ${journalIsCorrupt.message}, removing\",\n WARN,\n journalIsCorrupt,\n )\n }\n\n // The cache is corrupted, attempt to delete the contents of the directory. This can throw and\n // we'll let that propagate out as it likely means there is a severe filesystem problem.\n try {\n delete()\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":277,"symbol":"readJournal","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readJournal() {\n fileSystem.read(journalFile) {\n val magic = readUtf8LineStrict()\n val version = readUtf8LineStrict()\n val appVersionString = readUtf8LineStrict()\n val valueCountString = readUtf8LineStrict()\n val blank = readUtf8LineStrict()\n\n if (MAGIC != magic ||\n VERSION_1 != version ||\n appVersion.toString() != appVersionString ||\n valueCount.toString() != valueCountString ||\n blank.isNotEmpty()\n ) {\n throw IOException(\n \"unexpected journal header: [$magic, $version, $valueCountString, $blank]\",\n )\n }\n\n var lineCount = 0\n while (true) {\n try {\n readJournalLine(readUtf8LineStrict())\n lineCount++\n } catch (_: EOFException) {\n break // End of journal.\n }\n }\n\n redundantOpCount = lineCount - lruEntries.size\n\n // If we ended on a truncated line, rebuild the journal before appending to it.\n if (!exhausted()) {\n rebuildJournal()\n } else {\n journalWriter?.closeQuietly()\n journalWriter = newJournalWriter()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":319,"symbol":"newJournalWriter","kind":"function","lang":"kotlin","code":"@Throws(FileNotFoundException::class)\n private fun newJournalWriter(): BufferedSink {\n val fileSink = fileSystem.appendingSink(journalFile)\n val faultHidingSink =\n FaultHidingSink(fileSink) {\n assertLockHeld()\n hasJournalErrors = true\n }\n return faultHidingSink.buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":330,"symbol":"readJournalLine","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readJournalLine(line: String) {\n val firstSpace = line.indexOf(' ')\n if (firstSpace == -1) throw IOException(\"unexpected journal line: $line\")\n\n val keyBegin = firstSpace + 1\n val secondSpace = line.indexOf(' ', keyBegin)\n val key: String\n if (secondSpace == -1) {\n key = line.substring(keyBegin)\n if (firstSpace == REMOVE.length && line.startsWith(REMOVE)) {\n lruEntries.remove(key)\n return\n }\n } else {\n key = line.substring(keyBegin, secondSpace)\n }\n\n var entry: Entry? = lruEntries[key]\n if (entry == null) {\n entry = Entry(key)\n lruEntries[key] = entry\n }\n\n when {\n secondSpace != -1 && firstSpace == CLEAN.length && line.startsWith(CLEAN) -> {\n val parts =\n line\n .substring(secondSpace + 1)\n .split(' ')\n entry.readable = true\n entry.currentEditor = null\n entry.setLengths(parts)\n }\n\n secondSpace == -1 && firstSpace == DIRTY.length && line.startsWith(DIRTY) -> {\n entry.currentEditor = Editor(entry)\n }\n\n secondSpace == -1 && firstSpace == READ.length && line.startsWith(READ) ->"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":383,"symbol":"processJournal","kind":"function","lang":"kotlin","doc":"Computes the initial size and collects garbage as a part of opening the cache. Dirty entries are assumed to be inconsistent and will be deleted.","code":"@Throws(IOException::class)\n private fun processJournal() {\n fileSystem.deleteIfExists(journalFileTmp)\n val i = lruEntries.values.iterator()\n while (i.hasNext()) {\n val entry = i.next()\n if (entry.currentEditor == null) {\n for (t in 0 until valueCount) {\n size += entry.lengths[t]\n }\n } else {\n entry.currentEditor = null\n for (t in 0 until valueCount) {\n fileSystem.deleteIfExists(entry.cleanFiles[t])\n fileSystem.deleteIfExists(entry.dirtyFiles[t])\n }\n i.remove()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":408,"symbol":"rebuildJournal","kind":"function","lang":"kotlin","doc":"Creates a new journal that omits redundant information. This replaces the current journal if it exists.","code":"@Synchronized\n @Throws(IOException::class)\n internal fun rebuildJournal() {\n journalWriter?.close()\n\n fileSystem.write(journalFileTmp) {\n writeUtf8(MAGIC).writeByte('\\n'.code)\n writeUtf8(VERSION_1).writeByte('\\n'.code)\n writeDecimalLong(appVersion.toLong()).writeByte('\\n'.code)\n writeDecimalLong(valueCount.toLong()).writeByte('\\n'.code)\n writeByte('\\n'.code)\n\n for (entry in lruEntries.values) {\n if (entry.currentEditor != null) {\n writeUtf8(DIRTY).writeByte(' '.code)\n writeUtf8(entry.key)\n writeByte('\\n'.code)\n } else {\n writeUtf8(CLEAN).writeByte(' '.code)\n writeUtf8(entry.key)\n entry.writeLengths(this)\n writeByte('\\n'.code)\n }\n }\n }\n\n if (fileSystem.exists(journalFile)) {\n fileSystem.atomicMove(journalFile, journalFileBackup)\n fileSystem.atomicMove(journalFileTmp, journalFile)\n fileSystem.deleteIfExists(journalFileBackup)\n } else {\n fileSystem.atomicMove(journalFileTmp, journalFile)\n }\n\n journalWriter?.closeQuietly()\n journalWriter = newJournalWriter()\n hasJournalErrors = false\n mostRecentRebuildFailed = false\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":452,"symbol":"get","kind":"function","lang":"kotlin","doc":"Returns a snapshot of the entry named [key], or null if it doesn't exist is not currently readable. If a value is returned, it is moved to the head of the LRU queue.","code":"@Synchronized\n @Throws(IOException::class)\n operator fun get(key: String): Snapshot? {\n initialize()\n\n checkNotClosed()\n validateKey(key)\n val entry = lruEntries[key] ?: return null\n val snapshot = entry.snapshot() ?: return null\n\n redundantOpCount++\n journalWriter!!\n .writeUtf8(READ)\n .writeByte(' '.code)\n .writeUtf8(key)\n .writeByte('\\n'.code)\n if (journalRebuildRequired()) {\n cleanupQueue.schedule(cleanupTask)\n }\n\n return snapshot\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":476,"symbol":"edit","kind":"function","lang":"kotlin","doc":"Returns an editor for the entry named [key], or null if another edit is in progress.","code":"@Synchronized\n @Throws(IOException::class)\n @JvmOverloads\n fun edit(\n key: String,\n expectedSequenceNumber: Long = ANY_SEQUENCE_NUMBER,\n ): Editor? {\n initialize()\n\n checkNotClosed()\n validateKey(key)\n var entry: Entry? = lruEntries[key]\n if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER &&\n (entry == null || entry.sequenceNumber != expectedSequenceNumber)\n ) {\n return null // Snapshot is stale.\n }\n\n if (entry?.currentEditor != null) {\n return null // Another edit is in progress.\n }\n\n if (entry != null && entry.lockingSourceCount != 0) {\n return null // We can't write this file because a reader is still reading it.\n }\n\n if (mostRecentTrimFailed || mostRecentRebuildFailed) {\n // The OS has become our enemy! If the trim job failed, it means we are storing more data than\n // requested by the user. Do not allow edits so we do not go over that limit any further. If\n // the journal rebuild failed, the journal writer will not be active, meaning we will not be\n // able to record the edit, causing file leaks. In both cases, we want to retry the clean up\n // so we can get out of this state!\n clean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":538,"symbol":"size","kind":"function","lang":"kotlin","doc":"Returns the number of bytes currently being used to store the values in this cache. This may be greater than the max size if a background deletion is pending.","code":"@Synchronized\n @Throws(IOException::class)\n fun size(): Long {\n initialize()\n return size\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":545,"symbol":"completeEdit","kind":"function","lang":"kotlin","code":"@Synchronized\n @Throws(IOException::class)\n internal fun completeEdit(\n editor: Editor,\n success: Boolean,\n ) {\n val entry = editor.entry\n check(entry.currentEditor == editor)\n\n // If this edit is creating the entry for the first time, every index must have a value.\n if (success && !entry.readable) {\n for (i in 0 until valueCount) {\n if (!editor.written!![i]) {\n editor.abort()\n throw IllegalStateException(\"Newly created entry didn't create value for index $i\")\n }\n if (!fileSystem.exists(entry.dirtyFiles[i])) {\n editor.abort()\n return\n }\n }\n }\n\n for (i in 0 until valueCount) {\n val dirty = entry.dirtyFiles[i]\n if (success && !entry.zombie) {\n if (fileSystem.exists(dirty)) {\n val clean = entry.cleanFiles[i]\n fileSystem.atomicMove(dirty, clean)\n val oldLength = entry.lengths[i]\n // TODO check null behaviour\n val newLength = fileSystem.metadata(clean).size ?: 0\n entry.lengths[i] = newLength\n size = size - oldLength + newLength\n }\n } else {\n fileSystem.deleteIfExists(dirty)\n }\n }\n\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":620,"symbol":"journalRebuildRequired","kind":"function","lang":"kotlin","doc":"We only rebuild the journal when it will halve the size of the journal and eliminate at least 2000 ops.","code":"private fun journalRebuildRequired(): Boolean {\n val redundantOpCompactThreshold = 2000\n return redundantOpCount >= redundantOpCompactThreshold &&\n redundantOpCount >= lruEntries.size\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":632,"symbol":"remove","kind":"function","lang":"kotlin","doc":"Drops the entry for [key] if it exists and can be removed. If the entry for [key] is currently being edited, that edit will complete normally but its value will not be stored. @return true if an entry was removed.","code":"@Synchronized\n @Throws(IOException::class)\n fun remove(key: String): Boolean {\n initialize()\n\n checkNotClosed()\n validateKey(key)\n val entry = lruEntries[key] ?: return false\n val removed = removeEntry(entry)\n if (removed && size <= maxSize) mostRecentTrimFailed = false\n return removed\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":645,"symbol":"removeEntry","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n internal fun removeEntry(entry: Entry): Boolean {\n // If we can't delete files that are still open, mark this entry as a zombie so its files will\n // be deleted when those files are closed.\n if (!civilizedFileSystem) {\n if (entry.lockingSourceCount > 0) {\n // Mark this entry as 'DIRTY' so that if the process crashes this entry won't be used.\n journalWriter?.let {\n it.writeUtf8(DIRTY)\n it.writeByte(' '.code)\n it.writeUtf8(entry.key)\n it.writeByte('\\n'.code)\n it.flush()\n }\n }\n if (entry.lockingSourceCount > 0 || entry.currentEditor != null) {\n entry.zombie = true\n return true\n }\n }\n\n entry.currentEditor?.detach() // Prevent the edit from completing normally.\n\n for (i in 0 until valueCount) {\n fileSystem.deleteIfExists(entry.cleanFiles[i])\n size -= entry.lengths[i]\n entry.lengths[i] = 0\n }\n\n redundantOpCount++\n journalWriter?.let {\n it.writeUtf8(REMOVE)\n it.writeByte(' '.code)\n it.writeUtf8(entry.key)\n it.writeByte('\\n'.code)\n }\n lruEntries.remove(entry.key)\n\n if (journalRebuildRequired("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":690,"symbol":"checkNotClosed","kind":"function","lang":"kotlin","code":"@Synchronized private fun checkNotClosed() {\n check(!closed) { \"cache is closed\" }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":695,"symbol":"flush","kind":"function","lang":"kotlin","doc":"Force buffered operations to the filesystem.","code":"@Synchronized\n @Throws(IOException::class)\n override fun flush() {\n if (!initialized) return\n\n checkNotClosed()\n trimToSize()\n journalWriter!!.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":705,"symbol":"isClosed","kind":"function","lang":"kotlin","code":"@Synchronized fun isClosed(): Boolean = closed"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":708,"symbol":"close","kind":"function","lang":"kotlin","doc":"Closes this cache. Stored values will remain on the filesystem.","code":"@Synchronized\n @Throws(IOException::class)\n override fun close() {\n if (!initialized || closed) {\n closed = true\n return\n }\n\n // Copying for concurrent iteration.\n for (entry in lruEntries.values.toTypedArray()) {\n if (entry.currentEditor != null) {\n entry.currentEditor?.detach() // Prevent the edit from completing normally.\n }\n }\n\n trimToSize()\n journalWriter?.closeQuietly()\n journalWriter = null\n closed = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":729,"symbol":"trimToSize","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun trimToSize() {\n while (size > maxSize) {\n if (!removeOldestEntry()) return\n }\n mostRecentTrimFailed = false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":738,"symbol":"removeOldestEntry","kind":"function","lang":"kotlin","doc":"Returns true if an entry was removed. This will return false if all entries are zombies.","code":"private fun removeOldestEntry(): Boolean {\n for (toEvict in lruEntries.values) {\n if (!toEvict.zombie) {\n removeEntry(toEvict)\n return true\n }\n }\n return false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":752,"symbol":"delete","kind":"function","lang":"kotlin","doc":"Closes the cache and deletes all of its stored values. This will delete all files in the cache directory including files that weren't created by the cache.","code":"@Throws(IOException::class)\n fun delete() {\n close()\n fileSystem.deleteContents(directory)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":762,"symbol":"evictAll","kind":"function","lang":"kotlin","doc":"Deletes all stored values from the cache. In-flight edits will complete normally but their values will not be stored.","code":"@Synchronized\n @Throws(IOException::class)\n fun evictAll() {\n initialize()\n // Copying for concurrent iteration.\n for (entry in lruEntries.values.toTypedArray()) {\n removeEntry(entry)\n }\n mostRecentTrimFailed = false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":773,"symbol":"validateKey","kind":"function","lang":"kotlin","code":"private fun validateKey(key: String) {\n require(LEGAL_KEY_PATTERN.matches(key)) { \"keys must match regex [a-z0-9_-]{1,120}: \\\"$key\\\"\" }\n }\n\n /**\n * Returns an iterator over the cache's current entries. This iterator doesn't throw\n * `ConcurrentModificationException`, but if new entries are added while iterating, those new\n * entries will not be returned by the iterator. If existing entries are removed during iteration,\n * they will be absent (unless they were already returned).\n *\n * If there are I/O problems during iteration, this iterator fails silently. For example, if the\n * hosting filesystem becomes unreachable, the iterator will omit elements rather than throwing\n * exceptions.\n *\n * **The caller must [close][Snapshot.close]** each snapshot returned by [Iterator.next]. Failing\n * to do so leaks open files!\n */\n @Synchronized\n @Throws(IOException::class)\n fun snapshots(): MutableIterator {\n initialize()\n return object : MutableIterator {\n /** Iterate a copy of the entries to defend against concurrent modification errors. */\n private val delegate = ArrayList(lruEntries.values).iterator()\n\n /** The snapsho"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":843,"symbol":"Snapshot","kind":"class","lang":"kotlin","doc":"A snapshot of the values for an entry.","code":"inner class Snapshot internal constructor(\n private val key: String,\n private val sequenceNumber: Long,\n private val sources: List,\n private val lengths: LongArray,\n ) : Closeable {\n fun key(): String = key\n\n /**\n * Returns an editor for this snapshot's entry, or null if either the entry has changed since\n * this snapshot was created or if another edit is in progress.\n */\n @Throws(IOException::class)\n fun edit(): Editor? = this@DiskLruCache.edit(key, sequenceNumber)\n\n /** Returns the unbuffered stream with the value for [index]. */\n fun getSource(index: Int): Source = sources[index]\n\n /** Returns the byte length of the value for [index]. */\n fun getLength(index: Int): Long = lengths[index]\n\n override fun close() {\n for (source in sources) {\n source.closeQuietly()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":849,"symbol":"key","kind":"function","lang":"kotlin","code":"fun key(): String = key"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":855,"symbol":"edit","kind":"function","lang":"kotlin","doc":"Returns an editor for this snapshot's entry, or null if either the entry has changed since this snapshot was created or if another edit is in progress.","code":"@Throws(IOException::class)\n fun edit(): Editor? = this@DiskLruCache.edit(key, sequenceNumber)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":859,"symbol":"getSource","kind":"function","lang":"kotlin","doc":"Returns the unbuffered stream with the value for [index].","code":"fun getSource(index: Int): Source = sources[index]"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":862,"symbol":"getLength","kind":"function","lang":"kotlin","doc":"Returns the byte length of the value for [index].","code":"fun getLength(index: Int): Long = lengths[index]"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":864,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n for (source in sources) {\n source.closeQuietly()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":872,"symbol":"Editor","kind":"class","lang":"kotlin","doc":"Edits the values for an entry.","code":"inner class Editor internal constructor(\n internal val entry: Entry,\n ) {\n internal val written: BooleanArray? = if (entry.readable) null else BooleanArray(valueCount)\n private var done: Boolean = false\n\n /**\n * Prevents this editor from completing normally. This is necessary either when the edit causes\n * an I/O error, or if the target entry is evicted while this editor is active. In either case\n * we delete the editor's created files and prevent new files from being created. Note that once\n * an editor has been detached it is possible for another editor to edit the entry.\n */\n internal fun detach() {\n if (entry.currentEditor == this) {\n if (civilizedFileSystem) {\n completeEdit(this, false) // Delete it now.\n } else {\n entry.zombie = true // We can't delete it until the current edit completes.\n }\n }\n }\n\n /**\n * Returns an unbuffered input stream to read the last committed value, or null if no value has\n * been committed.\n */\n fun newSource(index: Int): Source? {\n synchronized(this@DiskLruCache) {\n check(!done)\n if (!entry.readable || entry.currentEditor != t"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":884,"symbol":"detach","kind":"function","lang":"kotlin","doc":"Prevents this editor from completing normally. This is necessary either when the edit causes an I/O error, or if the target entry is evicted while this editor is active. In either case we delete the editor's created files and prevent new files from being created. Note that once an editor has been detached it is possible for another editor to edit the entry.","code":"internal fun detach() {\n if (entry.currentEditor == this) {\n if (civilizedFileSystem) {\n completeEdit(this, false) // Delete it now.\n } else {\n entry.zombie = true // We can't delete it until the current edit completes.\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":898,"symbol":"newSource","kind":"function","lang":"kotlin","doc":"Returns an unbuffered input stream to read the last committed value, or null if no value has been committed.","code":"fun newSource(index: Int): Source? {\n synchronized(this@DiskLruCache) {\n check(!done)\n if (!entry.readable || entry.currentEditor != this || entry.zombie) {\n return null\n }\n return try {\n fileSystem.source(entry.cleanFiles[index])\n } catch (_: FileNotFoundException) {\n null\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":917,"symbol":"newSink","kind":"function","lang":"kotlin","doc":"Returns a new unbuffered output stream to write the value at [index]. If the underlying output stream encounters errors when writing to the filesystem, this edit will be aborted when [commit] is called. The returned output stream does not throw IOExceptions.","code":"fun newSink(index: Int): Sink {\n synchronized(this@DiskLruCache) {\n check(!done)\n if (entry.currentEditor != this) {\n return blackholeSink()\n }\n if (!entry.readable) {\n written!![index] = true\n }\n val dirtyFile = entry.dirtyFiles[index]\n val sink: Sink\n try {\n sink = fileSystem.sink(dirtyFile)\n } catch (_: FileNotFoundException) {\n return blackholeSink()\n }\n return FaultHidingSink(sink) {\n synchronized(this@DiskLruCache) {\n detach()\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":945,"symbol":"commit","kind":"function","lang":"kotlin","doc":"Commits this edit so it is visible to readers. This releases the edit lock so another edit may be started on the same key.","code":"@Throws(IOException::class)\n fun commit() {\n synchronized(this@DiskLruCache) {\n check(!done)\n if (entry.currentEditor == this) {\n completeEdit(this, true)\n }\n done = true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":960,"symbol":"abort","kind":"function","lang":"kotlin","doc":"Aborts this edit. This releases the edit lock so another edit may be started on the same key.","code":"@Throws(IOException::class)\n fun abort() {\n synchronized(this@DiskLruCache) {\n check(!done)\n if (entry.currentEditor == this) {\n completeEdit(this, false)\n }\n done = true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":972,"symbol":"Entry","kind":"class","lang":"kotlin","code":"internal inner class Entry internal constructor(\n internal val key: String,\n ) {\n /** Lengths of this entry's files. */\n internal val lengths: LongArray = LongArray(valueCount)\n internal val cleanFiles = mutableListOf()\n internal val dirtyFiles = mutableListOf()\n\n /** True if this entry has ever been published. */\n internal var readable: Boolean = false\n\n /** True if this entry must be deleted when the current edit or read completes. */\n internal var zombie: Boolean = false\n\n /**\n * The ongoing edit or null if this entry is not being edited. When setting this to null the\n * entry must be removed if it is a zombie.\n */\n internal var currentEditor: Editor? = null\n\n /**\n * Sources currently reading this entry before a write or delete can proceed. When decrementing\n * this to zero, the entry must be removed if it is a zombie.\n */\n internal var lockingSourceCount = 0\n\n /** The sequence number of the most recently committed edit to this entry. */\n internal var sequenceNumber: Long = 0\n\n init {\n // The names are repetitive so re-use the same builder to avoid allocations.\n val fileBuilder = Strin"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":1015,"symbol":"setLengths","kind":"function","lang":"kotlin","doc":"Set lengths using decimal numbers like \"10123\".","code":"@Throws(IOException::class)\n internal fun setLengths(strings: List) {\n if (strings.size != valueCount) {\n invalidLengths(strings)\n }\n\n try {\n for (i in strings.indices) {\n lengths[i] = strings[i].toLong()\n }\n } catch (_: NumberFormatException) {\n invalidLengths(strings)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":1031,"symbol":"writeLengths","kind":"function","lang":"kotlin","doc":"Append space-prefixed lengths to [writer].","code":"@Throws(IOException::class)\n internal fun writeLengths(writer: BufferedSink) {\n for (length in lengths) {\n writer.writeByte(' '.code).writeDecimalLong(length)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":1038,"symbol":"invalidLengths","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun invalidLengths(strings: List): Nothing = throw IOException(\"unexpected journal line: $strings\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":1046,"symbol":"snapshot","kind":"function","lang":"kotlin","doc":"Returns a snapshot of this entry. This opens all streams eagerly to guarantee that we see a single published snapshot. If we opened streams lazily then the streams could come from different edits.","code":"internal fun snapshot(): Snapshot? {\n assertLockHeld()\n\n if (!readable) return null\n if (!civilizedFileSystem && (currentEditor != null || zombie)) return null\n\n val sources = mutableListOf()\n val lengths = this.lengths.clone() // Defensive copy since these can be zeroed out.\n try {\n for (i in 0 until valueCount) {\n sources += newSource(i)\n }\n return Snapshot(key, sequenceNumber, sources, lengths)\n } catch (_: FileNotFoundException) {\n // A file must have been deleted manually!\n for (source in sources) {\n source.closeQuietly()\n }\n // Since the entry is no longer valid, remove it so the metadata is accurate (i.e. the cache\n // size.)\n try {\n removeEntry(this)\n } catch (_: IOException) {\n }\n return null\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":1074,"symbol":"newSource","kind":"function","lang":"kotlin","code":"private fun newSource(index: Int): Source {\n val fileSource = fileSystem.source(cleanFiles[index])\n if (civilizedFileSystem) return fileSource\n\n lockingSourceCount++\n return object : ForwardingSource(fileSource) {\n private var closed = false\n\n override fun close() {\n super.close()\n if (!closed) {\n closed = true\n synchronized(this@DiskLruCache) {\n lockingSourceCount--\n if (lockingSourceCount == 0 && zombie) {\n removeEntry(this@Entry)\n }\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/DiskLruCache.kt","line":1082,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n super.close()\n if (!closed) {\n closed = true\n synchronized(this@DiskLruCache) {\n lockingSourceCount--\n if (lockingSourceCount == 0 && zombie) {\n removeEntry(this@Entry)\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/FaultHidingSink.kt","line":24,"symbol":"FaultHidingSink","kind":"class","lang":"kotlin","doc":"A sink that never throws IOExceptions, even if the underlying sink does.","code":"internal open class FaultHidingSink(\n delegate: Sink,\n val onException: (IOException) -> Unit,\n) : ForwardingSink(delegate) {\n private var hasErrors = false\n\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n if (hasErrors) {\n source.skip(byteCount)\n return\n }\n try {\n super.write(source, byteCount)\n } catch (e: IOException) {\n hasErrors = true\n onException(e)\n }\n }\n\n override fun flush() {\n if (hasErrors) {\n return\n }\n try {\n super.flush()\n } catch (e: IOException) {\n hasErrors = true\n onException(e)\n }\n }\n\n override fun close() {\n try {\n super.close()\n } catch (e: IOException) {\n hasErrors = true\n onException(e)\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/FaultHidingSink.kt","line":30,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n if (hasErrors) {\n source.skip(byteCount)\n return\n }\n try {\n super.write(source, byteCount)\n } catch (e: IOException) {\n hasErrors = true\n onException(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/FaultHidingSink.kt","line":46,"symbol":"flush","kind":"function","lang":"kotlin","code":"override fun flush() {\n if (hasErrors) {\n return\n }\n try {\n super.flush()\n } catch (e: IOException) {\n hasErrors = true\n onException(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/cache/FaultHidingSink.kt","line":58,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n try {\n super.close()\n } catch (e: IOException) {\n hasErrors = true\n onException(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Lockable.kt","line":33,"symbol":"Lockable","kind":"interface","lang":"kotlin","doc":"Marker interface for objects that use the JVM's `synchronized` mechanism and the related `wait()` and `notify()` functions. The Lockable interface is particularly handy because it ensures we lock the right `this` when there are multiple `this` objects in scope.","code":"interface Lockable"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Lockable.kt","line":35,"symbol":"wait","kind":"function","lang":"kotlin","code":"@OkHttpInternalApi\ninline fun Lockable.wait() = (this as Object).wait()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Lockable.kt","line":38,"symbol":"notify","kind":"function","lang":"kotlin","code":"@OkHttpInternalApi\ninline fun Lockable.notify() = (this as Object).notify()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Lockable.kt","line":41,"symbol":"notifyAll","kind":"function","lang":"kotlin","code":"@OkHttpInternalApi\ninline fun Lockable.notifyAll() = (this as Object).notifyAll()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Lockable.kt","line":44,"symbol":"awaitNanos","kind":"function","lang":"kotlin","code":"@OkHttpInternalApi\ninline fun Lockable.awaitNanos(nanos: Long) {\n val ms = nanos / 1_000_000L\n val ns = nanos - (ms * 1_000_000L)\n if (ms > 0L || nanos > 0) {\n (this as Object).wait(ms, ns.toInt())\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Lockable.kt","line":59,"symbol":"assertLockHeld","kind":"function","lang":"kotlin","code":"internal inline fun Lockable.assertLockHeld() {\n if (assertionsEnabled && !Thread.holdsLock(this)) {\n throw AssertionError(\"Thread ${Thread.currentThread().name} MUST hold lock on $this\")\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Lockable.kt","line":65,"symbol":"withLock","kind":"function","lang":"kotlin","code":"@OptIn(ExperimentalContracts::class)\ninline fun Lockable.withLock(action: () -> T): T {\n contract { callsInPlace(action, InvocationKind.EXACTLY_ONCE) }\n return synchronized(this, action)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Task.kt","line":49,"symbol":"Task","kind":"class","lang":"kotlin","doc":"Task Queues ----------- Tasks are bound to the [TaskQueue] they are scheduled in. Each queue is sequential and the tasks within it never execute concurrently. It is an error to use a task in multiple queues.","code":"abstract class Task(\n val name: String,\n val cancelable: Boolean = true,\n) {\n // Guarded by the TaskRunner.\n internal var queue: TaskQueue? = null\n\n /** Undefined unless this is in [TaskQueue.futureTasks]. */\n internal var nextExecuteNanoTime = -1L\n\n /** Returns the delay in nanoseconds until the next execution, or -1L to not reschedule. */\n abstract fun runOnce(): Long\n\n internal fun initQueue(queue: TaskQueue) {\n if (this.queue === queue) return\n\n check(this.queue === null) { \"task is in multiple queues\" }\n this.queue = queue\n }\n\n override fun toString(): String = name\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Task.kt","line":60,"symbol":"runOnce","kind":"function","lang":"kotlin","doc":"Returns the delay in nanoseconds until the next execution, or -1L to not reschedule.","code":"abstract fun runOnce(): Long"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Task.kt","line":62,"symbol":"initQueue","kind":"function","lang":"kotlin","code":"internal fun initQueue(queue: TaskQueue) {\n if (this.queue === queue) return\n\n check(this.queue === null) { \"task is in multiple queues\" }\n this.queue = queue\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/Task.kt","line":69,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = name"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskLogger.kt","line":31,"symbol":"logElapsed","kind":"function","lang":"kotlin","code":"internal inline fun Logger.logElapsed(\n task: Task,\n queue: TaskQueue,\n block: () -> T,\n): T {\n var startNs = -1L\n val loggingEnabled = isLoggable(Level.FINE)\n if (loggingEnabled) {\n startNs = queue.taskRunner.backend.nanoTime()\n log(task, queue, \"starting\")\n }\n\n var completedNormally = false\n try {\n val result = block()\n completedNormally = true\n return result\n } finally {\n if (loggingEnabled) {\n val elapsedNs = queue.taskRunner.backend.nanoTime() - startNs\n if (completedNormally) {\n log(task, queue, \"finished run in ${formatDuration(elapsedNs)}\")\n } else {\n log(task, queue, \"failed a run in ${formatDuration(elapsedNs)}\")\n }\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskLogger.kt","line":60,"symbol":"log","kind":"function","lang":"kotlin","code":"private fun Logger.log(\n task: Task,\n queue: TaskQueue,\n message: String,\n) {\n fine(\"${queue.name} ${String.format(\"%-22s\", message)}: ${task.name}\")\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskLogger.kt","line":76,"symbol":"formatDuration","kind":"function","lang":"kotlin","doc":"units away from 0 and 0.499 towards 0. The smallest unit this returns is \"µs\"; the largest unit it returns is \"s\". For values in [-499..499] this returns \" 0 µs\". The returned string attempts to be column-aligned to 6 characters. For negative and large values the returned string may be longer.","code":"fun formatDuration(ns: Long): String {\n val s =\n when {\n ns <= -999_500_000 -> \"${(ns - 500_000_000) / 1_000_000_000} s \"\n ns <= -999_500 -> \"${(ns - 500_000) / 1_000_000} ms\"\n ns <= 0 -> \"${(ns - 500) / 1_000} µs\"\n ns < 999_500 -> \"${(ns + 500) / 1_000} µs\"\n ns < 999_500_000 -> \"${(ns + 500_000) / 1_000_000} ms\"\n else -> \"${(ns + 500_000_000) / 1_000_000_000} s \"\n }\n return String.format(\"%6s\", s)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":28,"symbol":"TaskQueue","kind":"class","lang":"kotlin","doc":"A set of tasks that are executed in sequential order. Work within queues is not concurrent. This is equivalent to each queue having a dedicated thread for its work; in practice a set of queues may share a set of threads to save resources.","code":"class TaskQueue internal constructor(\n internal val taskRunner: TaskRunner,\n internal val name: String,\n) {\n internal var shutdown = false\n\n /** This queue's currently-executing task, or null if none is currently executing. */\n internal var activeTask: Task? = null\n\n /** Scheduled tasks ordered by [Task.nextExecuteNanoTime]. */\n internal val futureTasks = mutableListOf()\n\n /** True if the [activeTask] should be canceled when it completes. */\n internal var cancelActiveTask = false\n\n /**\n * Returns a snapshot of tasks currently scheduled for execution. Does not include the\n * currently-executing task unless it is also scheduled for future execution.\n */\n val scheduledTasks: List\n get() = taskRunner.withLock { futureTasks.toList() }\n\n /**\n * Schedules [task] for execution in [delayNanos]. A task may only have one future execution\n * scheduled. If the task is already in the queue, the earliest execution time is used.\n *\n * The target execution time is implemented on a best-effort basis. If another task in this queue\n * is running when that time is reached, that task is allowed to complete before this task is\n * started. Similarly the task wi"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":60,"symbol":"schedule","kind":"function","lang":"kotlin","doc":"The target execution time is implemented on a best-effort basis. If another task in this queue is running when that time is reached, that task is allowed to complete before this task is started. Similarly the task will be delayed if the host lacks compute resources. @throws RejectedExecutionException if the queue is shut down and the task is not cancelable.","code":"fun schedule(\n task: Task,\n delayNanos: Long = 0L,\n ) {\n taskRunner.withLock {\n if (shutdown) {\n if (task.cancelable) {\n taskRunner.logger.taskLog(task, this) { \"schedule canceled (queue is shutdown)\" }\n return\n }\n taskRunner.logger.taskLog(task, this) { \"schedule failed (queue is shutdown)\" }\n throw RejectedExecutionException()\n }\n\n if (scheduleAndDecide(task, delayNanos, recurrence = false)) {\n taskRunner.kickCoordinator(this)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":85,"symbol":"schedule","kind":"function","lang":"kotlin","doc":"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","code":"fun schedule(\n name: String,\n delayNanos: Long = 0L,\n block: () -> Long,\n ) {\n schedule(\n object : Task(name) {\n override fun runOnce(): Long = block()\n },\n delayNanos,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":92,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long = block()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":103,"symbol":"execute","kind":"function","lang":"kotlin","doc":"Executes [block] once on a task runner thread. TODO: make this inline once this is fixed: https://github.com/oracle/graal/issues/3466","code":"fun execute(\n name: String,\n delayNanos: Long = 0L,\n cancelable: Boolean = true,\n block: () -> Unit,\n ) {\n schedule(\n object : Task(name, cancelable) {\n override fun runOnce(): Long {\n block()\n return -1L\n }\n },\n delayNanos,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":111,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n block()\n return -1L\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":121,"symbol":"idleLatch","kind":"function","lang":"kotlin","doc":"Returns a latch that reaches 0 when the queue is next idle.","code":"fun idleLatch(): CountDownLatch {\n taskRunner.withLock {\n // If the queue is already idle, that's easy.\n if (activeTask == null && futureTasks.isEmpty()) {\n return CountDownLatch(0)\n }\n\n // If there's an existing AwaitIdleTask, use it. This is necessary when the executor is\n // shutdown but still busy as we can't enqueue in that case.\n val existingTask = activeTask\n if (existingTask is AwaitIdleTask) {\n return existingTask.latch\n }\n for (futureTask in futureTasks) {\n if (futureTask is AwaitIdleTask) {\n return futureTask.latch\n }\n }\n\n // Don't delegate to schedule() because that enforces shutdown rules.\n val newTask = AwaitIdleTask()\n if (scheduleAndDecide(newTask, 0L, recurrence = false)) {\n taskRunner.kickCoordinator(this)\n }\n return newTask.latch\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":149,"symbol":"AwaitIdleTask","kind":"class","lang":"kotlin","code":"private class AwaitIdleTask : Task(\"$okHttpName awaitIdle\", cancelable = false) {\n val latch = CountDownLatch(1)\n\n override fun runOnce(): Long {\n latch.countDown()\n return -1L\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":152,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n latch.countDown()\n return -1L\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":159,"symbol":"scheduleAndDecide","kind":"function","lang":"kotlin","doc":"Adds [task] to run in [delayNanos]. Returns true if the coordinator is impacted.","code":"internal fun scheduleAndDecide(\n task: Task,\n delayNanos: Long,\n recurrence: Boolean,\n ): Boolean {\n task.initQueue(this)\n\n val now = taskRunner.backend.nanoTime()\n val executeNanoTime = now + delayNanos\n\n // If the task is already scheduled, take the earlier of the two times.\n val existingIndex = futureTasks.indexOf(task)\n if (existingIndex != -1) {\n if (task.nextExecuteNanoTime <= executeNanoTime) {\n taskRunner.logger.taskLog(task, this) { \"already scheduled\" }\n return false\n }\n futureTasks.removeAt(existingIndex) // Already scheduled later: reschedule below!\n }\n task.nextExecuteNanoTime = executeNanoTime\n taskRunner.logger.taskLog(task, this) {\n if (recurrence) {\n \"run again after ${formatDuration(executeNanoTime - now)}\"\n } else {\n \"scheduled after ${formatDuration(executeNanoTime - now)}\"\n }\n }\n\n // Insert in chronological order. Always compare deltas because nanoTime() is permitted to wrap.\n var insertAt = futureTasks.indexOfFirst { it.nextExecuteNanoTime - now > delayNanos }\n if (insertAt == -1) insertAt = futureTasks.size\n futureTasks.add(insertAt, task)\n\n // Imp"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":201,"symbol":"cancelAll","kind":"function","lang":"kotlin","doc":"Schedules immediate execution of [Task.tryCancel] on all currently-enqueued tasks. These calls will not be made until any currently-executing task has completed. Tasks that return true will be removed from the execution schedule.","code":"fun cancelAll() {\n taskRunner.assertLockNotHeld()\n\n taskRunner.withLock {\n if (cancelAllAndDecide()) {\n taskRunner.kickCoordinator(this)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":211,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"fun shutdown() {\n taskRunner.assertLockNotHeld()\n\n taskRunner.withLock {\n shutdown = true\n if (cancelAllAndDecide()) {\n taskRunner.kickCoordinator(this)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":223,"symbol":"cancelAllAndDecide","kind":"function","lang":"kotlin","doc":"Returns true if the coordinator is impacted.","code":"internal fun cancelAllAndDecide(): Boolean {\n if (activeTask != null && activeTask!!.cancelable) {\n cancelActiveTask = true\n }\n\n var tasksCanceled = false\n for (i in futureTasks.size - 1 downTo 0) {\n if (futureTasks[i].cancelable) {\n taskRunner.logger.taskLog(futureTasks[i], this) { \"canceled\" }\n tasksCanceled = true\n futureTasks.removeAt(i)\n }\n }\n return tasksCanceled\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskQueue.kt","line":239,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = name"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":40,"symbol":"TaskRunner","kind":"class","lang":"kotlin","doc":"The task runner is also responsible for releasing held threads when the library is unloaded. This is for the benefit of container environments that implement code unloading. Most applications should share a process-wide [TaskRunner] and use queues for per-client work.","code":"class TaskRunner(\n val backend: Backend,\n internal val logger: Logger = TaskRunner.logger,\n) : Lockable {\n private var nextQueueName = 10000\n private var coordinatorWaiting = false\n private var coordinatorWakeUpAt = 0L\n\n /**\n * When we need a new thread to run tasks, we call [Backend.execute]. A few microseconds later we\n * expect a newly-started thread to call [Runnable.run]. We shouldn't request new threads until\n * the already-requested ones are in service, otherwise we might create more threads than we need.\n *\n * We use [executeCallCount] and [runCallCount] to defend against starting more threads than we\n * need. Both fields are guarded by `this`.\n */\n private var executeCallCount = 0\n private var runCallCount = 0\n\n /** Queues with tasks that are currently executing their [TaskQueue.activeTask]. */\n private val busyQueues = mutableListOf()\n\n /** Queues not in [busyQueues] that have non-empty [TaskQueue.futureTasks]. */\n private val readyQueues = mutableListOf()\n\n private val runnable: Runnable =\n object : Runnable {\n override fun run() {\n var task: Task =\n withLock {\n runCallCount++\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":67,"symbol":"run","kind":"function","lang":"kotlin","code":"override fun run() {\n var task: Task =\n withLock {\n runCallCount++\n awaitTaskToRun()\n } ?: return\n\n val currentThread = Thread.currentThread()\n val oldName = currentThread.name\n try {\n while (true) {\n currentThread.name = task.name\n val delayNanos =\n logger.logElapsed(task, task.queue!!) {\n task.runOnce()\n }\n\n // A task ran successfully. Update the execution state and take the next task.\n task = withLock {\n afterRun(task, delayNanos, true)\n awaitTaskToRun()\n } ?: return\n }\n } catch (thrown: Throwable) {\n // A task failed. Update execution state and re-throw the exception.\n withLock {\n afterRun(task, -1L, false)\n }\n if (thrown is InterruptedException) {\n Thread.currentThread().interrupt()\n } else {\n throw thrown\n }\n } finally {\n currentThread.name = oldName\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":106,"symbol":"kickCoordinator","kind":"function","lang":"kotlin","code":"internal fun kickCoordinator(taskQueue: TaskQueue) {\n assertLockHeld()\n\n if (taskQueue.activeTask == null) {\n if (taskQueue.futureTasks.isNotEmpty()) {\n readyQueues.addIfAbsent(taskQueue)\n } else {\n readyQueues.remove(taskQueue)\n }\n }\n\n if (coordinatorWaiting) {\n backend.coordinatorNotify(this@TaskRunner)\n } else {\n startAnotherThread()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":124,"symbol":"beforeRun","kind":"function","lang":"kotlin","code":"private fun beforeRun(task: Task) {\n assertLockHeld()\n\n task.nextExecuteNanoTime = -1L\n val queue = task.queue!!\n queue.futureTasks.remove(task)\n readyQueues.remove(queue)\n queue.activeTask = task\n busyQueues.add(queue)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":135,"symbol":"afterRun","kind":"function","lang":"kotlin","code":"private fun afterRun(\n task: Task,\n delayNanos: Long,\n completedNormally: Boolean,\n ) {\n assertLockHeld()\n\n val queue = task.queue!!\n check(queue.activeTask === task)\n\n val cancelActiveTask = queue.cancelActiveTask\n queue.cancelActiveTask = false\n queue.activeTask = null\n busyQueues.remove(queue)\n\n if (delayNanos != -1L && !cancelActiveTask && !queue.shutdown) {\n queue.scheduleAndDecide(task, delayNanos, recurrence = true)\n }\n\n if (queue.futureTasks.isNotEmpty()) {\n readyQueues.add(queue)\n\n // If the task crashed, start another thread to run the next task.\n if (!completedNormally) {\n startAnotherThread()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":170,"symbol":"awaitTaskToRun","kind":"function","lang":"kotlin","doc":"Returns an immediately-executable task for the calling thread to execute, sleeping as necessary until one is ready. If there are no ready queues, or if other threads have everything under control this will return null. If there is more than a single task ready to execute immediately this will start another thread to handle that work.","code":"fun awaitTaskToRun(): Task? {\n assertLockHeld()\n\n while (true) {\n if (readyQueues.isEmpty()) {\n return null // Nothing to do.\n }\n\n val now = backend.nanoTime()\n var minDelayNanos = Long.MAX_VALUE\n var readyTask: Task? = null\n var multipleReadyTasks = false\n\n // Decide what to run. This loop's goal wants to:\n // * Find out what this thread should do (either run a task or sleep)\n // * Find out if there's enough work to start another thread.\n eachQueue@ for (queue in readyQueues) {\n val candidate = queue.futureTasks[0]\n val candidateDelay = maxOf(0L, candidate.nextExecuteNanoTime - now)\n\n when {\n // Compute the delay of the soonest-executable task.\n candidateDelay > 0L -> {\n minDelayNanos = minOf(candidateDelay, minDelayNanos)\n continue@eachQueue\n }\n\n // If we already have more than one task, that's enough work for now. Stop searching.\n readyTask != null -> {\n multipleReadyTasks = true\n break@eachQueue\n }\n\n // We have a task to execute when we complete the loop.\n else -> {\n r"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":250,"symbol":"startAnotherThread","kind":"function","lang":"kotlin","doc":"Start another thread, unless a new thread is already scheduled to start.","code":"private fun startAnotherThread() {\n assertLockHeld()\n if (executeCallCount > runCallCount) return // A thread is still starting.\n\n executeCallCount++\n backend.execute(this@TaskRunner, runnable)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":258,"symbol":"newQueue","kind":"function","lang":"kotlin","code":"fun newQueue(): TaskQueue {\n val name = this.withLock { nextQueueName++ }\n return TaskQueue(this, \"Q$name\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":267,"symbol":"activeQueues","kind":"function","lang":"kotlin","doc":"Returns a snapshot of queues that currently have tasks scheduled. The task runner does not necessarily track queues that have no tasks scheduled.","code":"fun activeQueues(): List {\n this.withLock {\n return busyQueues + readyQueues\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":273,"symbol":"cancelAll","kind":"function","lang":"kotlin","code":"fun cancelAll() {\n assertLockHeld()\n for (i in busyQueues.size - 1 downTo 0) {\n busyQueues[i].cancelAllAndDecide()\n }\n for (i in readyQueues.size - 1 downTo 0) {\n val queue = readyQueues[i]\n queue.cancelAllAndDecide()\n if (queue.futureTasks.isEmpty()) {\n readyQueues.removeAt(i)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":287,"symbol":"Backend","kind":"interface","lang":"kotlin","code":"interface Backend {\n fun nanoTime(): Long\n\n fun coordinatorNotify(taskRunner: TaskRunner)\n\n fun coordinatorWait(\n taskRunner: TaskRunner,\n nanos: Long,\n )\n\n fun decorate(queue: BlockingQueue): BlockingQueue\n\n fun execute(\n taskRunner: TaskRunner,\n runnable: Runnable,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":288,"symbol":"nanoTime","kind":"function","lang":"kotlin","code":"fun nanoTime(): Long"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":290,"symbol":"coordinatorNotify","kind":"function","lang":"kotlin","code":"fun coordinatorNotify(taskRunner: TaskRunner)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":292,"symbol":"coordinatorWait","kind":"function","lang":"kotlin","code":"fun coordinatorWait(\n taskRunner: TaskRunner,\n nanos: Long,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":297,"symbol":"decorate","kind":"function","lang":"kotlin","code":"fun decorate(queue: BlockingQueue): BlockingQueue"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":299,"symbol":"execute","kind":"function","lang":"kotlin","code":"fun execute(\n taskRunner: TaskRunner,\n runnable: Runnable,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":305,"symbol":"RealBackend","kind":"class","lang":"kotlin","code":"class RealBackend(\n threadFactory: ThreadFactory,\n ) : Backend {\n val executor =\n ThreadPoolExecutor(\n // corePoolSize:\n 0,\n // maximumPoolSize:\n Int.MAX_VALUE,\n // keepAliveTime:\n 60L,\n TimeUnit.SECONDS,\n SynchronousQueue(),\n threadFactory,\n )\n\n override fun nanoTime() = System.nanoTime()\n\n override fun coordinatorNotify(taskRunner: TaskRunner) {\n taskRunner.notify()\n }\n\n /**\n * Wait a duration in nanoseconds. Unlike [java.lang.Object.wait] this interprets 0 as\n * \"don't wait\" instead of \"wait forever\".\n */\n @Throws(InterruptedException::class)\n @Suppress(\"PLATFORM_CLASS_MAPPED_TO_KOTLIN\")\n override fun coordinatorWait(\n taskRunner: TaskRunner,\n nanos: Long,\n ) {\n taskRunner.assertLockHeld()\n if (nanos > 0) {\n taskRunner.awaitNanos(nanos)\n }\n }\n\n override fun decorate(queue: BlockingQueue) = queue\n\n override fun execute(\n taskRunner: TaskRunner,\n runnable: Runnable,\n ) {\n executor.execute(runnable)\n }\n\n fun shutdown() {\n executor.shutdown()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":321,"symbol":"nanoTime","kind":"function","lang":"kotlin","code":"override fun nanoTime() = System.nanoTime()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":323,"symbol":"coordinatorNotify","kind":"function","lang":"kotlin","code":"override fun coordinatorNotify(taskRunner: TaskRunner) {\n taskRunner.notify()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":331,"symbol":"coordinatorWait","kind":"function","lang":"kotlin","doc":"Wait a duration in nanoseconds. Unlike [java.lang.Object.wait] this interprets 0 as \"don't wait\" instead of \"wait forever\".","code":"@Throws(InterruptedException::class)\n @Suppress(\"PLATFORM_CLASS_MAPPED_TO_KOTLIN\")\n override fun coordinatorWait(\n taskRunner: TaskRunner,\n nanos: Long,\n ) {\n taskRunner.assertLockHeld()\n if (nanos > 0) {\n taskRunner.awaitNanos(nanos)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":343,"symbol":"decorate","kind":"function","lang":"kotlin","code":"override fun decorate(queue: BlockingQueue) = queue"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":345,"symbol":"execute","kind":"function","lang":"kotlin","code":"override fun execute(\n taskRunner: TaskRunner,\n runnable: Runnable,\n ) {\n executor.execute(runnable)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/concurrent/TaskRunner.kt","line":352,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"fun shutdown() {\n executor.shutdown()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/BufferedSocket.kt","line":25,"symbol":"BufferedSocket","kind":"interface","lang":"kotlin","code":"interface BufferedSocket : OkioSocket {\n override val source: BufferedSource\n override val sink: BufferedSink\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/BufferedSocket.kt","line":30,"symbol":"asBufferedSocket","kind":"function","lang":"kotlin","code":"fun JavaNetSocket.asBufferedSocket(): BufferedSocket = asOkioSocket().asBufferedSocket()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/BufferedSocket.kt","line":32,"symbol":"asBufferedSocket","kind":"function","lang":"kotlin","code":"fun OkioSocket.asBufferedSocket(): BufferedSocket =\n object : BufferedSocket {\n private val delegate = this@asBufferedSocket\n override val source = delegate.source.buffer()\n override val sink = delegate.sink.buffer()\n\n override fun cancel() {\n delegate.cancel()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/BufferedSocket.kt","line":38,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n delegate.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectInterceptor.kt","line":28,"symbol":"ConnectInterceptor","kind":"object","lang":"kotlin","doc":"Opens a connection to the target server and proceeds to the next interceptor. The network might be used for the returned response, or to validate a cached response with a conditional GET.","code":"object ConnectInterceptor : Interceptor {\n @Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val realChain = chain as RealInterceptorChain\n val exchange = realChain.call.initExchange(realChain)\n val connectedChain = realChain.copy(exchange = exchange)\n return connectedChain.proceed(realChain.request)\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectInterceptor.kt","line":29,"symbol":"intercept","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val realChain = chain as RealInterceptorChain\n val exchange = realChain.call.initExchange(realChain)\n val connectedChain = realChain.copy(exchange = exchange)\n return connectedChain.proceed(realChain.request)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":61,"symbol":"ConnectPlan","kind":"class","lang":"kotlin","doc":"we must send a `CONNECT` request, and handle authorization challenges from the proxy. * Optional [TLS handshake][connectTls]. Each step may fail. If a retry is possible, a new instance is created with the next plan, which will be configured differently.","code":"@OkHttpInternalApi\nclass ConnectPlan internal constructor(\n private val taskRunner: TaskRunner,\n private val connectionPool: RealConnectionPool,\n private val readTimeoutMillis: Int,\n private val writeTimeoutMillis: Int,\n private val socketConnectTimeoutMillis: Int,\n private val socketReadTimeoutMillis: Int,\n private val pingIntervalMillis: Int,\n private val retryOnConnectionFailure: Boolean,\n private val call: RealCall,\n private val routePlanner: RealRoutePlanner,\n // Specifics to this plan.\n override val route: Route,\n internal val routes: List?,\n private val attempt: Int,\n private val tunnelRequest: Request?,\n internal val connectionSpecIndex: Int,\n internal val isTlsFallback: Boolean,\n private val echRetryPlan: EchRetryPlan? = null,\n) : RoutePlanner.Plan,\n ExchangeCodec.Carrier {\n /** True if this connect was canceled; typically because it lost a race. */\n @Volatile private var canceled = false\n\n // These properties are initialized by connect() and never reassigned.\n\n /** The low-level TCP socket. */\n private var rawSocket: JavaNetSocket? = null\n\n /**\n * The application layer socket. Either an [SSLSocket] layered over [rawSocket], or [rawSocket]"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":105,"symbol":"copy","kind":"function","lang":"kotlin","code":"private fun copy(\n route: Route = this.route,\n attempt: Int = this.attempt,\n tunnelRequest: Request? = this.tunnelRequest,\n connectionSpecIndex: Int = this.connectionSpecIndex,\n isTlsFallback: Boolean = this.isTlsFallback,\n echRetryPlan: EchRetryPlan? = this.echRetryPlan,\n ): ConnectPlan =\n ConnectPlan(\n taskRunner = taskRunner,\n connectionPool = connectionPool,\n readTimeoutMillis = readTimeoutMillis,\n writeTimeoutMillis = writeTimeoutMillis,\n socketConnectTimeoutMillis = socketConnectTimeoutMillis,\n socketReadTimeoutMillis = socketReadTimeoutMillis,\n pingIntervalMillis = pingIntervalMillis,\n retryOnConnectionFailure = retryOnConnectionFailure,\n call = call,\n routePlanner = routePlanner,\n route = route,\n routes = routes,\n attempt = attempt,\n tunnelRequest = tunnelRequest,\n connectionSpecIndex = connectionSpecIndex,\n isTlsFallback = isTlsFallback,\n echRetryPlan = echRetryPlan,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":133,"symbol":"connectTcp","kind":"function","lang":"kotlin","code":"override fun connectTcp(): ConnectResult {\n check(rawSocket == null) { \"TCP already connected\" }\n\n var success = false\n\n // Tell the call about the connecting call so async cancels work.\n call.plansToCancel += this\n try {\n call.eventListener.connectStart(call, route.socketAddress, route.proxy)\n connectionPool.connectionListener.connectStart(route, call)\n\n connectSocket()\n success = true\n return ConnectResult(plan = this)\n } catch (e: IOException) {\n // If we used the ProxySelector, and got a IOException during connect, report the failure.\n if (route.address.proxy == null && route.proxy.type() != Proxy.Type.DIRECT) {\n route.address.proxySelector.connectFailed(\n route.address.url.toUri(),\n route.proxy.address(),\n e,\n )\n }\n call.eventListener.connectFailed(call, route.socketAddress, route.proxy, null, e)\n connectionPool.connectionListener.connectFailed(route, call, e)\n return ConnectResult(plan = this, throwable = e)\n } finally {\n call.plansToCancel -= this\n if (!success) {\n rawSocket?.closeQuietly()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":167,"symbol":"connectTlsEtc","kind":"function","lang":"kotlin","code":"override fun connectTlsEtc(): ConnectResult {\n val rawSocket = requireNotNull(rawSocket) { \"TCP not connected\" }\n check(!isReady) { \"already connected\" }\n\n val connectionSpecs = route.address.connectionSpecs\n var retryTlsConnection: ConnectPlan? = null\n var success = false\n\n // Tell the call about the connecting call so async cancels work.\n call.plansToCancel += this\n try {\n if (tunnelRequest != null) {\n val tunnelResult = connectTunnel()\n\n // Tunnel didn't work. Start it all again.\n if (tunnelResult.nextPlan != null || tunnelResult.throwable != null) {\n return tunnelResult\n }\n }\n\n if (route.address.sslSocketFactory != null) {\n // Assume the server won't send a TLS ServerHello until we send a TLS ClientHello. If\n // that happens, then we will have buffered bytes that are needed by the SSLSocket!\n // This check is imperfect: it doesn't tell us whether a handshake will succeed, just\n // that it will almost certainly fail because the proxy has sent unexpected data.\n if (!socket.source.buffer.exhausted() || !socket.sink.buffer.exhausted()) {\n throw IOException(\"TLS tu"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":267,"symbol":"connectSocket","kind":"function","lang":"kotlin","doc":"Does all the work necessary to build a full HTTP or HTTPS connection on a raw socket.","code":"@Throws(IOException::class)\n private fun connectSocket() {\n val rawSocket =\n when (route.proxy.type()) {\n Proxy.Type.DIRECT, Proxy.Type.HTTP -> route.address.socketFactory.createSocket()!!\n else -> JavaNetSocket(route.proxy)\n }\n this.rawSocket = rawSocket\n\n // Handle the race where cancel() precedes connectSocket(). We don't want to miss a cancel.\n if (canceled) {\n throw IOException(\"canceled\")\n }\n\n rawSocket.soTimeout = socketReadTimeoutMillis\n try {\n Platform.get().connectSocket(rawSocket, route.socketAddress, socketConnectTimeoutMillis)\n } catch (e: ConnectException) {\n throw ConnectException(\"Failed to connect to ${route.socketAddress}\").apply {\n initCause(e)\n }\n }\n\n // The following try/catch block is a pseudo hacky way to get around a crash on Android 7.0\n // More details:\n // https://github.com/lysine-dev/okhttp/issues/3245\n // https://android-review.googlesource.com/#/c/271775/\n try {\n this.socket = rawSocket.asBufferedSocket()\n } catch (npe: NullPointerException) {\n if (npe.message == NPE_THROW_WITH_NULL) {\n throw IOException(npe)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":310,"symbol":"connectTunnel","kind":"function","lang":"kotlin","doc":"Does all the work to build an HTTPS connection over a proxy tunnel. The catch here is that a proxy server can issue an auth challenge and then close the connection. @return the next plan to attempt, or null if no further attempt should be made either because we've successfully connected or because no further attempts should be made.","code":"@Throws(IOException::class)\n internal fun connectTunnel(): ConnectResult {\n val nextTunnelRequest =\n createTunnel()\n ?: return ConnectResult(plan = this) // Success.\n\n // The proxy decided to close the connection after an auth challenge. Retry with different\n // auth credentials.\n rawSocket?.closeQuietly()\n\n val nextAttempt = attempt + 1\n return when {\n nextAttempt < MAX_TUNNEL_ATTEMPTS -> {\n call.eventListener.connectEnd(call, route.socketAddress, route.proxy, null)\n ConnectResult(\n plan = this,\n nextPlan =\n copy(\n attempt = nextAttempt,\n tunnelRequest = nextTunnelRequest,\n ),\n )\n }\n\n else -> {\n val failure =\n ProtocolException(\n \"Too many tunnel connections attempted: $MAX_TUNNEL_ATTEMPTS\",\n )\n call.eventListener.connectFailed(call, route.socketAddress, route.proxy, null, failure)\n connectionPool.connectionListener.connectFailed(route, call, failure)\n return ConnectResult(plan = this, throwable = failure)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":346,"symbol":"connectTls","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun connectTls(\n sslSocket: SSLSocket,\n connectionSpec: ConnectionSpec,\n ) {\n val address = route.address\n var success = false\n try {\n if (connectionSpec.supportsTlsExtensions) {\n Platform.get().configureTlsExtensions(\n sslSocket = sslSocket,\n hostname = address.url.host,\n protocols = address.protocols,\n echConfigList = route.echConfigList,\n )\n }\n\n // Force handshake. This can throw!\n sslSocket.startHandshake()\n // block for session establishment\n val sslSocketSession = sslSocket.session\n val unverifiedHandshake = sslSocketSession.handshake()\n\n // Verify that the socket's certificates are acceptable for the target host.\n if (!address.hostnameVerifier!!.verify(address.url.host, sslSocketSession)) {\n val peerCertificates = unverifiedHandshake.peerCertificates\n if (peerCertificates.isNotEmpty()) {\n val cert = peerCertificates[0] as X509Certificate\n throw SSLPeerUnverifiedException(\n \"\"\"\n |Hostname ${address.url.host} not verified:\n | certificate: ${CertificatePinner.pin(c"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":432,"symbol":"createTunnel","kind":"function","lang":"kotlin","doc":"To make an HTTPS connection over an HTTP proxy, send an unencrypted CONNECT request to create the proxy connection. This may need to be retried if the proxy requires authorization.","code":"@Throws(IOException::class)\n private fun createTunnel(): Request? {\n var nextRequest = tunnelRequest!!\n // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.\n val url = route.address.url\n val requestLine = \"CONNECT ${url.toHostHeader(includeDefaultPort = true)} HTTP/1.1\"\n while (true) {\n val tunnelCodec =\n Http1ExchangeCodec(\n // No client for CONNECT tunnels:\n client = null,\n carrier = this,\n socket = socket,\n )\n socket.source.timeout().timeout(readTimeoutMillis.toLong(), TimeUnit.MILLISECONDS)\n socket.sink.timeout().timeout(writeTimeoutMillis.toLong(), TimeUnit.MILLISECONDS)\n tunnelCodec.writeRequest(nextRequest.headers, requestLine)\n tunnelCodec.finishRequest()\n val response =\n tunnelCodec\n .readResponseHeaders(false)!!\n .request(nextRequest)\n .build()\n tunnelCodec.skipConnectBody(response)\n\n when (response.code) {\n HttpURLConnection.HTTP_OK -> {\n return null\n }\n\n HttpURLConnection.HTTP_PROXY_AUTH -> {\n nextRequest = route.address.proxyAuthenticator.authenticate(route, response"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":482,"symbol":"planWithCurrentOrInitialConnectionSpec","kind":"function","lang":"kotlin","doc":"Returns this if its [connectionSpecIndex] is defined, or a new connection with it defined otherwise.","code":"@Throws(IOException::class)\n internal fun planWithCurrentOrInitialConnectionSpec(\n connectionSpecs: List,\n sslSocket: SSLSocket,\n ): ConnectPlan {\n if (connectionSpecIndex != -1) return this\n return nextCompatibleConnectionSpec(connectionSpecs, sslSocket)\n ?: throw UnknownServiceException(\n \"Unable to find acceptable protocols.\" +\n \" isFallback=$isTlsFallback,\" +\n \" modes=$connectionSpecs,\" +\n \" supported protocols=${sslSocket.enabledProtocols!!.contentToString()}\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":501,"symbol":"nextConnectionSpec","kind":"function","lang":"kotlin","doc":"Returns a copy of this connection that recovers from [sslException], or null if the failure should not be retried.","code":"internal fun nextConnectionSpec(\n connectionSpecs: List,\n sslSocket: SSLSocket,\n sslException: SSLException,\n ): ConnectPlan? {\n // If this was an ECH retry, don't retry again.\n if (echRetryPlan != null) return null\n\n val nextEchRetryPlan = Platform.get().echRetryPlan(sslException)\n if (nextEchRetryPlan != null) {\n // Validate the publicHostname against the session certificate. The session is protected by\n // the outer client hello (e.g. cloudflare-ech.com), not the origin server. If this fails,\n // we must not retry further.\n val hostnameVerifier = route.address.hostnameVerifier!!\n if (!hostnameVerifier.verify(nextEchRetryPlan.publicName, sslSocket.session)) {\n throw EchUntrustedException(\n \"public_name '${nextEchRetryPlan.publicName}' not verified\",\n sslException,\n )\n }\n\n return copy(\n route =\n Route(\n address = route.address,\n proxy = route.proxy,\n socketAddress = route.socketAddress,\n echConfigList = nextEchRetryPlan.configList,\n ),\n echRetryPlan = nextEchRetryPlan,\n )\n }\n\n // If recovery "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":547,"symbol":"nextCompatibleConnectionSpec","kind":"function","lang":"kotlin","doc":"Returns a copy of this connection with the next compatible connection spec, or null if none are available.","code":"private fun nextCompatibleConnectionSpec(\n connectionSpecs: List,\n sslSocket: SSLSocket,\n ): ConnectPlan? {\n for (i in connectionSpecIndex + 1 until connectionSpecs.size) {\n if (connectionSpecs[i].isCompatible(sslSocket)) {\n return copy(connectionSpecIndex = i, isTlsFallback = (connectionSpecIndex != -1))\n }\n }\n return null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":560,"symbol":"handleSuccess","kind":"function","lang":"kotlin","doc":"Returns the connection to use, which might be different from [connection].","code":"override fun handleSuccess(): RealConnection {\n call.client.routeDatabase.connected(route)\n\n val connection = this.connection!!\n connection.connectionListener.connectEnd(connection, route, call)\n\n // If we raced another call connecting to this host, coalesce the connections. This makes for\n // 3 different lookups in the connection pool!\n val pooled3 = routePlanner.planReusePooledConnection(this, routes)\n if (pooled3 != null) return pooled3.connection\n\n connection.withLock {\n connectionPool.put(connection)\n call.acquireConnectionNoEvents(connection)\n }\n\n call.eventListener.connectionAcquired(call, connection)\n connection.connectionListener.connectionAcquired(connection, call)\n return connection\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":581,"symbol":"trackFailure","kind":"function","lang":"kotlin","code":"override fun trackFailure(\n call: RealCall,\n e: IOException?,\n ) {\n // Do nothing.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":588,"symbol":"noNewExchanges","kind":"function","lang":"kotlin","code":"override fun noNewExchanges() {\n // Do nothing.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":592,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n canceled = true\n // Close the raw socket so we don't end up doing synchronous I/O.\n rawSocket?.closeQuietly()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":598,"symbol":"retry","kind":"function","lang":"kotlin","code":"override fun retry(): RoutePlanner.Plan =\n ConnectPlan(\n taskRunner = taskRunner,\n connectionPool = connectionPool,\n readTimeoutMillis = readTimeoutMillis,\n writeTimeoutMillis = writeTimeoutMillis,\n socketConnectTimeoutMillis = socketConnectTimeoutMillis,\n socketReadTimeoutMillis = socketReadTimeoutMillis,\n pingIntervalMillis = pingIntervalMillis,\n retryOnConnectionFailure = retryOnConnectionFailure,\n call = call,\n routePlanner = routePlanner,\n route = route,\n routes = routes,\n attempt = attempt,\n tunnelRequest = tunnelRequest,\n connectionSpecIndex = connectionSpecIndex,\n isTlsFallback = isTlsFallback,\n echRetryPlan = echRetryPlan,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt","line":619,"symbol":"closeQuietly","kind":"function","lang":"kotlin","code":"fun closeQuietly() {\n javaNetSocket?.closeQuietly()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectionListener.kt","line":30,"symbol":"ConnectionListener","kind":"class","lang":"kotlin","doc":"Listener for connection events. Extend this class to monitor the new connections and closes. All event methods must execute fast, without external locking, cannot throw exceptions, attempt to mutate the event parameters, or be reentrant back into the client. Any IO - writing to files or network should be done asynchronously.","code":"internal abstract class ConnectionListener {\n /**\n * Invoked as soon as a call causes a connection to be started.\n */\n open fun connectStart(\n route: Route,\n call: Call,\n ) {}\n\n /**\n * Invoked when a connection fails to be established.\n */\n open fun connectFailed(\n route: Route,\n call: Call,\n failure: IOException,\n ) {}\n\n /**\n * Invoked as soon as a connection is successfully established.\n */\n open fun connectEnd(\n connection: Connection,\n route: Route,\n call: Call,\n ) {}\n\n /**\n * Invoked when a connection is released as no longer required.\n */\n open fun connectionClosed(connection: Connection) {}\n\n /**\n * Invoked when a call is assigned a particular connection.\n */\n open fun connectionAcquired(\n connection: Connection,\n call: Call,\n ) {}\n\n /**\n * Invoked when a call no longer uses a connection.\n */\n open fun connectionReleased(\n connection: Connection,\n call: Call,\n ) {}\n\n /**\n * Invoked when a connection is marked for no new exchanges.\n */\n open fun noNewExchanges(connection: Connection) {}\n\n companion object {\n val NONE: ConnectionListener = object : ConnectionListener() {}\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectionListener.kt","line":34,"symbol":"connectStart","kind":"function","lang":"kotlin","doc":"Invoked as soon as a call causes a connection to be started.","code":"open fun connectStart(\n route: Route,\n call: Call,\n ) {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectionListener.kt","line":42,"symbol":"connectFailed","kind":"function","lang":"kotlin","doc":"Invoked when a connection fails to be established.","code":"open fun connectFailed(\n route: Route,\n call: Call,\n failure: IOException,\n ) {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectionListener.kt","line":51,"symbol":"connectEnd","kind":"function","lang":"kotlin","doc":"Invoked as soon as a connection is successfully established.","code":"open fun connectEnd(\n connection: Connection,\n route: Route,\n call: Call,\n ) {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectionListener.kt","line":60,"symbol":"connectionClosed","kind":"function","lang":"kotlin","doc":"Invoked when a connection is released as no longer required.","code":"open fun connectionClosed(connection: Connection) {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectionListener.kt","line":65,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","doc":"Invoked when a call is assigned a particular connection.","code":"open fun connectionAcquired(\n connection: Connection,\n call: Call,\n ) {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectionListener.kt","line":73,"symbol":"connectionReleased","kind":"function","lang":"kotlin","doc":"Invoked when a call no longer uses a connection.","code":"open fun connectionReleased(\n connection: Connection,\n call: Call,\n ) {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectionListener.kt","line":81,"symbol":"noNewExchanges","kind":"function","lang":"kotlin","doc":"Invoked when a connection is marked for no new exchanges.","code":"open fun noNewExchanges(connection: Connection) {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":39,"symbol":"Exchange","kind":"class","lang":"kotlin","doc":"Transmits a single HTTP request and a response pair. This layers connection management and events on [ExchangeCodec], which handles the actual I/O.","code":"@OkHttpInternalApi\nclass Exchange(\n internal val call: RealCall,\n internal val finder: ExchangeFinder,\n private val codec: ExchangeCodec,\n) {\n /** True if the request body need not complete before the response body starts. */\n internal var isDuplex: Boolean = false\n private set\n\n /** True if there was an exception on the connection to the peer. */\n internal var hasFailure: Boolean = false\n private set\n\n internal val connection: RealConnection\n get() = codec.carrier as? RealConnection ?: error(\"no connection for CONNECT tunnels\")\n\n internal val isCoalescedConnection: Boolean\n get() = finder.routePlanner.address.url.host != codec.carrier.route.address.url.host\n\n @Throws(IOException::class)\n fun writeRequestHeaders(request: Request) {\n try {\n call.eventListener.requestHeadersStart(call)\n codec.writeRequestHeaders(request)\n call.eventListener.requestHeadersEnd(call, request)\n } catch (e: IOException) {\n call.eventListener.requestFailed(call, e)\n trackFailure(e)\n throw e\n }\n }\n\n @Throws(IOException::class)\n fun createRequestBody(\n request: Request,\n duplex: Boolean,\n ): Sink {\n this.isDuplex = duplex\n val cont"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":59,"symbol":"writeRequestHeaders","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun writeRequestHeaders(request: Request) {\n try {\n call.eventListener.requestHeadersStart(call)\n codec.writeRequestHeaders(request)\n call.eventListener.requestHeadersEnd(call, request)\n } catch (e: IOException) {\n call.eventListener.requestFailed(call, e)\n trackFailure(e)\n throw e\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":72,"symbol":"createRequestBody","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun createRequestBody(\n request: Request,\n duplex: Boolean,\n ): Sink {\n this.isDuplex = duplex\n val contentLength = request.body!!.contentLength()\n call.eventListener.requestBodyStart(call)\n val rawRequestBody = codec.createRequestBody(request, contentLength)\n return RequestBodySink(\n delegate = rawRequestBody,\n contentLength = contentLength,\n isSocket = false,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":88,"symbol":"flushRequest","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun flushRequest() {\n try {\n codec.flushRequest()\n } catch (e: IOException) {\n call.eventListener.requestFailed(call, e)\n trackFailure(e)\n throw e\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":99,"symbol":"finishRequest","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun finishRequest() {\n try {\n codec.finishRequest()\n } catch (e: IOException) {\n call.eventListener.requestFailed(call, e)\n trackFailure(e)\n throw e\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":110,"symbol":"responseHeadersStart","kind":"function","lang":"kotlin","code":"fun responseHeadersStart() {\n call.eventListener.responseHeadersStart(call)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":114,"symbol":"readResponseHeaders","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun readResponseHeaders(expectContinue: Boolean): Response.Builder? {\n try {\n val result = codec.readResponseHeaders(expectContinue)\n result?.initExchange(this)\n return result\n } catch (e: IOException) {\n call.eventListener.responseFailed(call, e)\n trackFailure(e)\n throw e\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":127,"symbol":"responseHeadersEnd","kind":"function","lang":"kotlin","code":"fun responseHeadersEnd(response: Response) {\n call.eventListener.responseHeadersEnd(call, response)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":131,"symbol":"openResponseBody","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun openResponseBody(response: Response): ResponseBody {\n try {\n val contentType = response.header(\"Content-Type\")\n val contentLength = codec.reportedContentLength(response)\n val rawSource = codec.openResponseBodySource(response)\n val source =\n ResponseBodySource(\n delegate = rawSource,\n contentLength = contentLength,\n isSocket = false,\n )\n return RealResponseBody(contentType, contentLength, source.buffer())\n } catch (e: IOException) {\n call.eventListener.responseFailed(call, e)\n trackFailure(e)\n throw e\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":151,"symbol":"peekTrailers","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun peekTrailers(): Headers? = codec.peekTrailers()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":154,"symbol":"upgradeToSocket","kind":"function","lang":"kotlin","code":"fun upgradeToSocket(): Socket {\n call.upgradeToSocket()\n (codec.carrier as RealConnection).useAsSocket()\n\n return object : Socket {\n override fun cancel() {\n this@Exchange.cancel()\n }\n\n override val sink =\n RequestBodySink(\n delegate = codec.socket.sink,\n contentLength = -1L,\n isSocket = true,\n )\n override val source =\n ResponseBodySource(\n delegate = codec.socket.source,\n contentLength = -1L,\n isSocket = true,\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":159,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n this@Exchange.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":178,"symbol":"noNewExchangesOnConnection","kind":"function","lang":"kotlin","code":"fun noNewExchangesOnConnection() {\n codec.carrier.noNewExchanges()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":182,"symbol":"cancel","kind":"function","lang":"kotlin","code":"fun cancel() {\n codec.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":190,"symbol":"detachWithViolence","kind":"function","lang":"kotlin","doc":"Revoke this exchange's access to streams. This is necessary when a follow-up request is required but the preceding exchange hasn't completed yet.","code":"fun detachWithViolence() {\n codec.cancel()\n call.messageDone(\n exchange = this,\n requestDone = true,\n responseDone = true,\n socketSinkDone = true,\n socketSourceDone = true,\n e = null,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":202,"symbol":"trackFailure","kind":"function","lang":"kotlin","code":"private fun trackFailure(e: IOException) {\n hasFailure = true\n codec.carrier.trackFailure(call, e)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":208,"symbol":"bodyComplete","kind":"function","lang":"kotlin","doc":"If [e] is non-null, this will return a non-null value.","code":"fun bodyComplete(\n bytesRead: Long = -1L,\n isSocket: Boolean,\n responseDone: Boolean = false,\n requestDone: Boolean = false,\n e: IOException?,\n ): IOException? {\n if (e != null) {\n trackFailure(e)\n }\n if (requestDone) {\n if (e != null) {\n call.eventListener.requestFailed(call, e)\n } else {\n call.eventListener.requestBodyEnd(call, bytesRead)\n }\n }\n if (responseDone) {\n if (e != null) {\n call.eventListener.responseFailed(call, e)\n } else {\n call.eventListener.responseBodyEnd(call, bytesRead)\n }\n }\n return call.messageDone(\n exchange = this,\n requestDone = requestDone && !isSocket,\n responseDone = responseDone && !isSocket,\n socketSinkDone = requestDone && isSocket,\n socketSourceDone = responseDone && isSocket,\n e = e,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":242,"symbol":"noRequestBody","kind":"function","lang":"kotlin","code":"fun noRequestBody() {\n call.messageDone(\n exchange = this,\n requestDone = true,\n e = null,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":251,"symbol":"RequestBodySink","kind":"class","lang":"kotlin","doc":"A request body that fires events when it completes.","code":"private inner class RequestBodySink(\n delegate: Sink,\n /** The exact number of bytes to be written, or -1L if that is unknown. */\n private val contentLength: Long,\n private val isSocket: Boolean,\n ) : ForwardingSink(delegate) {\n private var completed = false\n private var bytesReceived = 0L\n private var invokeStartEvent = isSocket\n private var closed = false\n\n @Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n check(!closed) { \"closed\" }\n if (contentLength != -1L && bytesReceived + byteCount > contentLength) {\n throw ProtocolException(\n \"expected $contentLength bytes but received ${bytesReceived + byteCount}\",\n )\n }\n try {\n if (invokeStartEvent) {\n invokeStartEvent = false\n call.eventListener.requestBodyStart(call)\n }\n super.write(source, byteCount)\n this.bytesReceived += byteCount\n } catch (e: IOException) {\n throw complete(e)!!\n }\n }\n\n @Throws(IOException::class)\n override fun flush() {\n try {\n super.flush()\n } catch (e: IOException) {\n throw complete(e)!!\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":262,"symbol":"write","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n check(!closed) { \"closed\" }\n if (contentLength != -1L && bytesReceived + byteCount > contentLength) {\n throw ProtocolException(\n \"expected $contentLength bytes but received ${bytesReceived + byteCount}\",\n )\n }\n try {\n if (invokeStartEvent) {\n invokeStartEvent = false\n call.eventListener.requestBodyStart(call)\n }\n super.write(source, byteCount)\n this.bytesReceived += byteCount\n } catch (e: IOException) {\n throw complete(e)!!\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":285,"symbol":"flush","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun flush() {\n try {\n super.flush()\n } catch (e: IOException) {\n throw complete(e)!!\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":294,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n if (closed) return\n closed = true\n if (contentLength != -1L && bytesReceived != contentLength) {\n throw ProtocolException(\"unexpected end of stream\")\n }\n try {\n super.close()\n complete(null)\n } catch (e: IOException) {\n throw complete(e)!!\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":310,"symbol":"complete","kind":"function","lang":"kotlin","doc":"If [e] is non-null, this will return a non-null value.","code":"private fun complete(e: IOException?): IOException? {\n if (completed) return e\n completed = true\n return bodyComplete(\n bytesRead = bytesReceived,\n isSocket = isSocket,\n requestDone = true,\n e = e,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":323,"symbol":"ResponseBodySource","kind":"class","lang":"kotlin","doc":"A response body that fires events when it completes.","code":"internal inner class ResponseBodySource(\n delegate: Source,\n private val contentLength: Long,\n private val isSocket: Boolean,\n ) : ForwardingSource(delegate) {\n private var bytesReceived = 0L\n private var invokeStartEvent = true\n private var completed = false\n private var closed = false\n\n init {\n if (contentLength == 0L) {\n complete(null)\n }\n }\n\n @Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n check(!closed) { \"closed\" }\n try {\n val read = delegate.read(sink, byteCount)\n\n if (invokeStartEvent) {\n invokeStartEvent = false\n call.eventListener.responseBodyStart(call)\n }\n\n if (read == -1L) {\n complete(null)\n return -1L\n }\n\n val newBytesReceived = bytesReceived + read\n if (contentLength != -1L && newBytesReceived > contentLength) {\n throw ProtocolException(\"expected $contentLength bytes but received $newBytesReceived\")\n }\n\n bytesReceived = newBytesReceived\n if (codec.isResponseComplete) {\n complete(null)\n }\n\n return read\n } catch"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":339,"symbol":"read","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n check(!closed) { \"closed\" }\n try {\n val read = delegate.read(sink, byteCount)\n\n if (invokeStartEvent) {\n invokeStartEvent = false\n call.eventListener.responseBodyStart(call)\n }\n\n if (read == -1L) {\n complete(null)\n return -1L\n }\n\n val newBytesReceived = bytesReceived + read\n if (contentLength != -1L && newBytesReceived > contentLength) {\n throw ProtocolException(\"expected $contentLength bytes but received $newBytesReceived\")\n }\n\n bytesReceived = newBytesReceived\n if (codec.isResponseComplete) {\n complete(null)\n }\n\n return read\n } catch (e: IOException) {\n throw complete(e)!!\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":374,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n if (closed) return\n closed = true\n try {\n super.close()\n complete(null)\n } catch (e: IOException) {\n throw complete(e)!!\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/Exchange.kt","line":387,"symbol":"complete","kind":"function","lang":"kotlin","doc":"If [e] is non-null, this will return a non-null value.","code":"fun complete(e: IOException?): IOException? {\n if (completed) return e\n completed = true\n // If the body is closed without reading any bytes send a responseBodyStart() now.\n if (e == null && invokeStartEvent) {\n invokeStartEvent = false\n call.eventListener.responseBodyStart(call)\n }\n return bodyComplete(\n bytesRead = bytesReceived,\n isSocket = isSocket,\n responseDone = true,\n e = e,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ExchangeFinder.kt","line":20,"symbol":"ExchangeFinder","kind":"interface","lang":"kotlin","code":"@OkHttpInternalApi\ninterface ExchangeFinder {\n val routePlanner: RoutePlanner\n\n fun find(): RealConnection\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ExchangeFinder.kt","line":24,"symbol":"find","kind":"function","lang":"kotlin","code":"fun find(): RealConnection"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FailedPlan.kt","line":29,"symbol":"FailedPlan","kind":"class","lang":"kotlin","doc":"to use `H2_PRIOR_KNOWLEDGE` but the URL's scheme is `https:`. * Preemptive proxy authentication failed. Planning failures are not necessarily fatal. For example, even if we can't DNS lookup the first proxy in a list, looking up a subsequent one may succeed.","code":"internal class FailedPlan(\n e: Throwable,\n) : RoutePlanner.Plan {\n val result = RoutePlanner.ConnectResult(plan = this, throwable = e)\n\n override val isReady = false\n\n override fun connectTcp() = result\n\n override fun connectTlsEtc() = result\n\n override fun handleSuccess() = error(\"unexpected call\")\n\n override fun cancel() = error(\"unexpected cancel\")\n\n override fun retry() = error(\"unexpected retry\")\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FailedPlan.kt","line":36,"symbol":"connectTcp","kind":"function","lang":"kotlin","code":"override fun connectTcp() = result"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FailedPlan.kt","line":38,"symbol":"connectTlsEtc","kind":"function","lang":"kotlin","code":"override fun connectTlsEtc() = result"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FailedPlan.kt","line":40,"symbol":"handleSuccess","kind":"function","lang":"kotlin","code":"override fun handleSuccess() = error(\"unexpected call\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FailedPlan.kt","line":42,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() = error(\"unexpected cancel\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FailedPlan.kt","line":44,"symbol":"retry","kind":"function","lang":"kotlin","code":"override fun retry() = error(\"unexpected retry\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinder.kt","line":33,"symbol":"FastFallbackExchangeFinder","kind":"class","lang":"kotlin","doc":"Speculatively connects to each IP address of a target address, returning as soon as one of them connects successfully. This kicks off new attempts every 250 ms until a connect succeeds.","code":"@OkHttpInternalApi\ninternal class FastFallbackExchangeFinder(\n override val routePlanner: RoutePlanner,\n private val taskRunner: TaskRunner,\n) : ExchangeFinder {\n private val connectDelayNanos = TimeUnit.MILLISECONDS.toNanos(250L)\n private var nextTcpConnectAtNanos = Long.MIN_VALUE\n\n /**\n * Plans currently being connected, and that will later be added to [connectResults]. This is\n * mutated by the call thread only. If is accessed by background connect threads.\n */\n private val tcpConnectsInFlight = CopyOnWriteArrayList()\n\n /**\n * Results are posted here as they occur. The find job is done when either one plan completes\n * successfully or all plans fail.\n */\n private val connectResults = taskRunner.backend.decorate(LinkedBlockingDeque())\n\n override fun find(): RealConnection {\n var firstException: IOException? = null\n try {\n while (tcpConnectsInFlight.isNotEmpty() || routePlanner.hasNext()) {\n if (routePlanner.isCanceled()) throw IOException(\"Canceled\")\n\n // Launch a new connection if we're ready to.\n val now = taskRunner.backend.nanoTime()\n var awaitTimeoutNanos = nextTcpConnectAtNanos - now\n va"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinder.kt","line":53,"symbol":"find","kind":"function","lang":"kotlin","code":"override fun find(): RealConnection {\n var firstException: IOException? = null\n try {\n while (tcpConnectsInFlight.isNotEmpty() || routePlanner.hasNext()) {\n if (routePlanner.isCanceled()) throw IOException(\"Canceled\")\n\n // Launch a new connection if we're ready to.\n val now = taskRunner.backend.nanoTime()\n var awaitTimeoutNanos = nextTcpConnectAtNanos - now\n var connectResult: ConnectResult? = null\n if (tcpConnectsInFlight.isEmpty() || awaitTimeoutNanos <= 0) {\n connectResult = launchTcpConnect()\n nextTcpConnectAtNanos = now + connectDelayNanos\n awaitTimeoutNanos = connectDelayNanos\n }\n\n // Wait for an in-flight connect to complete or fail.\n if (connectResult == null) {\n connectResult = awaitTcpConnect(awaitTimeoutNanos, TimeUnit.NANOSECONDS) ?: continue\n }\n\n if (connectResult.isSuccess) {\n // We have a connected TCP connection. Cancel and defer the racing connects that all lost.\n cancelInFlightConnects()\n\n // Finish connecting. We won't have to if the winner is from the connection pool.\n if (!connectResult.plan.isReady) {\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinder.kt","line":117,"symbol":"launchTcpConnect","kind":"function","lang":"kotlin","doc":"Returns non-null if we don't need to wait for the launched result. In such cases, this result must be processed before whatever is waiting in the queue because we may have already acquired its connection.","code":"private fun launchTcpConnect(): ConnectResult? {\n val plan =\n when {\n routePlanner.hasNext() -> {\n try {\n routePlanner.plan()\n } catch (e: Throwable) {\n FailedPlan(e)\n }\n }\n\n else -> {\n return null\n } // Nothing further to try.\n }\n\n // Already connected. Return it immediately.\n if (plan.isReady) return ConnectResult(plan)\n\n // Already failed? Return it immediately.\n if (plan is FailedPlan) return plan.result\n\n // Connect TCP asynchronously.\n tcpConnectsInFlight += plan\n val taskName = \"$okHttpName connect ${routePlanner.address.url.redact()}\"\n taskRunner.newQueue().schedule(\n object : Task(taskName) {\n override fun runOnce(): Long {\n val connectResult =\n try {\n plan.connectTcp()\n } catch (e: Throwable) {\n ConnectResult(plan, throwable = e)\n }\n // Only post a result if this hasn't since been canceled.\n if (plan in tcpConnectsInFlight) {\n connectResults.put(connectResult)\n }\n return -1L\n }\n },\n )\n return null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinder.kt","line":144,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n val connectResult =\n try {\n plan.connectTcp()\n } catch (e: Throwable) {\n ConnectResult(plan, throwable = e)\n }\n // Only post a result if this hasn't since been canceled.\n if (plan in tcpConnectsInFlight) {\n connectResults.put(connectResult)\n }\n return -1L\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinder.kt","line":162,"symbol":"awaitTcpConnect","kind":"function","lang":"kotlin","code":"private fun awaitTcpConnect(\n timeout: Long,\n unit: TimeUnit,\n ): ConnectResult? {\n if (tcpConnectsInFlight.isEmpty()) return null\n\n val result = connectResults.poll(timeout, unit) ?: return null\n\n tcpConnectsInFlight.remove(result.plan)\n\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinder.kt","line":175,"symbol":"cancelInFlightConnects","kind":"function","lang":"kotlin","code":"private fun cancelInFlightConnects() {\n for (plan in tcpConnectsInFlight) {\n plan.cancel()\n val retry = plan.retry() ?: continue\n routePlanner.deferredPlans.addLast(retry)\n }\n tcpConnectsInFlight.clear()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/InetAddressOrder.kt","line":33,"symbol":"reorderForHappyEyeballs","kind":"function","lang":"kotlin","doc":"- Async DNS split by IP class - Stateful handling of connectivity results - The prioritisation of addresses https://datatracker.ietf.org/doc/html/rfc8305#section-4","code":"internal fun reorderForHappyEyeballs(addresses: List): List {\n if (addresses.size < 2) {\n return addresses\n }\n\n val (ipv6, ipv4) = addresses.partition { it.socketAddress.address is Inet6Address }\n\n return if (ipv6.isEmpty() || ipv4.isEmpty()) {\n addresses\n } else {\n interleave(ipv6, ipv4)\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":65,"symbol":"RealCall","kind":"class","lang":"kotlin","doc":"This class supports [asynchronous canceling][cancel]. This is intended to have the smallest blast radius possible. If an HTTP/2 stream is active, canceling will cancel that stream but not the other streams sharing its connection. But if the TLS handshake is still in progress then canceling may break the entire connection.","code":"@OkHttpInternalApi\nclass RealCall(\n val client: OkHttpClient,\n /** The application's original request unadulterated by redirects or auth headers. */\n val originalRequest: Request,\n val forWebSocket: Boolean,\n) : Call,\n Cloneable,\n Lockable {\n private val connectionPool: RealConnectionPool = client.connectionPool.delegate\n\n @Volatile\n internal var eventListener: EventListener = client.eventListenerFactory.create(this)\n\n private val timeout =\n object : AsyncTimeout() {\n override fun timedOut() {\n this@RealCall.cancel()\n }\n }.apply {\n timeout(client.callTimeoutMillis.toLong(), MILLISECONDS)\n }\n\n private val executed = AtomicBoolean()\n\n // These properties are only accessed by the thread executing the call.\n\n /** Initialized in [callStart]. */\n private var callStackTrace: Any? = null\n\n /** Finds an exchange to send the next request and receive the next response. */\n private var exchangeFinder: ExchangeFinder? = null\n\n var connection: RealConnection? = null\n private set\n private var timeoutEarlyExit = false\n\n /**\n * This is the same value as [exchange], but scoped to the execution of the network interceptors.\n * The [exchange] fie"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":81,"symbol":"timedOut","kind":"function","lang":"kotlin","code":"override fun timedOut() {\n this@RealCall.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":131,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = timeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":133,"symbol":"addEventListener","kind":"function","lang":"kotlin","code":"override fun addEventListener(eventListener: EventListener) {\n // Atomically replace the current eventListener with a composite one.\n do {\n val previous = this.eventListener\n } while (!eventListenerUpdater.compareAndSet(this, previous, previous + eventListener))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":140,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(type: KClass): T? = type.java.cast(tags.get()[type])"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":142,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(type: Class): T? = tag(type.kotlin)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":144,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(\n type: KClass,\n computeIfAbsent: () -> T,\n ): T = tags.computeIfAbsent(type, computeIfAbsent)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":149,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(\n type: Class,\n computeIfAbsent: () -> T,\n ): T = tags.computeIfAbsent(type.kotlin, computeIfAbsent)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":154,"symbol":"clone","kind":"function","lang":"kotlin","code":"@SuppressWarnings(\"CloneDoesntCallSuperClone\") // We are a final type & this saves clearing state.\n override fun clone(): Call = RealCall(client, originalRequest, forWebSocket)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":157,"symbol":"request","kind":"function","lang":"kotlin","code":"override fun request(): Request = originalRequest"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":168,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"and response body streams; otherwise resources may be leaked. This method is safe to be called concurrently, but provides limited guarantees. If a transport layer connection has been established (such as a HTTP/2 stream) that is terminated. Otherwise, if a socket connection is being established, that is terminated.","code":"override fun cancel() {\n if (canceled) return // Already canceled.\n\n canceled = true\n exchange?.cancel()\n for (plan in plansToCancel) {\n plan.cancel()\n }\n\n eventListener.canceled(this)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":180,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"override fun isCanceled(): Boolean = canceled"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":182,"symbol":"execute","kind":"function","lang":"kotlin","code":"override fun execute(): Response {\n check(executed.compareAndSet(false, true)) { \"Already Executed\" }\n\n timeout.enter()\n callStart()\n try {\n client.dispatcher.executed(this)\n return getResponseWithInterceptorChain()\n } finally {\n client.dispatcher.finished(this)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":195,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(responseCallback: Callback) {\n check(executed.compareAndSet(false, true)) { \"Already Executed\" }\n\n callStart()\n client.dispatcher.enqueue(AsyncCall(responseCallback))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":202,"symbol":"isExecuted","kind":"function","lang":"kotlin","code":"override fun isExecuted(): Boolean = executed.get()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":204,"symbol":"callStart","kind":"function","lang":"kotlin","code":"private fun callStart() {\n this.callStackTrace = Platform.get().getStackTraceForCloseable(\"response.body().close()\")\n eventListener.callStart(this)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":209,"symbol":"getResponseWithInterceptorChain","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n internal fun getResponseWithInterceptorChain(): Response {\n // Build a full stack of interceptors.\n val interceptors = mutableListOf()\n interceptors += client.interceptors\n interceptors += RetryAndFollowUpInterceptor()\n interceptors += BridgeInterceptor()\n interceptors += CacheInterceptor()\n interceptors += ConnectInterceptor\n if (!forWebSocket) {\n interceptors += client.networkInterceptors\n }\n interceptors += CallServerInterceptor\n\n val chain =\n RealInterceptorChain(\n call = this,\n interceptors = interceptors,\n index = 0,\n exchange = null,\n request = originalRequest,\n )\n\n var calledNoMoreExchanges = false\n try {\n val response = chain.proceed(originalRequest)\n if (isCanceled()) {\n response.closeQuietly()\n throw IOException(\"Canceled\")\n }\n return response\n } catch (e: IOException) {\n calledNoMoreExchanges = true\n throw noMoreExchanges(e) as Throwable\n } finally {\n if (!calledNoMoreExchanges) {\n noMoreExchanges(null)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":258,"symbol":"enterNetworkInterceptorExchange","kind":"function","lang":"kotlin","doc":"find an exchange to carry the request. Note that an exchange will not be needed if the request is satisfied by the cache. @param newRoutePlanner true if this is not a retry and new routing can be performed.","code":"fun enterNetworkInterceptorExchange(\n request: Request,\n newRoutePlanner: Boolean,\n chain: RealInterceptorChain,\n ) {\n check(interceptorScopedExchange == null)\n\n withLock {\n check(!responseBodyOpen) {\n \"cannot make a new request because the previous response is still open: \" +\n \"please call response.close()\"\n }\n check(!requestBodyOpen && !socketSourceOpen && !socketSinkOpen)\n }\n\n if (newRoutePlanner) {\n val routePlanner =\n RealRoutePlanner(\n taskRunner = client.taskRunner,\n connectionPool = chain.connectionPool.delegate,\n readTimeoutMillis = chain.readTimeoutMillis,\n writeTimeoutMillis = chain.writeTimeoutMillis,\n socketConnectTimeoutMillis = chain.connectTimeoutMillis,\n socketReadTimeoutMillis = chain.readTimeoutMillis,\n pingIntervalMillis = client.pingIntervalMillis,\n retryOnConnectionFailure = chain.retryOnConnectionFailure,\n fastFallback = client.fastFallback,\n address = chain.address(request.url),\n routeDatabase = client.routeDatabase,\n call = this,\n request = request,\n )\n this.exchange"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":299,"symbol":"initExchange","kind":"function","lang":"kotlin","doc":"Finds a new or pooled connection to carry a forthcoming request and response.","code":"internal fun initExchange(chain: RealInterceptorChain): Exchange {\n withLock {\n check(expectMoreExchanges) { \"released\" }\n check(!responseBodyOpen && !requestBodyOpen && !socketSourceOpen && !socketSinkOpen)\n }\n\n val exchangeFinder = this.exchangeFinder!!\n val connection = exchangeFinder.find()\n val codec = connection.newCodec(client, chain)\n val result = Exchange(this, exchangeFinder, codec)\n this.interceptorScopedExchange = result\n this.exchange = result\n withLock {\n this.requestBodyOpen = true\n this.responseBodyOpen = true\n }\n\n if (canceled) throw IOException(\"Canceled\")\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":320,"symbol":"acquireConnectionNoEvents","kind":"function","lang":"kotlin","code":"fun acquireConnectionNoEvents(connection: RealConnection) {\n connection.assertLockHeld()\n\n check(this.connection == null)\n this.connection = connection\n connection.calls.add(CallReference(this, callStackTrace))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":336,"symbol":"messageDone","kind":"function","lang":"kotlin","doc":"the request completes normally or when it fails due to an exception, in which case [e] should be non-null. If the exchange was canceled or timed out, this will wrap [e] in an exception that provides that additional context. Otherwise [e] is returned as-is.","code":"internal fun messageDone(\n exchange: Exchange,\n requestDone: Boolean = false,\n responseDone: Boolean = false,\n socketSourceDone: Boolean = false,\n socketSinkDone: Boolean = false,\n e: IOException?,\n ): IOException? {\n if (exchange != this.exchange) return e // This exchange was detached violently!\n\n var allStreamsDone = false\n var callDone = false\n withLock {\n if (\n requestDone && requestBodyOpen ||\n responseDone && responseBodyOpen ||\n socketSinkDone && socketSinkOpen ||\n socketSourceDone && socketSourceOpen\n ) {\n if (requestDone) requestBodyOpen = false\n if (responseDone) responseBodyOpen = false\n if (socketSinkDone) socketSinkOpen = false\n if (socketSourceDone) socketSourceOpen = false\n allStreamsDone = !requestBodyOpen &&\n !responseBodyOpen &&\n !socketSinkOpen &&\n !socketSourceOpen\n callDone = allStreamsDone && !expectMoreExchanges\n }\n }\n\n if (allStreamsDone) {\n this.exchange = null\n this.connection?.incrementSuccessCount()\n }\n\n if (callDone) {\n return callDone(e)\n }\n\n return e\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":379,"symbol":"noMoreExchanges","kind":"function","lang":"kotlin","code":"internal fun noMoreExchanges(e: IOException?): IOException? {\n var callDone = false\n withLock {\n if (expectMoreExchanges) {\n expectMoreExchanges = false\n callDone = !requestBodyOpen && !responseBodyOpen && !socketSinkOpen && !socketSourceOpen\n }\n }\n\n if (callDone) {\n return callDone(e)\n }\n\n return e\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":408,"symbol":"callDone","kind":"function","lang":"kotlin","doc":"It will also notify the listener that the call completed; either successfully or unsuccessfully. If the call was canceled or timed out, this will wrap [e] in an exception that provides that additional context. Otherwise [e] is returned as-is.","code":"private fun callDone(e: IOException?): IOException? {\n assertLockNotHeld()\n\n val connection = this.connection\n if (connection != null) {\n connection.assertLockNotHeld()\n val toClose: Socket? =\n connection.withLock {\n // Sets this.connection to null.\n releaseConnectionNoEvents()\n }\n if (this.connection == null) {\n toClose?.closeQuietly()\n eventListener.connectionReleased(this, connection)\n connection.connectionListener.connectionReleased(connection, this)\n if (toClose != null) {\n connection.connectionListener.connectionClosed(connection)\n }\n } else {\n check(toClose == null) // If we still have a connection we shouldn't be closing any sockets.\n }\n }\n\n val result = timeoutExit(e)\n if (e != null) {\n eventListener.callFailed(this, result!!)\n } else {\n eventListener.callEnd(this)\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":444,"symbol":"releaseConnectionNoEvents","kind":"function","lang":"kotlin","doc":"Remove this call from the connection's list of allocations. Returns a socket that the caller should close.","code":"internal fun releaseConnectionNoEvents(): Socket? {\n val connection = this.connection!!\n connection.assertLockHeld()\n\n val calls = connection.calls\n val index = calls.indexOfFirst { it.get() == this@RealCall }\n check(index != -1)\n\n calls.removeAt(index)\n this.connection = null\n\n if (calls.isEmpty()) {\n connection.idleAtNs = System.nanoTime()\n if (connectionPool.connectionBecameIdle(connection)) {\n return connection.socket()\n }\n }\n\n return null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":465,"symbol":"timeoutExit","kind":"function","lang":"kotlin","code":"private fun timeoutExit(cause: IOException?): IOException? {\n if (timeoutEarlyExit) return cause\n if (!timeout.exit()) return cause\n\n val e = InterruptedIOException(\"timeout\")\n if (cause != null) e.initCause(cause)\n return e\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":478,"symbol":"timeoutEarlyExit","kind":"function","lang":"kotlin","doc":"Stops applying the timeout before the call is entirely complete. This is used for WebSockets and duplex calls where the timeout only applies to the initial setup.","code":"fun timeoutEarlyExit() {\n check(!timeoutEarlyExit)\n timeoutEarlyExit = true\n timeout.exit()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":484,"symbol":"upgradeToSocket","kind":"function","lang":"kotlin","code":"fun upgradeToSocket() {\n timeoutEarlyExit()\n\n withLock {\n check(exchange != null)\n check(!socketSinkOpen && !socketSourceOpen)\n check(!requestBodyOpen)\n check(responseBodyOpen)\n responseBodyOpen = false\n socketSinkOpen = true\n socketSourceOpen = true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":502,"symbol":"exitNetworkInterceptorExchange","kind":"function","lang":"kotlin","doc":"@param closeExchange true if the current exchange should be closed because it will not be used. This is usually due to either an exception or a retry.","code":"internal fun exitNetworkInterceptorExchange(closeExchange: Boolean) {\n withLock {\n check(expectMoreExchanges) { \"released\" }\n }\n\n if (closeExchange) {\n exchange?.detachWithViolence()\n }\n\n interceptorScopedExchange = null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":514,"symbol":"retryAfterFailure","kind":"function","lang":"kotlin","code":"fun retryAfterFailure(): Boolean =\n exchange?.hasFailure == true &&\n exchangeFinder!!.routePlanner.hasNext(exchange?.connection)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":522,"symbol":"toLoggableString","kind":"function","lang":"kotlin","doc":"Returns a string that describes this call. Doesn't include a full URL as that might contain sensitive information.","code":"private fun toLoggableString(): String =\n (\n (if (isCanceled()) \"canceled \" else \"\") +\n (if (forWebSocket) \"web socket\" else \"call\") +\n \" to \" + redactedUrl()\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":529,"symbol":"redactedUrl","kind":"function","lang":"kotlin","code":"internal fun redactedUrl(): String = originalRequest.url.redact()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":531,"symbol":"AsyncCall","kind":"class","lang":"kotlin","code":"inner class AsyncCall(\n private val responseCallback: Callback,\n ) : Runnable {\n @Volatile var callsPerHost = AtomicInteger(0)\n private set\n\n fun reuseCallsPerHostFrom(other: AsyncCall) {\n this.callsPerHost = other.callsPerHost\n }\n\n val host: String\n get() = originalRequest.url.host\n\n val request: Request\n get() = originalRequest\n\n val call: RealCall\n get() = this@RealCall\n\n /**\n * Attempt to enqueue this async call on [executorService]. This will attempt to clean up\n * if the executor has been shut down by reporting the call as failed.\n */\n fun executeOn(executorService: ExecutorService) {\n client.dispatcher.assertLockNotHeld()\n\n var success = false\n try {\n executorService.execute(this)\n success = true\n } catch (e: RejectedExecutionException) {\n failRejected(e)\n } finally {\n if (!success) {\n client.dispatcher.finished(this) // This call is no longer running!\n }\n }\n }\n\n internal fun failRejected(e: RejectedExecutionException? = null) {\n val ioException = InterruptedIOException(\"executor rejected\")\n ioException.initCause(e)\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":537,"symbol":"reuseCallsPerHostFrom","kind":"function","lang":"kotlin","code":"fun reuseCallsPerHostFrom(other: AsyncCall) {\n this.callsPerHost = other.callsPerHost\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":554,"symbol":"executeOn","kind":"function","lang":"kotlin","doc":"Attempt to enqueue this async call on [executorService]. This will attempt to clean up if the executor has been shut down by reporting the call as failed.","code":"fun executeOn(executorService: ExecutorService) {\n client.dispatcher.assertLockNotHeld()\n\n var success = false\n try {\n executorService.execute(this)\n success = true\n } catch (e: RejectedExecutionException) {\n failRejected(e)\n } finally {\n if (!success) {\n client.dispatcher.finished(this) // This call is no longer running!\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":570,"symbol":"failRejected","kind":"function","lang":"kotlin","code":"internal fun failRejected(e: RejectedExecutionException? = null) {\n val ioException = InterruptedIOException(\"executor rejected\")\n ioException.initCause(e)\n noMoreExchanges(ioException)\n responseCallback.onFailure(this@RealCall, ioException)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealCall.kt","line":577,"symbol":"run","kind":"function","lang":"kotlin","code":"override fun run() {\n threadName(\"OkHttp ${redactedUrl()}\") {\n var signalledCallback = false\n timeout.enter()\n try {\n val response = getResponseWithInterceptorChain()\n signalledCallback = true\n responseCallback.onResponse(this@RealCall, response)\n } catch (e: IOException) {\n if (signalledCallback) {\n // Do not signal the callback twice!\n Platform.get().log(\"Callback failure for ${toLoggableString()}\", Platform.INFO, e)\n } else {\n responseCallback.onFailure(this@RealCall, e)\n }\n } catch (t: Throwable) {\n cancel()\n if (!signalledCallback) {\n val canceledException = IOException(\"canceled due to $t\")\n canceledException.initCause(t)\n responseCallback.onFailure(this@RealCall, canceledException)\n }\n if (t is InterruptedException) {\n Thread.currentThread().interrupt()\n } else {\n throw t\n }\n } finally {\n client.dispatcher.finished(this)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":63,"symbol":"RealConnection","kind":"class","lang":"kotlin","doc":"A connection to a remote web server capable of carrying 1 or more concurrent streams. Connections are shared in a connection pool. Accesses to the connection's state must be guarded by holding a lock on the connection.","code":"@OkHttpInternalApi\nclass RealConnection internal constructor(\n val taskRunner: TaskRunner,\n val connectionPool: RealConnectionPool,\n override val route: Route,\n /** The low-level TCP socket. */\n private val rawSocket: JavaNetSocket,\n /**\n * The application layer socket. Either an [SSLSocket] layered over [rawSocket], or [rawSocket]\n * itself if this connection does not use SSL.\n */\n private val javaNetSocket: JavaNetSocket,\n private val handshake: Handshake?,\n private val protocol: Protocol,\n private val socket: BufferedSocket,\n private val pingIntervalMillis: Int,\n internal val connectionListener: ConnectionListener,\n) : Http2Connection.Listener(),\n Connection,\n ExchangeCodec.Carrier,\n Lockable {\n private var http2Connection: Http2Connection? = null\n\n // These properties are guarded by `this`.\n\n /**\n * If true, no new exchanges can be created on this connection. It is necessary to set this to\n * true when removing a connection from the pool; otherwise a racing caller might get it from the\n * pool when it shouldn't. Symmetrically, this must always be checked before returning a\n * connection from the pool.\n *\n * Once true this is always true. Guar"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":134,"symbol":"noNewExchanges","kind":"function","lang":"kotlin","doc":"Prevent further exchanges from being created on this connection.","code":"override fun noNewExchanges() {\n withLock {\n noNewExchanges = true\n }\n connectionListener.noNewExchanges(this)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":142,"symbol":"noCoalescedConnections","kind":"function","lang":"kotlin","doc":"Prevent this connection from being used for hosts other than the one in [route].","code":"internal fun noCoalescedConnections() {\n withLock {\n noCoalescedConnections = true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":148,"symbol":"incrementSuccessCount","kind":"function","lang":"kotlin","code":"internal fun incrementSuccessCount() {\n withLock {\n successCount++\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":154,"symbol":"start","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun start() {\n idleAtNs = System.nanoTime()\n if (protocol == Protocol.HTTP_2 || protocol == Protocol.H2_PRIOR_KNOWLEDGE) {\n startHttp2()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":162,"symbol":"startHttp2","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun startHttp2() {\n javaNetSocket.soTimeout = 0 // HTTP/2 connection timeouts are set per-stream.\n val flowControlListener = connectionListener as? FlowControlListener ?: FlowControlListener.None\n val http2Connection =\n Http2Connection\n .Builder(client = true, taskRunner)\n .socket(socket, route.address.url.host)\n .listener(this)\n .pingIntervalMillis(pingIntervalMillis)\n .flowControlListener(flowControlListener)\n .build()\n this.http2Connection = http2Connection\n this.allocationLimit = Http2Connection.DEFAULT_SETTINGS.getMaxConcurrentStreams()\n http2Connection.start()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":183,"symbol":"isEligible","kind":"function","lang":"kotlin","doc":"Returns true if this connection can carry a stream allocation to `address`. If non-null `route` is the resolved route for a connection.","code":"internal fun isEligible(\n address: Address,\n routes: List?,\n ): Boolean {\n assertLockHeld()\n\n // If this connection is not accepting new exchanges, we're done.\n if (calls.size >= allocationLimit || noNewExchanges) return false\n\n // If the non-host fields of the address don't overlap, we're done.\n if (!this.route.address.equalsNonHost(address)) return false\n\n // If the host exactly matches, we're done: this connection can carry the address.\n if (address.url.host ==\n this\n .route()\n .address.url.host\n ) {\n return true // This connection is a perfect match.\n }\n\n // At this point we don't have a hostname match. But we still be able to carry the request if\n // our connection coalescing requirements are met. See also:\n // https://hpbn.co/optimizing-application-delivery/#eliminate-domain-sharding\n // https://daniel.haxx.se/blog/2016/08/18/http2-connection-coalescing/\n\n // 1. This connection must be HTTP/2.\n if (http2Connection == null) return false\n\n // 2. The routes must share an IP address.\n if (routes == null || !routeMatchesAny(routes)) return false\n\n // 3. This connection's server certificates"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":235,"symbol":"routeMatchesAny","kind":"function","lang":"kotlin","doc":"Returns true if this connection's route has the same address as any of [candidates]. This requires us to have a DNS address for both hosts, which only happens after route planning. We can't coalesce connections that use a proxy, since proxies don't tell us the origin server's IP address.","code":"private fun routeMatchesAny(candidates: List): Boolean =\n candidates.any {\n it.proxy.type() == Proxy.Type.DIRECT &&\n route.proxy.type() == Proxy.Type.DIRECT &&\n route.socketAddress == it.socketAddress\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":242,"symbol":"supportsUrl","kind":"function","lang":"kotlin","code":"private fun supportsUrl(url: HttpUrl): Boolean {\n assertLockHeld()\n\n val routeUrl = route.address.url\n\n if (url.port != routeUrl.port) {\n return false // Port mismatch.\n }\n\n if (url.host == routeUrl.host) {\n return true // Host match. The URL is supported.\n }\n\n // We have a host mismatch. But if the certificate matches, we're still good.\n return !noCoalescedConnections && handshake != null && certificateSupportHost(url, handshake)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":259,"symbol":"certificateSupportHost","kind":"function","lang":"kotlin","code":"private fun certificateSupportHost(\n url: HttpUrl,\n handshake: Handshake,\n ): Boolean {\n val peerCertificates = handshake.peerCertificates\n\n return peerCertificates.isNotEmpty() &&\n OkHostnameVerifier.verify(url.host, peerCertificates[0] as X509Certificate)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":269,"symbol":"newCodec","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n internal fun newCodec(\n client: OkHttpClient,\n chain: RealInterceptorChain,\n ): ExchangeCodec {\n val okHttpSocket = this.socket\n val http2Connection = this.http2Connection\n\n return if (http2Connection != null) {\n Http2ExchangeCodec(client, this, chain, http2Connection)\n } else {\n javaNetSocket.soTimeout = chain.readTimeoutMillis()\n okHttpSocket.source.timeout().timeout(chain.readTimeoutMillis.toLong(), MILLISECONDS)\n okHttpSocket.sink.timeout().timeout(chain.writeTimeoutMillis.toLong(), MILLISECONDS)\n Http1ExchangeCodec(client, this, okHttpSocket)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":287,"symbol":"useAsSocket","kind":"function","lang":"kotlin","code":"internal fun useAsSocket() {\n javaNetSocket.soTimeout = 0\n noNewExchanges()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":292,"symbol":"route","kind":"function","lang":"kotlin","code":"override fun route(): Route = route"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":294,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n // Close the raw socket so we don't end up doing synchronous I/O.\n rawSocket.closeQuietly()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":299,"symbol":"socket","kind":"function","lang":"kotlin","code":"override fun socket(): JavaNetSocket = javaNetSocket"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":302,"symbol":"isHealthy","kind":"function","lang":"kotlin","doc":"Returns true if this connection is ready to host new streams.","code":"fun isHealthy(doExtensiveChecks: Boolean): Boolean {\n assertLockNotHeld()\n\n val nowNs = System.nanoTime()\n\n if (rawSocket.isClosed ||\n javaNetSocket.isClosed ||\n javaNetSocket.isInputShutdown ||\n javaNetSocket.isOutputShutdown\n ) {\n return false\n }\n\n val http2Connection = this.http2Connection\n if (http2Connection != null) {\n return http2Connection.isHealthy(nowNs)\n }\n\n val idleDurationNs = withLock { nowNs - idleAtNs }\n if (idleDurationNs >= IDLE_CONNECTION_HEALTHY_NS && doExtensiveChecks) {\n return javaNetSocket.isHealthy(socket.source)\n }\n\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":329,"symbol":"onStream","kind":"function","lang":"kotlin","doc":"Refuse incoming streams.","code":"@Throws(IOException::class)\n override fun onStream(stream: Http2Stream) {\n stream.close(ErrorCode.REFUSED_STREAM, null)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":335,"symbol":"onSettings","kind":"function","lang":"kotlin","doc":"When settings are received, adjust the allocation limit.","code":"override fun onSettings(\n connection: Http2Connection,\n settings: Settings,\n ) {\n withLock {\n allocationLimit = settings.getMaxConcurrentStreams()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":344,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(): Handshake? = handshake"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":347,"symbol":"connectFailed","kind":"function","lang":"kotlin","doc":"Track a bad route in the route database. Other routes will be attempted first.","code":"internal fun connectFailed(\n client: OkHttpClient,\n failedRoute: Route,\n failure: IOException,\n ) {\n // Tell the proxy selector when we fail to connect on a fresh connection.\n if (failedRoute.proxy.type() != Proxy.Type.DIRECT) {\n val address = failedRoute.address\n address.proxySelector.connectFailed(\n address.url.toUri(),\n failedRoute.proxy.address(),\n failure,\n )\n }\n\n client.routeDatabase.failed(failedRoute)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":369,"symbol":"trackFailure","kind":"function","lang":"kotlin","doc":"Track a failure using this connection. This may prevent both the connection and its route from being used for future exchanges.","code":"override fun trackFailure(\n call: RealCall,\n e: IOException?,\n ) {\n var noNewExchangesEvent = false\n withLock {\n if (e is StreamResetException) {\n when {\n e.errorCode == ErrorCode.REFUSED_STREAM -> {\n // Stop using this connection on the 2nd REFUSED_STREAM error.\n refusedStreamCount++\n if (refusedStreamCount > 1) {\n noNewExchangesEvent = !noNewExchanges\n noNewExchanges = true\n routeFailureCount++\n }\n }\n\n e.errorCode == ErrorCode.CANCEL && call.isCanceled() -> {\n // Permit any number of CANCEL errors on locally-canceled calls.\n }\n\n else -> {\n // Everything else wants a fresh connection.\n noNewExchangesEvent = !noNewExchanges\n noNewExchanges = true\n routeFailureCount++\n }\n }\n } else if (!isMultiplexed || e is ConnectionShutdownException) {\n noNewExchangesEvent = !noNewExchanges\n noNewExchanges = true\n\n // If this route hasn't completed a call, avoid it for new connections.\n if (successCount == 0) {\n if (e != null) {\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":419,"symbol":"protocol","kind":"function","lang":"kotlin","code":"override fun protocol(): Protocol = protocol"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":421,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n \"Connection{${route.address.url.host}:${route.address.url.port},\" +\n \" proxy=${route.proxy}\" +\n \" hostAddress=${route.socketAddress}\" +\n \" cipherSuite=${handshake?.cipherSuite ?: \"none\"}\" +\n \" protocol=$protocol}\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":431,"symbol":"newTestConnection","kind":"function","lang":"kotlin","code":"fun newTestConnection(\n taskRunner: TaskRunner,\n connectionPool: RealConnectionPool,\n route: Route,\n socket: JavaNetSocket,\n idleAtNs: Long,\n ): RealConnection {\n val bufferedSocket =\n object : BufferedSocket {\n override val sink = Buffer()\n override val source = Buffer()\n\n override fun cancel() {\n }\n }\n\n val result =\n RealConnection(\n taskRunner = taskRunner,\n connectionPool = connectionPool,\n route = route,\n rawSocket = JavaNetSocket(),\n javaNetSocket = socket,\n handshake = null,\n protocol = Protocol.HTTP_2,\n socket = bufferedSocket,\n pingIntervalMillis = 0,\n connectionListener = ConnectionListener.NONE,\n )\n result.idleAtNs = idleAtNs\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnection.kt","line":443,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":36,"symbol":"RealConnectionPool","kind":"class","lang":"kotlin","code":"@OkHttpInternalApi\nclass RealConnectionPool internal constructor(\n taskRunner: TaskRunner,\n /** The maximum number of idle connections across all addresses. */\n private val maxIdleConnections: Int,\n keepAliveDuration: Long,\n timeUnit: TimeUnit,\n internal val connectionListener: ConnectionListener,\n) {\n internal val keepAliveDurationNs: Long = timeUnit.toNanos(keepAliveDuration)\n\n private val cleanupQueue: TaskQueue = taskRunner.newQueue()\n private val cleanupTask =\n object : Task(\"$okHttpName ConnectionPool connection closer\") {\n override fun runOnce(): Long = closeConnections(System.nanoTime())\n }\n\n /**\n * Holding the lock of the connection being added or removed when mutating this, and check its\n * [RealConnection.noNewExchanges] property. This defends against races where a connection is\n * simultaneously adopted and removed.\n */\n private val connections = ConcurrentLinkedQueue()\n\n init {\n // Put a floor on the keep alive duration, otherwise cleanup will spin loop.\n require(keepAliveDuration > 0L) { \"keepAliveDuration <= 0: $keepAliveDuration\" }\n }\n\n fun idleConnectionCount(): Int =\n connections.count {\n it.withLock {"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":50,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long = closeConnections(System.nanoTime())"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":65,"symbol":"idleConnectionCount","kind":"function","lang":"kotlin","code":"fun idleConnectionCount(): Int =\n connections.count {\n it.withLock { it.calls.isEmpty() }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":70,"symbol":"connectionCount","kind":"function","lang":"kotlin","code":"fun connectionCount(): Int = connections.size"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":84,"symbol":"callAcquirePooledConnection","kind":"function","lang":"kotlin","doc":"unhealthy connections in its search, this will clean them up. If [routes] is non-null these are the resolved routes (ie. IP addresses) for the connection. This is used to coalesce related domains to the same HTTP/2 connection, such as `square.com` and `square.ca`.","code":"internal fun callAcquirePooledConnection(\n doExtensiveHealthChecks: Boolean,\n address: Address,\n call: RealCall,\n routes: List?,\n requireMultiplexed: Boolean,\n ): RealConnection? {\n for (connection in connections) {\n // In the first synchronized block, acquire the connection if it can satisfy this call.\n val acquired =\n connection.withLock {\n when {\n requireMultiplexed && !connection.isMultiplexed -> {\n false\n }\n\n !connection.isEligible(address, routes) -> {\n false\n }\n\n else -> {\n call.acquireConnectionNoEvents(connection)\n true\n }\n }\n }\n if (!acquired) continue\n\n // Confirm the connection is healthy and return it.\n if (connection.isHealthy(doExtensiveHealthChecks)) return connection\n\n // In the second synchronized block, release the unhealthy acquired connection. We're also on\n // the hook to close this connection if it's no longer in use.\n val noNewExchangesEvent: Boolean\n val toClose: Socket? =\n connection.withLock {\n noNewExchangesEvent = !conne"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":134,"symbol":"put","kind":"function","lang":"kotlin","code":"fun put(connection: RealConnection) {\n connection.assertLockHeld()\n\n connections.add(connection)\n// connection.queueEvent { connectionListener.connectEnd(connection) }\n scheduleCloser()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":146,"symbol":"connectionBecameIdle","kind":"function","lang":"kotlin","doc":"Notify this pool that [connection] has become idle. Returns true if the connection has been removed from the pool and should be closed.","code":"fun connectionBecameIdle(connection: RealConnection): Boolean {\n connection.assertLockHeld()\n\n return if (connection.noNewExchanges || maxIdleConnections == 0) {\n connection.noNewExchanges = true\n connections.remove(connection)\n if (connections.isEmpty()) cleanupQueue.cancelAll()\n true\n } else {\n scheduleCloser()\n false\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":160,"symbol":"evictAll","kind":"function","lang":"kotlin","code":"fun evictAll() {\n val i = connections.iterator()\n while (i.hasNext()) {\n val connection = i.next()\n val socketToClose =\n connection.withLock {\n if (connection.calls.isEmpty()) {\n i.remove()\n connection.noNewExchanges = true\n return@withLock connection.socket()\n } else {\n return@withLock null\n }\n }\n if (socketToClose != null) {\n socketToClose.closeQuietly()\n connectionListener.connectionClosed(connection)\n }\n }\n\n if (connections.isEmpty()) cleanupQueue.cancelAll()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":190,"symbol":"closeConnections","kind":"function","lang":"kotlin","doc":"Performs maintenance on this pool, evicting the connection that has been idle the longest if either it has exceeded the keep alive limit or the idle connections limit. Returns the duration in nanoseconds to sleep until the next scheduled call to this method. Returns -1 if no further cleanups are required.","code":"fun closeConnections(now: Long): Long {\n // Find the longest-idle connections in 2 categories:\n //\n // 1. OLD: Connections that have been idle for at least keepAliveDurationNs. We close these if\n // we find them, regardless of what the address policies need.\n //\n // 2. EVICTABLE: Connections not required by any address policy. This matches connections that\n // don't participate in any policy, plus connections whose policies won't be violated if the\n // connection is closed. We only close these if the idle connection limit is exceeded.\n //\n // Also count the evictable connections to find out if we must close an EVICTABLE connection\n // before its keepAliveDurationNs is reached.\n var earliestOldIdleAtNs = (now - keepAliveDurationNs) + 1\n var earliestOldConnection: RealConnection? = null\n var earliestEvictableIdleAtNs = Long.MAX_VALUE\n var earliestEvictableConnection: RealConnection? = null\n var inUseConnectionCount = 0\n var evictableConnectionCount = 0\n for (connection in connections) {\n connection.withLock {\n // If the connection is in use, keep searching.\n if (pruneAndGetAllocationCount(connectio"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":291,"symbol":"pruneAndGetAllocationCount","kind":"function","lang":"kotlin","doc":"Prunes any leaked calls and then returns the number of remaining live calls on [connection]. Calls are leaked if the connection is tracking them but the application code has abandoned them. Leak detection is imprecise and relies on garbage collection.","code":"private fun pruneAndGetAllocationCount(\n connection: RealConnection,\n now: Long,\n ): Int {\n connection.assertLockHeld()\n\n val references = connection.calls\n var i = 0\n while (i < references.size) {\n val reference = references[i]\n\n if (reference.get() != null) {\n i++\n continue\n }\n\n // We've discovered a leaked call. This is an application bug.\n val callReference = reference as CallReference\n val message =\n \"A connection to ${connection.route().address.url} was leaked. \" +\n \"Did you forget to close a response body?\"\n Platform.get().logCloseableLeak(message, callReference.callStackTrace)\n\n references.removeAt(i)\n\n // If this was the last allocation, the connection is eligible for immediate eviction.\n if (references.isEmpty()) {\n connection.idleAtNs = now - keepAliveDurationNs\n return 0\n }\n }\n\n return references.size\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":326,"symbol":"scheduleCloser","kind":"function","lang":"kotlin","code":"fun scheduleCloser() {\n cleanupQueue.schedule(cleanupTask)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealConnectionPool.kt","line":331,"symbol":"get","kind":"function","lang":"kotlin","code":"fun get(connectionPool: ConnectionPool): RealConnectionPool = connectionPool.delegate"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":39,"symbol":"RealRoutePlanner","kind":"class","lang":"kotlin","code":"@OkHttpInternalApi\nclass RealRoutePlanner internal constructor(\n private val taskRunner: TaskRunner,\n private val connectionPool: RealConnectionPool,\n private val readTimeoutMillis: Int,\n private val writeTimeoutMillis: Int,\n private val socketConnectTimeoutMillis: Int,\n private val socketReadTimeoutMillis: Int,\n private val pingIntervalMillis: Int,\n private val retryOnConnectionFailure: Boolean,\n private val fastFallback: Boolean,\n override val address: Address,\n private val routeDatabase: RouteDatabase,\n private val call: RealCall,\n request: Request,\n) : RoutePlanner {\n private val doExtensiveHealthChecks = request.method != \"GET\"\n private var routeSelection: RouteSelector.Selection? = null\n private var routeSelector: RouteSelector? = null\n private var nextRouteToTry: Route? = null\n\n override val deferredPlans = ArrayDeque()\n\n override fun isCanceled(): Boolean = call.isCanceled()\n\n @Throws(IOException::class)\n override fun plan(): Plan {\n val reuseCallConnection = planReuseCallConnection()\n if (reuseCallConnection != null) return reuseCallConnection\n\n // Attempt to get a connection from the pool.\n val pooled1 = planReusePooledConnection()\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":62,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"override fun isCanceled(): Boolean = call.isCanceled()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":64,"symbol":"plan","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun plan(): Plan {\n val reuseCallConnection = planReuseCallConnection()\n if (reuseCallConnection != null) return reuseCallConnection\n\n // Attempt to get a connection from the pool.\n val pooled1 = planReusePooledConnection()\n if (pooled1 != null) return pooled1\n\n // Attempt a deferred plan before new routes.\n if (deferredPlans.isNotEmpty()) return deferredPlans.removeFirst()\n\n // Do blocking calls to plan a route for a new connection.\n val connect = planConnect()\n\n // Now that we have a set of IP addresses, make another attempt at getting a connection from\n // the pool. We have a better chance of matching thanks to connection coalescing.\n val pooled2 = planReusePooledConnection(connect, connect.routes)\n if (pooled2 != null) return pooled2\n\n return connect\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":93,"symbol":"planReuseCallConnection","kind":"function","lang":"kotlin","doc":"Returns the connection already attached to the call if it's eligible for a new exchange. If the call's connection exists and is eligible for another exchange, it is returned. If it exists but cannot be used for another exchange, it is closed and this returns null.","code":"private fun planReuseCallConnection(): ReusePlan? {\n // This may be mutated by releaseConnectionNoEvents()!\n val candidate = call.connection ?: return null\n\n // Make sure this connection is healthy & eligible for new exchanges. If it's no longer needed\n // then we're on the hook to close it.\n val healthy = candidate.isHealthy(doExtensiveHealthChecks)\n var noNewExchangesEvent = false\n val toClose: Socket? =\n candidate.withLock {\n when {\n !healthy -> {\n noNewExchangesEvent = !candidate.noNewExchanges\n candidate.noNewExchanges = true\n call.releaseConnectionNoEvents()\n }\n\n candidate.noNewExchanges || !sameHostAndPort(candidate.route().address.url) -> {\n call.releaseConnectionNoEvents()\n }\n\n else -> {\n null\n }\n }\n }\n\n // If the call's connection wasn't released, reuse it. We don't call connectionAcquired() here\n // because we already acquired it.\n if (call.connection != null) {\n check(toClose == null)\n return ReusePlan(candidate)\n }\n\n // The call's connection was released.\n toClose?.closeQuietly()\n call.e"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":140,"symbol":"planConnect","kind":"function","lang":"kotlin","doc":"Plans to make a new connection by deciding which route to try next.","code":"@Throws(IOException::class)\n internal fun planConnect(): ConnectPlan {\n // Use a route from a preceding coalesced connection.\n val localNextRouteToTry = nextRouteToTry\n if (localNextRouteToTry != null) {\n nextRouteToTry = null\n return planConnectToRoute(localNextRouteToTry)\n }\n\n // Use a route from an existing route selection.\n val existingRouteSelection = routeSelection\n if (existingRouteSelection != null && existingRouteSelection.hasNext()) {\n return planConnectToRoute(existingRouteSelection.next())\n }\n\n // Decide which proxy to use, if any. This may block in ProxySelector.select().\n var newRouteSelector = routeSelector\n if (newRouteSelector == null) {\n newRouteSelector =\n RouteSelector(\n address = address,\n routeDatabase = routeDatabase,\n call = call,\n fastFallback = fastFallback,\n )\n routeSelector = newRouteSelector\n }\n\n // List available IP addresses for the current proxy. This may block in Dns.lookup().\n if (!newRouteSelector.hasNext()) throw IOException(\"exhausted all routes\")\n val newRouteSelection = newRouteSelector.next()\n routeSelection = newRouteSe"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":185,"symbol":"planReusePooledConnection","kind":"function","lang":"kotlin","doc":"Returns a plan to reuse a pooled connection, or null if the pool doesn't have a connection for this address. If [planToReplace] is non-null, this will swap it for a pooled connection if that pooled connection uses HTTP/2. That results in fewer sockets overall and thus fewer TCP slow starts.","code":"internal fun planReusePooledConnection(\n planToReplace: ConnectPlan? = null,\n routes: List? = null,\n ): ReusePlan? {\n val result =\n connectionPool.callAcquirePooledConnection(\n doExtensiveHealthChecks = doExtensiveHealthChecks,\n address = address,\n call = call,\n routes = routes,\n requireMultiplexed = planToReplace != null && planToReplace.isReady,\n ) ?: return null\n\n // If we coalesced our connection, remember the replaced connection's route. That way if the\n // coalesced connection later fails we don't waste a valid route.\n if (planToReplace != null) {\n nextRouteToTry = planToReplace.route\n planToReplace.closeQuietly()\n }\n\n call.eventListener.connectionAcquired(call, result)\n result.connectionListener.connectionAcquired(result, call)\n return ReusePlan(result)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":211,"symbol":"planConnectToRoute","kind":"function","lang":"kotlin","doc":"Returns a plan for the first attempt at [route]. This throws if no plan is possible.","code":"@Throws(IOException::class)\n internal fun planConnectToRoute(\n route: Route,\n routes: List? = null,\n ): ConnectPlan {\n if (route.address.sslSocketFactory == null) {\n if (ConnectionSpec.CLEARTEXT !in route.address.connectionSpecs) {\n throw UnknownServiceException(\"CLEARTEXT communication not enabled for client\")\n }\n\n val host = route.address.url.host\n if (!Platform.get().isCleartextTrafficPermitted(host)) {\n throw UnknownServiceException(\n \"CLEARTEXT communication to $host not permitted by network security policy\",\n )\n }\n } else {\n if (Protocol.H2_PRIOR_KNOWLEDGE in route.address.protocols) {\n throw UnknownServiceException(\"H2_PRIOR_KNOWLEDGE cannot be used with HTTPS\")\n }\n }\n\n val tunnelRequest =\n when {\n route.requiresTunnel() -> createTunnelRequest(route)\n else -> null\n }\n\n return ConnectPlan(\n taskRunner = taskRunner,\n connectionPool = connectionPool,\n readTimeoutMillis = readTimeoutMillis,\n writeTimeoutMillis = writeTimeoutMillis,\n socketConnectTimeoutMillis = socketConnectTimeoutMillis,\n socketReadTimeoutMillis = socketRead"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":268,"symbol":"createTunnelRequest","kind":"function","lang":"kotlin","doc":"This avoids sending potentially sensitive data like HTTP cookies to the proxy unencrypted. In order to support preemptive authentication we pass a fake \"Auth Failed\" response to the authenticator. This gives the authenticator the option to customize the CONNECT request. It can decline to do so by returning null, in which case OkHttp will use it as-is.","code":"@Throws(IOException::class)\n private fun createTunnelRequest(route: Route): Request {\n val proxyConnectRequest =\n Request\n .Builder()\n .url(route.address.url)\n .method(\"CONNECT\", null)\n .header(\"Host\", route.address.url.toHostHeader(includeDefaultPort = true))\n .header(\"Proxy-Connection\", \"Keep-Alive\") // For HTTP/1.0 proxies like Squid.\n .header(\"User-Agent\", USER_AGENT)\n .build()\n\n val fakeAuthChallengeResponse =\n Response\n .Builder()\n .request(proxyConnectRequest)\n .protocol(Protocol.HTTP_1_1)\n .code(HttpURLConnection.HTTP_PROXY_AUTH)\n .message(\"Preemptive Authenticate\")\n .sentRequestAtMillis(-1L)\n .receivedResponseAtMillis(-1L)\n .header(\"Proxy-Authenticate\", \"OkHttp-Preemptive\")\n .build()\n\n val authenticatedRequest =\n route.address.proxyAuthenticator\n .authenticate(route, fakeAuthChallengeResponse)\n\n return authenticatedRequest ?: proxyConnectRequest\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":299,"symbol":"hasNext","kind":"function","lang":"kotlin","code":"override fun hasNext(failedConnection: RealConnection?): Boolean {\n if (deferredPlans.isNotEmpty()) {\n return true\n }\n\n if (nextRouteToTry != null) {\n return true\n }\n\n if (failedConnection != null) {\n val retryRoute = retryRoute(failedConnection)\n if (retryRoute != null) {\n // Lock in the route because retryRoute() is racy and we don't want to call it twice.\n nextRouteToTry = retryRoute\n return true\n }\n }\n\n // If we have a routes left, use 'em.\n if (routeSelection?.hasNext() == true) return true\n\n // If we haven't initialized the route selector yet, assume it'll have at least one route.\n val localRouteSelector = routeSelector ?: return true\n\n // If we do have a route selector, use its routes.\n return localRouteSelector.hasNext()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":332,"symbol":"retryRoute","kind":"function","lang":"kotlin","doc":"Return the route from [connection] if it should be retried, even if the connection itself is unhealthy. The biggest gotcha here is that we shouldn't reuse routes from coalesced connections.","code":"private fun retryRoute(connection: RealConnection): Route? =\n connection.withLock {\n when {\n connection.routeFailureCount != 0 -> null\n\n // This route is still in use.\n !connection.noNewExchanges -> null\n\n !connection\n .route()\n .address.url\n .canReuseConnectionFor(address.url) -> null\n\n else -> connection.route()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RealRoutePlanner.kt","line":349,"symbol":"sameHostAndPort","kind":"function","lang":"kotlin","code":"override fun sameHostAndPort(url: HttpUrl): Boolean {\n val routeUrl = address.url\n return url.port == routeUrl.port && url.host == routeUrl.host\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RetryTlsHandshake.kt","line":31,"symbol":"attemptAnotherConnection","kind":"function","lang":"kotlin","doc":"Returns true if another connection should be attempted to any IP address.","code":"internal fun attemptAnotherConnection(e: IOException): Boolean = e !is EchUntrustedException"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RetryTlsHandshake.kt","line":34,"symbol":"attemptAnotherConnectionSpec","kind":"function","lang":"kotlin","doc":"Returns true if the next [okhttp3.ConnectionSpec] should be attempted to the same IP address.","code":"fun attemptAnotherConnectionSpec(e: IOException): Boolean =\n when {\n // If there was a protocol problem, don't recover.\n e is ProtocolException -> false\n\n // If there was an interruption or timeout (SocketTimeoutException), don't recover.\n // For the socket connect timeout case we do not try the same host with a different\n // ConnectionSpec: we assume it is unreachable.\n e is InterruptedIOException -> false\n\n // If the problem was a CertificateException from the X509TrustManager, do not retry.\n e is SSLHandshakeException && e.cause is CertificateException -> false\n\n // e.g. a certificate pinning error.\n e is SSLPeerUnverifiedException -> false\n\n // Retry for all other SSL failures.\n e is SSLException -> true\n\n else -> false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ReusePlan.kt","line":21,"symbol":"ReusePlan","kind":"class","lang":"kotlin","doc":"Reuse a connection from the pool.","code":"@OkHttpInternalApi\ninternal class ReusePlan(\n val connection: RealConnection,\n) : RoutePlanner.Plan {\n override val isReady = true\n\n override fun connectTcp() = error(\"already connected\")\n\n override fun connectTlsEtc() = error(\"already connected\")\n\n override fun handleSuccess() = connection\n\n override fun cancel() = error(\"unexpected cancel\")\n\n override fun retry() = error(\"unexpected retry\")\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ReusePlan.kt","line":27,"symbol":"connectTcp","kind":"function","lang":"kotlin","code":"override fun connectTcp() = error(\"already connected\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ReusePlan.kt","line":29,"symbol":"connectTlsEtc","kind":"function","lang":"kotlin","code":"override fun connectTlsEtc() = error(\"already connected\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ReusePlan.kt","line":31,"symbol":"handleSuccess","kind":"function","lang":"kotlin","code":"override fun handleSuccess() = connection"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ReusePlan.kt","line":33,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() = error(\"unexpected cancel\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ReusePlan.kt","line":35,"symbol":"retry","kind":"function","lang":"kotlin","code":"override fun retry() = error(\"unexpected retry\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteDatabase.kt","line":26,"symbol":"RouteDatabase","kind":"class","lang":"kotlin","doc":"A denylist of failed routes to avoid when creating a new connection to a target address. This is used so that OkHttp can learn from its mistakes: if there was a failure attempting to connect to a specific IP address or proxy server, that failure is remembered and alternate routes are preferred.","code":"class RouteDatabase {\n private val _failedRoutes = mutableSetOf()\n\n val failedRoutes: Set\n @Synchronized get() = _failedRoutes.toSet()\n\n /** Records a failure connecting to [failedRoute]. */\n @Synchronized fun failed(failedRoute: Route) {\n _failedRoutes.add(failedRoute)\n }\n\n /** Records success connecting to [route]. */\n @Synchronized fun connected(route: Route) {\n _failedRoutes.remove(route)\n }\n\n /** Returns true if [route] has failed recently and should be avoided. */\n @Synchronized fun shouldPostpone(route: Route): Boolean = route in _failedRoutes\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteDatabase.kt","line":33,"symbol":"failed","kind":"function","lang":"kotlin","doc":"Records a failure connecting to [failedRoute].","code":"@Synchronized fun failed(failedRoute: Route) {\n _failedRoutes.add(failedRoute)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteDatabase.kt","line":38,"symbol":"connected","kind":"function","lang":"kotlin","doc":"Records success connecting to [route].","code":"@Synchronized fun connected(route: Route) {\n _failedRoutes.remove(route)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteDatabase.kt","line":43,"symbol":"shouldPostpone","kind":"function","lang":"kotlin","doc":"Returns true if [route] has failed recently and should be avoided.","code":"@Synchronized fun shouldPostpone(route: Route): Boolean = route in _failedRoutes"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":50,"symbol":"RoutePlanner","kind":"interface","lang":"kotlin","doc":"It is possible to cancel the finding process by canceling its call. Implementations of this interface are not thread-safe. Each instance is thread-confined to the thread executing the call.","code":"@OkHttpInternalApi\ninterface RoutePlanner {\n val address: Address\n\n /** Follow-ups for failed plans and plans that lost a race. */\n val deferredPlans: ArrayDeque\n\n fun isCanceled(): Boolean\n\n /** Returns a plan to attempt. */\n @Throws(IOException::class)\n fun plan(): Plan\n\n /**\n * Returns true if there's more route plans to try.\n *\n * @param failedConnection an optional connection that was resulted in a failure. If the failure\n * is recoverable, the connection's route may be recovered for the retry.\n */\n fun hasNext(failedConnection: RealConnection? = null): Boolean\n\n /**\n * Returns true if the host and port are unchanged from when this was created. This is used to\n * detect if followups need to do a full connection-finding process including DNS resolution, and\n * certificate pin checks.\n */\n fun sameHostAndPort(url: HttpUrl): Boolean\n\n /**\n * A plan holds either an immediately-usable connection, or one that must be connected first.\n * These steps are split so callers can call [connectTcp] on a background thread if attempting\n * multiple plans concurrently.\n */\n interface Plan {\n val isReady: Boolean\n\n fun connectTcp(): Connect"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":57,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"fun isCanceled(): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":60,"symbol":"plan","kind":"function","lang":"kotlin","doc":"Returns a plan to attempt.","code":"@Throws(IOException::class)\n fun plan(): Plan"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":69,"symbol":"hasNext","kind":"function","lang":"kotlin","doc":"Returns true if there's more route plans to try. @param failedConnection an optional connection that was resulted in a failure. If the failure is recoverable, the connection's route may be recovered for the retry.","code":"fun hasNext(failedConnection: RealConnection? = null): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":76,"symbol":"sameHostAndPort","kind":"function","lang":"kotlin","doc":"Returns true if the host and port are unchanged from when this was created. This is used to detect if followups need to do a full connection-finding process including DNS resolution, and certificate pin checks.","code":"fun sameHostAndPort(url: HttpUrl): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":83,"symbol":"Plan","kind":"interface","lang":"kotlin","doc":"A plan holds either an immediately-usable connection, or one that must be connected first. These steps are split so callers can call [connectTcp] on a background thread if attempting multiple plans concurrently.","code":"interface Plan {\n val isReady: Boolean\n\n fun connectTcp(): ConnectResult\n\n fun connectTlsEtc(): ConnectResult\n\n fun handleSuccess(): RealConnection\n\n fun cancel()\n\n /**\n * Returns a plan to attempt if canceling this plan was a mistake! The returned plan is not\n * canceled, even if this plan is canceled.\n */\n fun retry(): Plan?\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":86,"symbol":"connectTcp","kind":"function","lang":"kotlin","code":"fun connectTcp(): ConnectResult"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":88,"symbol":"connectTlsEtc","kind":"function","lang":"kotlin","code":"fun connectTlsEtc(): ConnectResult"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":90,"symbol":"handleSuccess","kind":"function","lang":"kotlin","code":"fun handleSuccess(): RealConnection"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":92,"symbol":"cancel","kind":"function","lang":"kotlin","code":"fun cancel()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":98,"symbol":"retry","kind":"function","lang":"kotlin","doc":"Returns a plan to attempt if canceling this plan was a mistake! The returned plan is not canceled, even if this plan is canceled.","code":"fun retry(): Plan?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RoutePlanner.kt","line":110,"symbol":"ConnectResult","kind":"class","lang":"kotlin","doc":"If [nextPlan] is not-null, another attempt should be made by following it. If [throwable] is non-null, it should be reported to the user should all further attempts fail. The two values are independent: results can contain both (recoverable error), neither (success), just an exception (permanent failure), or just a plan (non-exceptional retry).","code":"data class ConnectResult(\n val plan: Plan,\n val nextPlan: Plan? = null,\n val throwable: Throwable? = null,\n ) {\n val isSuccess: Boolean\n get() = nextPlan == null && throwable == null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteSelector.kt","line":39,"symbol":"RouteSelector","kind":"class","lang":"kotlin","doc":"Selects routes to connect to an origin server. Each connection requires a choice of proxy server, IP address, and TLS mode. Connections may also be recycled.","code":"@OkHttpInternalApi\nclass RouteSelector internal constructor(\n private val address: Address,\n private val routeDatabase: RouteDatabase,\n private val call: RealCall,\n private val fastFallback: Boolean,\n) {\n // State for negotiating the next proxy to use.\n private var proxies = emptyList()\n private var nextProxyIndex: Int = 0\n\n // State for negotiating failed routes\n private val postponedRoutes = mutableListOf()\n\n init {\n resetNextProxy(address.url, address.proxy)\n }\n\n /**\n * Returns true if there's another set of routes to attempt. Every address has at least one route.\n */\n operator fun hasNext(): Boolean = hasNextProxy() || postponedRoutes.isNotEmpty()\n\n @Throws(IOException::class)\n operator fun next(): Selection {\n if (!hasNext()) throw NoSuchElementException()\n\n // Compute the next set of routes to attempt.\n val routes = mutableListOf()\n while (hasNextProxy()) {\n // Postponed routes are always tried last. For example, if we have 2 proxies and all the\n // routes for proxy1 should be postponed, we'll move to proxy2. Only after we've exhausted\n // all the good routes will we attempt the postponed routes.\n val "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteSelector.kt","line":60,"symbol":"hasNext","kind":"function","lang":"kotlin","doc":"Returns true if there's another set of routes to attempt. Every address has at least one route.","code":"operator fun hasNext(): Boolean = hasNextProxy() || postponedRoutes.isNotEmpty()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteSelector.kt","line":62,"symbol":"next","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n operator fun next(): Selection {\n if (!hasNext()) throw NoSuchElementException()\n\n // Compute the next set of routes to attempt.\n val routes = mutableListOf()\n while (hasNextProxy()) {\n // Postponed routes are always tried last. For example, if we have 2 proxies and all the\n // routes for proxy1 should be postponed, we'll move to proxy2. Only after we've exhausted\n // all the good routes will we attempt the postponed routes.\n val proxyRoutes = nextProxy()\n for (route in proxyRoutes) {\n if (routeDatabase.shouldPostpone(route)) {\n postponedRoutes += route\n } else {\n routes += route\n }\n }\n\n if (routes.isNotEmpty()) {\n break\n }\n }\n\n if (routes.isEmpty()) {\n // We've exhausted all Proxies so fallback to the postponed routes.\n routes += postponedRoutes\n postponedRoutes.clear()\n }\n\n return Selection(routes)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteSelector.kt","line":96,"symbol":"resetNextProxy","kind":"function","lang":"kotlin","doc":"Prepares the proxy servers to try.","code":"private fun resetNextProxy(\n url: HttpUrl,\n proxy: Proxy?,\n ) {\n fun selectProxies(): List {\n // If the user specifies a proxy, try that and only that.\n if (proxy != null) return listOf(proxy)\n\n // If the URI lacks a host (as in \"http:// {\n // If the user specifies a proxy, try that and only that.\n if (proxy != null) return listOf(proxy)\n\n // If the URI lacks a host (as in \"http:// {\n if (!hasNextProxy()) {\n throw SocketException(\n \"No route to ${address.url.host}; exhausted proxy configurations: $proxies\",\n )\n }\n val result = proxies[nextProxyIndex++]\n return nextRoutes(result)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteSelector.kt","line":144,"symbol":"nextRoutes","kind":"function","lang":"kotlin","doc":"Returns the routes to attempt for [proxy].","code":"@Throws(IOException::class)\n private fun nextRoutes(proxy: Proxy): List {\n val socketHost: String\n val socketPort: Int\n if (proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.SOCKS) {\n socketHost = address.url.host\n socketPort = address.url.port\n } else {\n val proxyAddress = proxy.address()\n require(proxyAddress is InetSocketAddress) {\n \"Proxy.address() is not an InetSocketAddress: ${proxyAddress.javaClass}\"\n }\n socketHost = proxyAddress.socketHost\n socketPort = proxyAddress.port\n }\n\n if (socketPort !in 1..65535) {\n throw SocketException(\"No route to $socketHost:$socketPort; port is out of range\")\n }\n\n if (proxy.type() == Proxy.Type.SOCKS) {\n return listOf(\n Route(\n address,\n proxy,\n InetSocketAddress.createUnresolved(socketHost, socketPort),\n ),\n )\n }\n\n if (socketHost.canParseAsIpAddress()) {\n return listOf(\n Route(\n address,\n proxy,\n InetSocketAddress(InetAddress.getByName(socketHost), socketPort),\n ),\n )\n }\n\n val routes = dnsLookup(proxy, socketHost, socketPort)\n\n // If DNS"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteSelector.kt","line":206,"symbol":"dnsLookup","kind":"function","lang":"kotlin","doc":"Use the new async [Dns.Call] API, but call it *synchronously* until we change this class to itself be asynchronous. To save threads and context switching, this currently falls back to the synchronous API if the DNS implementation is itself synchronous. When everything is async we won't do that anymore.","code":"private fun dnsLookup(\n proxy: Proxy,\n socketHost: String,\n socketPort: Int,\n ): List {\n call.eventListener.dnsStart(\n call = call,\n domainName = socketHost,\n )\n\n // If it's a 'http://' URL on the default port, do the DNS query for a 'https://' URL on the\n // default port. DNS records that have a port promote HTTP to HTTPS.\n val dnsPort =\n when {\n !address.url.isHttps && socketPort == 80 -> -1\n else -> socketPort\n }\n\n val dnsRequest = Dns.Request(socketHost, dnsPort)\n val result =\n when (val dnsCall = address.dns.newCall(dnsRequest)) {\n is LookupDnsCall -> {\n val inetAddresses = address.dns.lookup(socketHost)\n inetAddresses.map { inetAddress ->\n Route(\n address,\n proxy,\n InetSocketAddress(inetAddress, socketPort),\n )\n }\n }\n\n else -> {\n val records = dnsCall.execute()\n\n val hostnameToServiceMetadata =\n records\n .filterIsInstance()\n .associateBy { it.hostname }\n\n records\n .filterIsInstance,\n ) {\n private var nextRouteIndex = 0\n\n operator fun hasNext(): Boolean = nextRouteIndex < routes.size\n\n operator fun next(): Route {\n if (!hasNext()) throw NoSuchElementException()\n return routes[nextRouteIndex++]\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteSelector.kt","line":283,"symbol":"hasNext","kind":"function","lang":"kotlin","code":"operator fun hasNext(): Boolean = nextRouteIndex < routes.size"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/RouteSelector.kt","line":285,"symbol":"next","kind":"function","lang":"kotlin","code":"operator fun next(): Route {\n if (!hasNext()) throw NoSuchElementException()\n return routes[nextRouteIndex++]\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/SequentialExchangeFinder.kt","line":22,"symbol":"SequentialExchangeFinder","kind":"class","lang":"kotlin","doc":"Attempt routes one at a time until one connects.","code":"@OkHttpInternalApi\ninternal class SequentialExchangeFinder(\n override val routePlanner: RoutePlanner,\n) : ExchangeFinder {\n override fun find(): RealConnection {\n var firstException: IOException? = null\n while (true) {\n if (routePlanner.isCanceled()) throw IOException(\"Canceled\")\n\n try {\n val plan = routePlanner.plan()\n\n if (!plan.isReady) {\n val tcpConnectResult = plan.connectTcp()\n val connectResult =\n when {\n tcpConnectResult.isSuccess -> plan.connectTlsEtc()\n else -> tcpConnectResult\n }\n\n val (_, nextPlan, failure) = connectResult\n\n if (failure != null) throw failure\n if (nextPlan != null) {\n routePlanner.deferredPlans.addFirst(nextPlan)\n continue\n }\n }\n return plan.handleSuccess()\n } catch (e: IOException) {\n if (firstException == null) {\n firstException = e\n } else {\n firstException.addSuppressed(e)\n }\n if (!attemptAnotherConnection(e)) {\n throw firstException\n }\n if (!routePlanner.hasNext()) {\n throw firstException\n }\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/SequentialExchangeFinder.kt","line":26,"symbol":"find","kind":"function","lang":"kotlin","code":"override fun find(): RealConnection {\n var firstException: IOException? = null\n while (true) {\n if (routePlanner.isCanceled()) throw IOException(\"Canceled\")\n\n try {\n val plan = routePlanner.plan()\n\n if (!plan.isReady) {\n val tcpConnectResult = plan.connectTcp()\n val connectResult =\n when {\n tcpConnectResult.isSuccess -> plan.connectTlsEtc()\n else -> tcpConnectResult\n }\n\n val (_, nextPlan, failure) = connectResult\n\n if (failure != null) throw failure\n if (nextPlan != null) {\n routePlanner.deferredPlans.addFirst(nextPlan)\n continue\n }\n }\n return plan.handleSuccess()\n } catch (e: IOException) {\n if (firstException == null) {\n firstException = e\n } else {\n firstException.addSuppressed(e)\n }\n if (!attemptAnotherConnection(e)) {\n throw firstException\n }\n if (!routePlanner.hasNext()) {\n throw firstException\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessage.kt","line":24,"symbol":"DnsMessage","kind":"class","lang":"kotlin","code":"@OkHttpInternalApi\ndata class DnsMessage(\n val id: Short,\n val flags: Int,\n val questions: List,\n val answers: List = listOf(),\n val authorityRecords: List = listOf(),\n val additionalRecords: List = listOf(),\n) {\n val responseCode: Int\n get() = (flags and 0b0000_0000_0000_1111)\n\n companion object {\n fun query(question: Question): DnsMessage {\n // QR = 0 (Query)\n // RD = 1 (Recursion Desired)\n // OPCODE = 0 (standard query)\n // QR OPCODE AA TC RD RA Z RCODE\n val flags = 0b0___0000__0__0__1__0_000__0000\n return DnsMessage(\n id = 0,\n flags = flags,\n questions = listOf(question),\n )\n }\n\n fun response(\n id: Short = 0,\n questions: List,\n answers: List,\n ): DnsMessage {\n // QR = 1 (Response)\n // OPCODE = 0 (standard query)\n // RCODE = 0 (success)\n // QR OPCODE AA TC RD RA Z RCODE\n val flags = 0b1___0000__0__0__0__0_000__0000\n\n return DnsMessage(\n id = id,\n flags = flags,\n questions = questions,\n answers = answers,\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessage.kt","line":37,"symbol":"query","kind":"function","lang":"kotlin","code":"fun query(question: Question): DnsMessage {\n // QR = 0 (Query)\n // RD = 1 (Recursion Desired)\n // OPCODE = 0 (standard query)\n // QR OPCODE AA TC RD RA Z RCODE\n val flags = 0b0___0000__0__0__1__0_000__0000\n return DnsMessage(\n id = 0,\n flags = flags,\n questions = listOf(question),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessage.kt","line":50,"symbol":"response","kind":"function","lang":"kotlin","code":"fun response(\n id: Short = 0,\n questions: List,\n answers: List,\n ): DnsMessage {\n // QR = 1 (Response)\n // OPCODE = 0 (standard query)\n // RCODE = 0 (success)\n // QR OPCODE AA TC RD RA Z RCODE\n val flags = 0b1___0000__0__0__0__0_000__0000\n\n return DnsMessage(\n id = id,\n flags = flags,\n questions = questions,\n answers = answers,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessage.kt","line":78,"symbol":"ResourceRecord","kind":"interface","lang":"kotlin","code":"@OkHttpInternalApi\nsealed interface ResourceRecord {\n val name: String\n val timeToLive: Int\n\n data class IpAddress(\n override val name: String,\n override val timeToLive: Int,\n val address: InetAddress,\n ) : ResourceRecord\n\n data class Https(\n override val name: String,\n override val timeToLive: Int,\n val priority: Int = 1,\n val targetName: String = \"\",\n val alpnIds: List? = null,\n var port: Int = 443,\n val ipAddressHints: List = listOf(),\n val echConfigList: ByteString? = null,\n ) : ResourceRecord\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageReader.kt","line":38,"symbol":"DnsMessageReader","kind":"class","lang":"kotlin","doc":"Decode DNS messages, which are symmetric for requests and responses. https://datatracker.ietf.org/doc/html/rfc1035","code":"@OkHttpInternalApi\nclass DnsMessageReader(\n source: BufferedSource,\n) {\n /**\n * Keep a reference to the source at its initial offset, so we can implement name compression.\n * That mechanism requires us to backtrack in the message.\n */\n private val sourceOffsetZero = source\n private val source = source.peek()\n\n fun read(): DnsMessage {\n val id = source.readShort()\n val flags = source.readShort().toInt()\n\n val questionCount = source.readUShort().toInt()\n val answerCount = source.readUShort().toInt()\n val authorityRecordCount = source.readUShort().toInt()\n val additionalRecordCount = source.readUShort().toInt()\n\n val questions = ArrayList(questionCount)\n for (i in 0 until questionCount) {\n questions += source.readQuestion()\n }\n\n val answers = ArrayList(answerCount)\n for (i in 0 until answerCount) {\n answers += source.readResourceRecord() ?: continue\n }\n\n val authorityRecords = ArrayList(authorityRecordCount)\n for (i in 0 until authorityRecordCount) {\n authorityRecords += source.readResourceRecord() ?: continue\n }\n\n val additionalRecords = ArrayList(additi"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageReader.kt","line":49,"symbol":"read","kind":"function","lang":"kotlin","code":"fun read(): DnsMessage {\n val id = source.readShort()\n val flags = source.readShort().toInt()\n\n val questionCount = source.readUShort().toInt()\n val answerCount = source.readUShort().toInt()\n val authorityRecordCount = source.readUShort().toInt()\n val additionalRecordCount = source.readUShort().toInt()\n\n val questions = ArrayList(questionCount)\n for (i in 0 until questionCount) {\n questions += source.readQuestion()\n }\n\n val answers = ArrayList(answerCount)\n for (i in 0 until answerCount) {\n answers += source.readResourceRecord() ?: continue\n }\n\n val authorityRecords = ArrayList(authorityRecordCount)\n for (i in 0 until authorityRecordCount) {\n authorityRecords += source.readResourceRecord() ?: continue\n }\n\n val additionalRecords = ArrayList(additionalRecordCount)\n for (i in 0 until additionalRecordCount) {\n additionalRecords += source.readResourceRecord() ?: continue\n }\n\n if (!source.exhausted()) {\n throw ProtocolException(\"unexpected trailing data in message\")\n }\n\n sourceOffsetZero.skipAll()\n\n return DnsMessage(\n id = id,\n fl"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageReader.kt","line":94,"symbol":"readQuestion","kind":"function","lang":"kotlin","code":"private fun BufferedSource.readQuestion(): Question {\n val name = readName()\n val type = readShort().toInt()\n val `class` = readShort().toInt()\n return Question(\n name = name,\n type = type,\n `class` = `class`,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageReader.kt","line":105,"symbol":"readName","kind":"function","lang":"kotlin","code":"private fun BufferedSource.readName(): String {\n val result = Buffer()\n readName(result)\n return result.readUtf8()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageReader.kt","line":111,"symbol":"readName","kind":"function","lang":"kotlin","code":"private tailrec fun BufferedSource.readName(\n sink: Buffer,\n maxOffset: Int = Int.MAX_VALUE,\n ) {\n while (true) {\n val labelTypeAndLength = readUByte().toInt()\n val labelType = labelTypeAndLength and 0b11000000\n val labelLength = labelTypeAndLength and 0b00111111\n when (labelType) {\n // Inline value.\n 0b00_000000 -> {\n if (labelLength == 0) return\n if (sink.size > 0L) sink.writeByte('.'.code)\n sink.write(this, labelLength.toLong())\n }\n\n // Compressed suffix.\n 0b11_000000 -> {\n val offset = (labelLength shl 8) or readUByte().toInt()\n\n // Pointers may only refer to prior occurrences.\n if (offset >= maxOffset) {\n throw ProtocolException(\"malformed DNS message\")\n }\n\n val offsetSource = sourceOffsetZero.peek()\n offsetSource.skip(offset.toLong())\n return offsetSource.readName(sink, maxOffset = offset)\n }\n\n 0b01_000000, 0b10_000000 -> {\n throw ProtocolException(\"unsupported label type\")\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageReader.kt","line":149,"symbol":"readResourceRecord","kind":"function","lang":"kotlin","doc":"Returns null if this record type is unsupported.","code":"fun BufferedSource.readResourceRecord(): ResourceRecord? {\n val name = readName()\n val type = readShort().toInt()\n val `class` = readShort().toInt()\n val timeToLive = readInt()\n val recordDataLength = readUShort().toLong()\n\n when {\n `class` == CLASS_IN && type == TYPE_A -> {\n if (recordDataLength != 4L) throw ProtocolException(\"unexpected record length\")\n val address = InetAddress.getByAddress(readByteArray(4L))\n return ResourceRecord.IpAddress(\n name = name,\n timeToLive = timeToLive,\n address = address,\n )\n }\n\n `class` == CLASS_IN && type == TYPE_AAAA -> {\n if (recordDataLength != 16L) throw ProtocolException(\"unexpected record length\")\n val address = InetAddress.getByAddress(readByteArray(16L))\n return ResourceRecord.IpAddress(\n name = name,\n timeToLive = timeToLive,\n address = address,\n )\n }\n\n `class` == CLASS_IN && type == TYPE_HTTPS -> {\n return limit(recordDataLength)\n .buffer()\n .readHttpsResourceRecord(name, timeToLive)\n }\n\n else -> {\n skip(recordDataLength)\n return null\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageReader.kt","line":191,"symbol":"readHttpsResourceRecord","kind":"function","lang":"kotlin","doc":"https://datatracker.ietf.org/doc/rfc9460/","code":"private fun BufferedSource.readHttpsResourceRecord(\n name: String,\n timeToLive: Int,\n ): ResourceRecord.Https {\n val svcPriority = readUShort()\n val targetName = readName()\n var lastKey = -1\n var alpnIds: MutableList? = null\n var noDefaultAlpn = false\n var port = 443\n var ipAddressHints: MutableList? = null\n var echConfigList: ByteString? = null\n\n while (!exhausted()) {\n val key = readUShort().toInt()\n if (key <= lastKey) throw ProtocolException(\"malformed HTTPS resource record\")\n lastKey = key\n val valueLength = readUShort().toLong()\n when (key) {\n SERVICE_PARAMETER_MANDATORY -> {\n if (valueLength % 2 != 0L) throw ProtocolException(\"malformed HTTPS / mandatory\")\n for (i in 0 until valueLength step 2) {\n val serviceParameterKey = readUShort().toInt()\n if (serviceParameterKey !in SERVICE_PARAMETER_MANDATORY..SERVICE_PARAMETER_IPV6_HINT) {\n throw ProtocolException(\"unsupported HTTPS mandatory parameter $serviceParameterKey\")\n }\n }\n }\n\n SERVICE_PARAMETER_ALPN -> {\n alpnIds = mutableListOf()\n var "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageWriter.kt","line":34,"symbol":"DnsMessageWriter","kind":"class","lang":"kotlin","doc":"Encode DNS messages. https://datatracker.ietf.org/doc/html/rfc1035","code":"@OkHttpInternalApi\nclass DnsMessageWriter(\n private val sink: Buffer,\n) {\n /**\n * When compressing name labels, this is the offset into [sink] of the label.\n *\n * Because we write [ResourceRecord.Https] values to an intermediate buffer, the overall offset\n * must be predicted when putting in this map.\n */\n private val labelToOffset = mutableMapOf()\n private val messageStart = sink.size\n\n fun write(message: DnsMessage) {\n sink.writeShort(message.id.toInt())\n sink.writeShort(message.flags)\n sink.writeShort(message.questions.size)\n sink.writeShort(message.answers.size)\n sink.writeShort(message.authorityRecords.size)\n sink.writeShort(message.additionalRecords.size)\n\n for (question in message.questions) {\n writeQuestion(question)\n }\n for (resourceRecord in message.answers) {\n writeResourceRecord(resourceRecord)\n }\n for (resourceRecord in message.authorityRecords) {\n writeResourceRecord(resourceRecord)\n }\n for (resourceRecord in message.additionalRecords) {\n writeResourceRecord(resourceRecord)\n }\n }\n\n private fun writeQuestion(question: Question) {\n sink.writeName(question.name.encodeUtf8("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageWriter.kt","line":47,"symbol":"write","kind":"function","lang":"kotlin","code":"fun write(message: DnsMessage) {\n sink.writeShort(message.id.toInt())\n sink.writeShort(message.flags)\n sink.writeShort(message.questions.size)\n sink.writeShort(message.answers.size)\n sink.writeShort(message.authorityRecords.size)\n sink.writeShort(message.additionalRecords.size)\n\n for (question in message.questions) {\n writeQuestion(question)\n }\n for (resourceRecord in message.answers) {\n writeResourceRecord(resourceRecord)\n }\n for (resourceRecord in message.authorityRecords) {\n writeResourceRecord(resourceRecord)\n }\n for (resourceRecord in message.additionalRecords) {\n writeResourceRecord(resourceRecord)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageWriter.kt","line":69,"symbol":"writeQuestion","kind":"function","lang":"kotlin","code":"private fun writeQuestion(question: Question) {\n sink.writeName(question.name.encodeUtf8())\n sink.writeShort(question.type.toInt())\n sink.writeShort(question.`class`.toInt())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageWriter.kt","line":75,"symbol":"writeName","kind":"function","lang":"kotlin","code":"private tailrec fun Buffer.writeName(\n name: ByteString,\n receiverOffset: Long = 0L,\n ) {\n // Write an empty name.\n if (name.size == 0) {\n writeByte(0)\n return\n }\n\n // Write a back reference to a previous name.\n val compressedAt = labelToOffset[name]\n if (compressedAt != null) {\n writeShort(compressedAt.toInt() or 0b1100_0000_0000_0000)\n return\n }\n\n // We're about to write a new name. Remember its offset for future compression.\n labelToOffset[name] = receiverOffset + size - messageStart\n\n // This is the last label. Write it followed by an empty string.\n val dot = name.indexOf(LABEL_SEPARATOR)\n if (dot == -1) {\n check(name.size < 64) { \"label too long\" }\n writeByte(name.size)\n write(name)\n writeByte(0)\n return\n }\n\n // Write one label, then recurse.\n check(dot < 64) { \"label too long\" }\n writeByte(dot)\n write(name, offset = 0, byteCount = dot)\n writeName(name.substring(dot + 1), receiverOffset)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageWriter.kt","line":112,"symbol":"writeResourceRecord","kind":"function","lang":"kotlin","code":"private fun writeResourceRecord(resourceRecord: ResourceRecord) {\n when (resourceRecord) {\n is ResourceRecord.Https -> writeHttps(resourceRecord)\n is ResourceRecord.IpAddress -> writeIpAddress(resourceRecord)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageWriter.kt","line":119,"symbol":"writeIpAddress","kind":"function","lang":"kotlin","code":"private fun writeIpAddress(record: ResourceRecord.IpAddress) {\n val address = record.address.address\n sink.writeName(record.name.encodeUtf8())\n sink.writeShort(\n when (address.size) {\n 4 -> TYPE_A\n 16 -> TYPE_AAAA\n else -> error(\"unexpected address\")\n },\n )\n sink.writeShort(CLASS_IN)\n sink.writeInt(record.timeToLive)\n sink.writeShort(address.size)\n sink.write(address)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-DnsMessageWriter.kt","line":136,"symbol":"writeHttps","kind":"function","lang":"kotlin","doc":"https://datatracker.ietf.org/doc/rfc9460/","code":"private fun writeHttps(record: ResourceRecord.Https) {\n sink.writeName(record.name.encodeUtf8())\n sink.writeShort(TYPE_HTTPS)\n sink.writeShort(CLASS_IN)\n sink.writeInt(record.timeToLive)\n\n val content = Buffer()\n content.writeShort(record.priority)\n content.writeName(\n name = record.targetName.encodeUtf8(),\n receiverOffset = sink.size + 2,\n )\n\n if (record.alpnIds != null) {\n content.writeShort(SERVICE_PARAMETER_ALPN)\n val nonDefaultAlpnIds = record.alpnIds.filter { it != Protocol.HTTP_1_1.toString() }\n content.writeShort(nonDefaultAlpnIds.sumOf { 1 + it.utf8Size() }.toInt())\n for (alpnId in nonDefaultAlpnIds) {\n content.writeByte(alpnId.utf8Size().toInt())\n content.writeUtf8(alpnId)\n }\n if (Protocol.HTTP_1_1.toString() !in record.alpnIds) {\n content.writeShort(SERVICE_PARAMETER_NO_DEFAULT_ALPN)\n content.writeShort(0)\n }\n }\n\n if (record.port != 443) {\n content.writeShort(SERVICE_PARAMETER_PORT)\n content.writeShort(2)\n content.writeShort(record.port)\n }\n\n val ipv4Hints = record.ipAddressHints.filterIsInstance()\n if (ipv4Hints.isNotEmpty()) {\n"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-ExecuteDns.kt","line":35,"symbol":"Call","kind":"function","lang":"kotlin","doc":"This returns normally if at least one [Dns.Record.IpAddress] is returned. Partial failures are silently ignored. This is intended to be transitional only; doing it this way needlessly blocks the caller's thread.","code":"@OkHttpInternalApi\n@Throws(UnknownHostException::class)\nfun Dns.Call.execute(): List {\n val queue = LinkedBlockingQueue>>()\n\n enqueue(\n object : Dns.Callback {\n val allRecords = mutableListOf()\n\n override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n allRecords += records\n if (last) {\n complete()\n }\n }\n\n override fun onFailure(\n call: Dns.Call,\n e: IOException,\n ) {\n complete(e)\n }\n\n private fun complete(e: IOException? = null) {\n val result =\n when {\n allRecords.any { it is Dns.Record.IpAddress } -> {\n Result.success(allRecords)\n }\n\n else -> {\n Result.failure(\n e ?: UnknownHostException(\"DNS returned no addresses for ${request.hostname}\"),\n )\n }\n }\n queue.put(result)\n }\n },\n )\n\n return queue.take().getOrThrow()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-ExecuteDns.kt","line":44,"symbol":"onRecords","kind":"function","lang":"kotlin","code":"override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n allRecords += records\n if (last) {\n complete()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-ExecuteDns.kt","line":55,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Dns.Call,\n e: IOException,\n ) {\n complete(e)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-ExecuteDns.kt","line":62,"symbol":"complete","kind":"function","lang":"kotlin","code":"private fun complete(e: IOException? = null) {\n val result =\n when {\n allRecords.any { it is Dns.Record.IpAddress } -> {\n Result.success(allRecords)\n }\n\n else -> {\n Result.failure(\n e ?: UnknownHostException(\"DNS returned no addresses for ${request.hostname}\"),\n )\n }\n }\n queue.put(result)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":55,"symbol":"StateMachineDnsCall","kind":"class","lang":"kotlin","doc":"The potentially surprising outcome of this strategy is the thread that performed the `TYPE_AAAA` DNS request may also deliver the `TYPE_A` records to the callback, or vice versa. If a thread is intending to call the callback, it sets [State.Running.lockHeld] to true while that call is executing.","code":"@OkHttpInternalApi\nclass StateMachineDnsCall(\n private val taskRunner: TaskRunner,\n override val request: Dns.Request,\n private val queryFactory: DnsQuery.Factory,\n private val includeIPv6: Boolean,\n private val includeServiceMetadata: Boolean,\n) : Dns.Call {\n private val state = AtomicReference(State.Idle())\n\n override fun isCanceled() = state.get().canceled\n\n override fun enqueue(callback: Dns.Callback) {\n val questions =\n buildList {\n if (includeServiceMetadata) {\n // If this query doesn't use the default port, we need to put that into the query name\n // using Attrleaf syntax. See RFC 9460 section 2.3.\n add(\n Question(\n name =\n when (request.port) {\n 443 -> request.hostname\n else -> \"_${request.port}._https.${request.hostname}\"\n },\n type = TYPE_HTTPS,\n ),\n )\n }\n if (includeIPv6) {\n add(Question(request.hostname, TYPE_AAAA))\n }\n add(Question(request.hostname, TYPE_A))\n }\n\n while (true) {\n val previous =\n state.get() as? State.Idle\n ?: error"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":65,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"override fun isCanceled() = state.get().canceled"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":67,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(callback: Dns.Callback) {\n val questions =\n buildList {\n if (includeServiceMetadata) {\n // If this query doesn't use the default port, we need to put that into the query name\n // using Attrleaf syntax. See RFC 9460 section 2.3.\n add(\n Question(\n name =\n when (request.port) {\n 443 -> request.hostname\n else -> \"_${request.port}._https.${request.hostname}\"\n },\n type = TYPE_HTTPS,\n ),\n )\n }\n if (includeIPv6) {\n add(Question(request.hostname, TYPE_AAAA))\n }\n add(Question(request.hostname, TYPE_A))\n }\n\n while (true) {\n val previous =\n state.get() as? State.Idle\n ?: error(\"already enqueued\")\n\n // If it's canceled before it is enqueued, jump straight to Complete.\n if (previous.canceled) {\n val next = State.Complete(canceled = true)\n\n if (!state.compareAndSet(previous, next)) continue // Lost a race, retry.\n\n taskRunner.newQueue().execute(\"${request.hostname} dns\") {\n callback.onFailure(this, IOException(\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":126,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(dnsResponse: DnsMessage) {\n updateStateAndCallCallbacks(\n question = question,\n completedQuery = query,\n dnsResponse = dnsResponse,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":134,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(e: IOException) {\n updateStateAndCallCallbacks(\n completedQuery = query,\n newException = e,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":148,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n while (true) {\n val previous = state.get()\n val next = previous.cancel()\n if (!state.compareAndSet(previous, next)) continue // Lost a race, retry.\n\n if (previous is State.Running) {\n for (query in previous.runningQueries) {\n query.cancel()\n }\n }\n return\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":163,"symbol":"updateStateAndCallCallbacks","kind":"function","lang":"kotlin","code":"private fun updateStateAndCallCallbacks(\n question: Question,\n completedQuery: DnsQuery,\n dnsResponse: DnsMessage,\n ) {\n val resourceRecords =\n try {\n when (dnsResponse.responseCode) {\n RESPONSE_CODE_SUCCESS -> dnsResponse.answers\n RESPONSE_CODE_SERVER_FAILURE -> throw UnknownHostException(\"DNS server failure\")\n else -> throw UnknownHostException()\n }\n } catch (e: IOException) {\n return updateStateAndCallCallbacks(\n completedQuery = completedQuery,\n newException = e,\n )\n }\n\n val dnsRecords: List =\n when (question.type) {\n TYPE_HTTPS -> {\n resourceRecords\n .filterIsInstance()\n .shuffled()\n .sortedBy { it.priority }\n .map { resourceRecord ->\n // OkHttp doesn't yet implement AliasMode resource records. If any AliasMode record is\n // returned, we must ignore ALL returned resource records.\n if (resourceRecord.priority == 0) {\n return updateStateAndCallCallbacks(\n completedQuery = completedQuery,\n )\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":237,"symbol":"updateStateAndCallCallbacks","kind":"function","lang":"kotlin","code":"private tailrec fun updateStateAndCallCallbacks(\n completedQuery: DnsQuery? = null,\n newRecords: List = listOf(),\n newException: IOException? = null,\n lockHeldByThisThread: Boolean = false,\n ) {\n while (true) {\n val previous =\n state.get() as? State.Running\n ?: return // Already complete or canceled; nothing to do.\n\n val newRunningQueries =\n when {\n completedQuery != null -> previous.runningQueries - completedQuery\n else -> previous.runningQueries\n }\n\n val allExceptions =\n when {\n newException != null -> previous.pendingExceptions + newException\n else -> previous.pendingExceptions\n }\n\n val allRecords =\n when {\n newRecords.isNotEmpty() -> previous.pendingRecords + newRecords\n else -> previous.pendingRecords\n }\n\n val last = newRunningQueries.isEmpty()\n val lockHeldByAnotherThread = !lockHeldByThisThread && previous.lockHeld\n\n // There's a few reasons why we might not call any callbacks:\n // - There's no more records or failures to emit immediately\n // - Another thread is already calling the callbacks"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":331,"symbol":"State","kind":"interface","lang":"kotlin","code":"private sealed interface State {\n val canceled: Boolean\n\n class Idle(\n override val canceled: Boolean = false,\n ) : State {\n override fun cancel() = Idle(canceled = true)\n }\n\n class Running(\n override val canceled: Boolean,\n val callback: Dns.Callback,\n val lockHeld: Boolean = false,\n val runningQueries: List,\n val pendingRecords: List = listOf(),\n val pendingExceptions: List = listOf(),\n ) : State {\n init {\n check(pendingRecords.isEmpty() || lockHeld)\n }\n\n override fun cancel() =\n Running(\n canceled = true,\n callback = callback,\n lockHeld = lockHeld,\n runningQueries = runningQueries,\n pendingRecords = pendingRecords,\n pendingExceptions = pendingExceptions,\n )\n }\n\n class Complete(\n override val canceled: Boolean,\n ) : State {\n override fun cancel() = Idle(canceled = true)\n }\n\n fun cancel(): State\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":334,"symbol":"Idle","kind":"class","lang":"kotlin","code":"class Idle(\n override val canceled: Boolean = false,\n ) : State {\n override fun cancel() = Idle(canceled = true)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":337,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() = Idle(canceled = true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":340,"symbol":"Running","kind":"class","lang":"kotlin","code":"class Running(\n override val canceled: Boolean,\n val callback: Dns.Callback,\n val lockHeld: Boolean = false,\n val runningQueries: List,\n val pendingRecords: List = listOf(),\n val pendingExceptions: List = listOf(),\n ) : State {\n init {\n check(pendingRecords.isEmpty() || lockHeld)\n }\n\n override fun cancel() =\n Running(\n canceled = true,\n callback = callback,\n lockHeld = lockHeld,\n runningQueries = runningQueries,\n pendingRecords = pendingRecords,\n pendingExceptions = pendingExceptions,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":352,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() =\n Running(\n canceled = true,\n callback = callback,\n lockHeld = lockHeld,\n runningQueries = runningQueries,\n pendingRecords = pendingRecords,\n pendingExceptions = pendingExceptions,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":363,"symbol":"Complete","kind":"class","lang":"kotlin","code":"class Complete(\n override val canceled: Boolean,\n ) : State {\n override fun cancel() = Idle(canceled = true)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":366,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() = Idle(canceled = true)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":369,"symbol":"cancel","kind":"function","lang":"kotlin","code":"fun cancel(): State"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/-StateMachineDnsCall.kt","line":373,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"internal fun Dns.Callback.onFailure(\n call: Dns.Call,\n exceptions: List,\n) {\n val firstException = exceptions.first()\n for (i in 1 until exceptions.size) {\n firstException.addSuppressed(exceptions[i])\n }\n\n onFailure(call, firstException)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/DnsQuery.kt","line":28,"symbol":"DnsQuery","kind":"interface","lang":"kotlin","doc":"A transport-layer DNS query for a single record type. This is different from `Dns.Call` which returns multiple record types.","code":"@OkHttpInternalApi\ninterface DnsQuery {\n fun enqueue(callback: Callback)\n\n fun cancel()\n\n interface Callback {\n fun onFailure(e: IOException)\n\n fun onResponse(dnsResponse: DnsMessage)\n }\n\n fun interface Factory {\n fun newQuery(question: Question): DnsQuery\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/DnsQuery.kt","line":30,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"fun enqueue(callback: Callback)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/DnsQuery.kt","line":32,"symbol":"cancel","kind":"function","lang":"kotlin","code":"fun cancel()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/DnsQuery.kt","line":34,"symbol":"Callback","kind":"interface","lang":"kotlin","code":"interface Callback {\n fun onFailure(e: IOException)\n\n fun onResponse(dnsResponse: DnsMessage)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/DnsQuery.kt","line":35,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"fun onFailure(e: IOException)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/DnsQuery.kt","line":37,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"fun onResponse(dnsResponse: DnsMessage)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/DnsQuery.kt","line":40,"symbol":"Factory","kind":"interface","lang":"kotlin","code":"fun interface Factory {\n fun newQuery(question: Question): DnsQuery\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/DnsQuery.kt","line":41,"symbol":"newQuery","kind":"function","lang":"kotlin","code":"fun newQuery(question: Question): DnsQuery"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/InetAddressDns.kt","line":27,"symbol":"InetAddressDns","kind":"object","lang":"kotlin","doc":"A DNS that uses [InetAddress.getAllByName] to ask the underlying operating system to lookup IP addresses.","code":"@OkHttpInternalApi\ninternal object InetAddressDns : Dns {\n override fun lookup(hostname: String): List {\n try {\n return InetAddress.getAllByName(hostname).toList()\n } catch (e: NullPointerException) {\n throw UnknownHostException(\"Broken system behaviour for dns lookup of $hostname\").apply {\n initCause(e)\n }\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/InetAddressDns.kt","line":29,"symbol":"lookup","kind":"function","lang":"kotlin","code":"override fun lookup(hostname: String): List {\n try {\n return InetAddress.getAllByName(hostname).toList()\n } catch (e: NullPointerException) {\n throw UnknownHostException(\"Broken system behaviour for dns lookup of $hostname\").apply {\n initCause(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":36,"symbol":"LookupDnsCall","kind":"class","lang":"kotlin","doc":"Adapts the blocking [Dns.lookup] function (introduced in 2015) to the non-blocking [Dns.newCall] API (introduced in 2026), using [TaskRunner] to provide a thread for background execution. When canceled, the callback is immediately notified but the in-flight call is run to completion and discarded.","code":"@OkHttpInternalApi\nclass LookupDnsCall(\n private val taskRunner: TaskRunner,\n private val delegate: Dns,\n override val request: Dns.Request,\n) : Task(\"${request.hostname} dns\", cancelable = false),\n Dns.Call {\n private val state = AtomicReference(State.Idle)\n\n override fun enqueue(callback: Dns.Callback) {\n val previous = state.testAndSet(State.Running(callback)) { it is State.Idle }\n when (previous) {\n is State.Idle -> taskRunner.newQueue().schedule(this)\n is State.Running, State.Complete -> throw IllegalStateException(\"already enqueued\")\n State.Canceled -> callback.onFailure(this, IOException(\"canceled\"))\n }\n }\n\n override fun cancel() {\n val previous = state.testAndSet(State.Canceled) { it is State.Running || it == State.Idle }\n (previous as? State.Running)?.callback?.onFailure(this, IOException(\"canceled\"))\n }\n\n override fun isCanceled() = state.get() is State.Canceled\n\n override fun runOnce(): Long {\n try {\n val inetAddresses = delegate.lookup(request.hostname)\n val previous = state.testAndSet(State.Complete) { it is State.Running }\n (previous as? State.Running)?.callback?.onRecords(\n call = this,\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":45,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(callback: Dns.Callback) {\n val previous = state.testAndSet(State.Running(callback)) { it is State.Idle }\n when (previous) {\n is State.Idle -> taskRunner.newQueue().schedule(this)\n is State.Running, State.Complete -> throw IllegalStateException(\"already enqueued\")\n State.Canceled -> callback.onFailure(this, IOException(\"canceled\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":54,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n val previous = state.testAndSet(State.Canceled) { it is State.Running || it == State.Idle }\n (previous as? State.Running)?.callback?.onFailure(this, IOException(\"canceled\"))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":59,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"override fun isCanceled() = state.get() is State.Canceled"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":61,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n try {\n val inetAddresses = delegate.lookup(request.hostname)\n val previous = state.testAndSet(State.Complete) { it is State.Running }\n (previous as? State.Running)?.callback?.onRecords(\n call = this,\n last = true,\n records = inetAddresses.map { Dns.Record.IpAddress(request.hostname, it) },\n )\n } catch (e: UnknownHostException) {\n val previous = state.testAndSet(State.Complete) { it is State.Running }\n (previous as? State.Running)?.callback?.onFailure(\n call = this,\n e = e,\n )\n }\n return -1L\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":80,"symbol":"State","kind":"interface","lang":"kotlin","code":"private sealed interface State {\n object Idle : State\n\n class Running(\n val callback: Dns.Callback,\n ) : State\n\n object Complete : State\n\n object Canceled : State\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":81,"symbol":"Idle","kind":"object","lang":"kotlin","code":"object Idle : State"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":87,"symbol":"Complete","kind":"object","lang":"kotlin","code":"object Complete : State"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/LookupDnsCall.kt","line":89,"symbol":"Canceled","kind":"object","lang":"kotlin","code":"object Canceled : State"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/MemoryCache.kt","line":31,"symbol":"MemoryCache","kind":"class","lang":"kotlin","doc":"has twice as many entries. This retains entries in least-recently-used order. This evicts in big batches because each eviction must traverse the entire cache.","code":"abstract class MemoryCache(\n val timeSource: TimeSource.WithComparableMarks,\n val maxSize: Int,\n) {\n val size: Int\n get() = entries.size\n\n private val entries = ConcurrentHashMap()\n\n init {\n require(maxSize >= 0)\n }\n\n /**\n * Returns the time this value was most recently used, in order to make an eviction decision. This\n * should return null if this element should be evicted immediately.\n */\n protected abstract fun lastRequestedAt(\n now: Time,\n value: V,\n ): Time?\n\n /**\n * Similar to [ConcurrentHashMap.computeIfAbsent], but this will also prune the cache to size if\n * this function grows the cache to double [maxSize].\n */\n fun computeIfAbsent(\n key: K,\n computeValue: () -> V,\n ): V {\n if (maxSize == 0) return computeValue()\n\n val result = entries[key]\n if (result != null) return result\n\n val created = computeValue()\n val existing = entries.putIfAbsent(key, created)\n if (existing != null) return existing\n\n // If there's more than 2x as many entries as the max, automatically evict.\n val toEvict = entries.size - maxSize\n if (toEvict >= maxSize) {\n evict(toEvict)\n }\n\n return created\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/MemoryCache.kt","line":48,"symbol":"lastRequestedAt","kind":"function","lang":"kotlin","doc":"Returns the time this value was most recently used, in order to make an eviction decision. This should return null if this element should be evicted immediately.","code":"protected abstract fun lastRequestedAt(\n now: Time,\n value: V,\n ): Time?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/MemoryCache.kt","line":57,"symbol":"computeIfAbsent","kind":"function","lang":"kotlin","doc":"Similar to [ConcurrentHashMap.computeIfAbsent], but this will also prune the cache to size if this function grows the cache to double [maxSize].","code":"fun computeIfAbsent(\n key: K,\n computeValue: () -> V,\n ): V {\n if (maxSize == 0) return computeValue()\n\n val result = entries[key]\n if (result != null) return result\n\n val created = computeValue()\n val existing = entries.putIfAbsent(key, created)\n if (existing != null) return existing\n\n // If there's more than 2x as many entries as the max, automatically evict.\n val toEvict = entries.size - maxSize\n if (toEvict >= maxSize) {\n evict(toEvict)\n }\n\n return created\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/MemoryCache.kt","line":79,"symbol":"evictAll","kind":"function","lang":"kotlin","code":"fun evictAll() {\n entries.clear()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/MemoryCache.kt","line":92,"symbol":"evict","kind":"function","lang":"kotlin","doc":"If the cache is smaller than [count], this evicts everything. Entries that are expired are evicted unconditionally, even if this causes more than [count] entries to be evicted. If [count] or more expired entries are evicted, non-expired entries will not be evicted.","code":"fun evict(count: Int) {\n // Note that we call lastRequestedAt() exactly once for each entry. If we called it on-demand in\n // the comparator, we'd break the PriorityQueue's invariant that the sort order is stable.\n var count = count\n val now = timeSource.markNow()\n val entriesToEvict = PriorityQueue>>(count + 1, NewestFirst)\n val i = entries.entries.iterator()\n while (i.hasNext()) {\n val entry = i.next()\n\n when (val lastRequestedAt = lastRequestedAt(now, entry.value)) {\n // It's expired, evict unconditionally.\n null -> {\n i.remove()\n count--\n }\n\n // It's not expired. Make it a candidate for eviction.\n else -> {\n entriesToEvict.add(lastRequestedAt to entry)\n }\n }\n\n // If we're above our target eviction count, save the newest entry from eviction.\n if (entriesToEvict.size > count) {\n entriesToEvict.poll()\n }\n }\n\n for ((_, entry) in entriesToEvict) {\n entries.remove(entry.key, entry.value)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/MemoryCache.kt","line":126,"symbol":"NewestFirst","kind":"object","lang":"kotlin","code":"private object NewestFirst : Comparator> {\n override fun compare(\n o1: Pair,\n o2: Pair,\n ) = o2.first.compareTo(o1.first)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/MemoryCache.kt","line":127,"symbol":"compare","kind":"function","lang":"kotlin","code":"override fun compare(\n o1: Pair,\n o2: Pair,\n ) = o2.first.compareTo(o1.first)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":31,"symbol":"RealDnsCache","kind":"class","lang":"kotlin","code":"@OkHttpInternalApi\n@OptIn(ExperimentalTime::class) // We know Clock and Instant will be stable in Kotlin 2.3.\nclass RealDnsCache(\n private val taskRunner: TaskRunner,\n timeSource: TimeSource.WithComparableMarks,\n internal val minimumTimeToLive: Duration,\n internal val maximumTimeToLive: Duration,\n internal val failureTimeToLive: Duration,\n internal val revalidateBeforeExpire: Duration,\n maxEntryCount: Int,\n) {\n private val cache =\n object : MemoryCache(\n timeSource = timeSource,\n maxSize = maxEntryCount,\n ) {\n override fun lastRequestedAt(\n now: Time,\n value: Entry,\n ): Time? {\n val state = value.state.get()\n\n // If it's already expired, evict immediately.\n if (state.inFlightCall == null) {\n val expireAt = state.result?.expireAt ?: return null\n if (expireAt <= now) return null\n }\n\n return state.lastRequestedAt\n }\n }\n\n private val atomicNetworkCount = AtomicInteger()\n private val atomicHitCount = AtomicInteger()\n private val atomicRequestCount = AtomicInteger()\n\n internal val size: Int\n get() = cache.size\n internal val maxSize: Int\n get() = cache.m"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":47,"symbol":"lastRequestedAt","kind":"function","lang":"kotlin","code":"override fun lastRequestedAt(\n now: Time,\n value: Entry,\n ): Time? {\n val state = value.state.get()\n\n // If it's already expired, evict immediately.\n if (state.inFlightCall == null) {\n val expireAt = state.result?.expireAt ?: return null\n if (expireAt <= now) return null\n }\n\n return state.lastRequestedAt\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":85,"symbol":"evictAll","kind":"function","lang":"kotlin","code":"fun evictAll() {\n cache.evictAll()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":89,"symbol":"wrap","kind":"function","lang":"kotlin","code":"fun wrap(delegate: DnsQuery.Factory) =\n DnsQuery.Factory { question ->\n val entry = cache.computeIfAbsent(question) { Entry() }\n CacheQuery(question, delegate, entry)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":99,"symbol":"CacheQuery","kind":"class","lang":"kotlin","doc":"An application-layer DNS query that is served by cached data in [entry] or by a new call to the underlying transport via [delegate]. If a new call is made, its result is stored in [entry].","code":"private inner class CacheQuery(\n val question: Question,\n val delegate: DnsQuery.Factory,\n val entry: Entry,\n ) : DnsQuery,\n DnsQuery.Callback {\n var callback: DnsQuery.Callback? = null\n\n override fun enqueue(callback: DnsQuery.Callback) {\n check(this.callback == null) { \"already enqueued\" }\n this.callback = callback\n\n val now = cache.timeSource.markNow()\n while (true) {\n val previous = entry.state.get()\n val result = previous.result\n val inFlightCall = previous.inFlightCall\n\n // We use a cached value unless it's expired.\n val useCached = result != null && now < result.expireAt\n\n // Revalidate the cache if necessary. Note that we might revalidate the cache without any\n // particular callback waiting for that response.\n val next =\n previous.copy(\n lastRequestedAt = now,\n inFlightCall =\n when {\n inFlightCall != null && useCached -> {\n inFlightCall\n }\n\n inFlightCall != null -> {\n inFlightCall.copy(queries = inFlightCall.queries + this)\n }\n\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":107,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(callback: DnsQuery.Callback) {\n check(this.callback == null) { \"already enqueued\" }\n this.callback = callback\n\n val now = cache.timeSource.markNow()\n while (true) {\n val previous = entry.state.get()\n val result = previous.result\n val inFlightCall = previous.inFlightCall\n\n // We use a cached value unless it's expired.\n val useCached = result != null && now < result.expireAt\n\n // Revalidate the cache if necessary. Note that we might revalidate the cache without any\n // particular callback waiting for that response.\n val next =\n previous.copy(\n lastRequestedAt = now,\n inFlightCall =\n when {\n inFlightCall != null && useCached -> {\n inFlightCall\n }\n\n inFlightCall != null -> {\n inFlightCall.copy(queries = inFlightCall.queries + this)\n }\n\n result == null || now >= result.revalidateAt -> {\n InFlightCall(\n query = delegate.newQuery(question),\n sentAt = now,\n queries = if ("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":176,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"Note that we don't cancel the query even if nothing is waiting on it. We assume there's still value in updating the cache!","code":"override fun cancel() {\n while (true) {\n val previous = entry.state.get()\n val inFlightCall = previous.inFlightCall ?: return\n\n // If we've already called the callback, there's nothing to do.\n val newQueries = inFlightCall.queries - this\n if (newQueries.size == inFlightCall.queries.size) return\n\n val next =\n previous.copy(\n inFlightCall =\n inFlightCall.copy(\n queries = newQueries,\n ),\n )\n\n if (!entry.state.compareAndSet(previous, next)) continue // Lost a race, retry.\n\n taskRunner.newQueue().execute(\"${question.name} dns\") {\n callback!!.onFailure(IOException(\"canceled\"))\n }\n\n return\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":203,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(dnsResponse: DnsMessage) {\n while (true) {\n val previous = entry.state.get()\n val sentAt = previous.inFlightCall!!.sentAt\n val timeToLive =\n when {\n dnsResponse.answers.isEmpty() -> {\n failureTimeToLive\n }\n\n else -> {\n dnsResponse.answers\n .minOf { it.timeToLive }\n .seconds\n .coerceIn(minimumTimeToLive, maximumTimeToLive)\n }\n }\n val revalidateDelay = (timeToLive - revalidateBeforeExpire).coerceAtLeast(0.seconds)\n\n val next =\n previous.copy(\n inFlightCall = null,\n result =\n Result.Success(\n message = dnsResponse,\n revalidateAt = sentAt + revalidateDelay,\n expireAt = sentAt + timeToLive,\n ),\n )\n\n if (!entry.state.compareAndSet(previous, next)) continue // Lost a race, retry.\n\n val queries = previous.inFlightCall.queries\n for (query in queries) {\n query.callback!!.onResponse(dnsResponse)\n }\n\n return\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":244,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(e: IOException) {\n while (true) {\n val previous = entry.state.get()\n val sentAt = previous.inFlightCall!!.sentAt\n val revalidateDelay = (failureTimeToLive - revalidateBeforeExpire).coerceAtLeast(0.seconds)\n\n val next =\n previous.copy(\n inFlightCall = null,\n result =\n Result.Failure(\n exception = e,\n revalidateAt = sentAt + revalidateDelay,\n expireAt = sentAt + failureTimeToLive,\n ),\n )\n\n if (!entry.state.compareAndSet(previous, next)) continue // Lost a race, retry.\n\n val queries = previous.inFlightCall.queries\n for (query in queries) {\n query.callback!!.onFailure(e)\n }\n\n return\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":273,"symbol":"Entry","kind":"class","lang":"kotlin","code":"private class Entry {\n val state = AtomicReference(State())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/dns/RealDnsCache.kt","line":293,"symbol":"Result","kind":"interface","lang":"kotlin","doc":"A cached result.","code":"private sealed interface Result {\n val revalidateAt: Time\n val expireAt: Time\n\n class Failure(\n override val revalidateAt: Time,\n override val expireAt: Time,\n val exception: IOException,\n ) : Result\n\n class Success(\n override val revalidateAt: Time,\n override val expireAt: Time,\n val message: DnsMessage,\n ) : Result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ech/EchRetryPlan.kt","line":34,"symbol":"EchRetryPlan","kind":"class","lang":"kotlin","doc":"The [configList] comes from the server that couldn't successfully handshake with ECH. It will be null if the server has directed us to securely disable ECH. See RFC 9849, section 6.1.6.","code":"@OkHttpInternalApi\nclass EchRetryPlan private constructor(\n /** The client-facing server's name from `ECHConfig.contents.public_name`. */\n val publicName: String,\n /** The ECH config list to retry with, or null to retry without ECH. */\n val configList: ByteString?,\n) {\n companion object {\n private val INVALID_PUBLIC_NAME =\n \"(\\\\..*)|(.*\\\\.)|((.*\\\\.)?[0-9]+)|((.*\\\\.)?0[xX][0-9a-fA-F]*)\".toRegex()\n\n /** Returns a new config if the inputs are valid, and null otherwise. */\n fun getOrNull(\n publicName: String,\n configList: ByteString?,\n ): EchRetryPlan? {\n val canonicalHost = publicName.toCanonicalHost() ?: return null\n if (canonicalHost.canParseAsIpAddress()) return null\n if (INVALID_PUBLIC_NAME.matches(canonicalHost)) return null\n return EchRetryPlan(\n publicName,\n configList,\n )\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ech/EchRetryPlan.kt","line":46,"symbol":"getOrNull","kind":"function","lang":"kotlin","doc":"Returns a new config if the inputs are valid, and null otherwise.","code":"fun getOrNull(\n publicName: String,\n configList: ByteString?,\n ): EchRetryPlan? {\n val canonicalHost = publicName.toCanonicalHost() ?: return null\n if (canonicalHost.canParseAsIpAddress()) return null\n if (INVALID_PUBLIC_NAME.matches(canonicalHost)) return null\n return EchRetryPlan(\n publicName,\n configList,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/BridgeInterceptor.kt","line":34,"symbol":"BridgeInterceptor","kind":"class","lang":"kotlin","doc":"Bridges from application code to network code. First it builds a network request from a user request. Then it proceeds to call the network. Finally it builds a user response from the network response.","code":"class BridgeInterceptor : Interceptor {\n @Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val userRequest = chain.request()\n val requestBuilder = userRequest.newBuilder()\n\n val body = userRequest.body\n if (body != null) {\n val contentType = body.contentType()\n if (contentType != null) {\n requestBuilder.header(\"Content-Type\", contentType.toString())\n }\n\n val contentLength = body.contentLength()\n if (contentLength != -1L) {\n requestBuilder.header(\"Content-Length\", contentLength.toString())\n requestBuilder.removeHeader(\"Transfer-Encoding\")\n } else {\n requestBuilder.header(\"Transfer-Encoding\", \"chunked\")\n requestBuilder.removeHeader(\"Content-Length\")\n }\n }\n\n if (userRequest.header(\"Host\") == null) {\n requestBuilder.header(\"Host\", userRequest.url.toHostHeader())\n }\n\n if (userRequest.header(\"Connection\") == null) {\n requestBuilder.header(\"Connection\", \"Keep-Alive\")\n }\n\n // If we add an \"Accept-Encoding: gzip\" header field we're responsible for also decompressing\n // the transfer stream.\n var transparentGzip = false\n if (userReq"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/BridgeInterceptor.kt","line":35,"symbol":"intercept","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val userRequest = chain.request()\n val requestBuilder = userRequest.newBuilder()\n\n val body = userRequest.body\n if (body != null) {\n val contentType = body.contentType()\n if (contentType != null) {\n requestBuilder.header(\"Content-Type\", contentType.toString())\n }\n\n val contentLength = body.contentLength()\n if (contentLength != -1L) {\n requestBuilder.header(\"Content-Length\", contentLength.toString())\n requestBuilder.removeHeader(\"Transfer-Encoding\")\n } else {\n requestBuilder.header(\"Transfer-Encoding\", \"chunked\")\n requestBuilder.removeHeader(\"Content-Length\")\n }\n }\n\n if (userRequest.header(\"Host\") == null) {\n requestBuilder.header(\"Host\", userRequest.url.toHostHeader())\n }\n\n if (userRequest.header(\"Connection\") == null) {\n requestBuilder.header(\"Connection\", \"Keep-Alive\")\n }\n\n // If we add an \"Accept-Encoding: gzip\" header field we're responsible for also decompressing\n // the transfer stream.\n var transparentGzip = false\n if (userRequest.header(\"Accept-Encoding\") == null && "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/BridgeInterceptor.kt","line":113,"symbol":"cookieHeader","kind":"function","lang":"kotlin","doc":"Returns a 'Cookie' HTTP request header with all cookies, like `a=b; c=d`.","code":"private fun cookieHeader(cookies: List): String =\n buildString {\n cookies.forEachIndexed { index, cookie ->\n if (index > 0) append(\"; \")\n append(cookie.name).append('=').append(cookie.value)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/CallServerInterceptor.kt","line":30,"symbol":"CallServerInterceptor","kind":"object","lang":"kotlin","doc":"This is the last interceptor in the chain. It makes a network call to the server.","code":"object CallServerInterceptor : Interceptor {\n @Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val realChain = chain as RealInterceptorChain\n val exchange = realChain.exchange!!\n val request = realChain.request\n val requestBody = request.body\n val sentRequestMillis = System.currentTimeMillis()\n\n var invokeStartEvent = true\n var responseBuilder: Response.Builder? = null\n var sendRequestException: IOException? = null\n val hasRequestBody = HttpMethod.permitsRequestBody(request.method) && requestBody != null\n val isUpgradeRequest = \"upgrade\".equals(request.header(\"Connection\"), ignoreCase = true)\n try {\n exchange.writeRequestHeaders(request)\n\n if (hasRequestBody) {\n // If there's a \"Expect: 100-continue\" header on the request, wait for a \"HTTP/1.1 100\n // Continue\" response before transmitting the request body. If we don't get that, return\n // what we did get (such as a 4xx response) without ever transmitting the request body.\n if (\"100-continue\".equals(request.header(\"Expect\"), ignoreCase = true)) {\n exchange.flushRequest()\n responseBuilder = exchange.re"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/CallServerInterceptor.kt","line":31,"symbol":"intercept","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val realChain = chain as RealInterceptorChain\n val exchange = realChain.exchange!!\n val request = realChain.request\n val requestBody = request.body\n val sentRequestMillis = System.currentTimeMillis()\n\n var invokeStartEvent = true\n var responseBuilder: Response.Builder? = null\n var sendRequestException: IOException? = null\n val hasRequestBody = HttpMethod.permitsRequestBody(request.method) && requestBody != null\n val isUpgradeRequest = \"upgrade\".equals(request.header(\"Connection\"), ignoreCase = true)\n try {\n exchange.writeRequestHeaders(request)\n\n if (hasRequestBody) {\n // If there's a \"Expect: 100-continue\" header on the request, wait for a \"HTTP/1.1 100\n // Continue\" response before transmitting the request body. If we don't get that, return\n // what we did get (such as a 4xx response) without ever transmitting the request body.\n if (\"100-continue\".equals(request.header(\"Expect\"), ignoreCase = true)) {\n exchange.flushRequest()\n responseBuilder = exchange.readResponseHeaders(expectContinue = true)\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/CallServerInterceptor.kt","line":161,"symbol":"peek","kind":"function","lang":"kotlin","code":"override fun peek() = exchange.peekTrailers()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/CallServerInterceptor.kt","line":163,"symbol":"get","kind":"function","lang":"kotlin","code":"override fun get(): Headers {\n val source = responseBody.source()\n if (source.isOpen) {\n source.skipAll()\n }\n return peek() ?: error(\"null trailers after exhausting response body?!\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/CallServerInterceptor.kt","line":194,"symbol":"shouldIgnoreAndWaitForRealResponse","kind":"function","lang":"kotlin","code":"private fun shouldIgnoreAndWaitForRealResponse(code: Int): Boolean =\n when {\n // Server sent a 100-continue even though we did not request one. Try again to read the\n // actual response status.\n code == 100 -> true\n\n // Handle Processing (102) & Early Hints (103) and any new codes without failing\n // 100 and 101 are the exceptions with different meanings\n // But Early Hints not currently exposed\n code in (102 until 200) -> true\n\n else -> false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/DateFormatting.kt","line":34,"symbol":"initialValue","kind":"function","lang":"kotlin","code":"override fun initialValue(): DateFormat {\n // Date format specified by RFC 7231 section 7.1.1.1.\n return SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss 'GMT'\", Locale.US).apply {\n isLenient = false\n timeZone = UTC\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/DateFormatting.kt","line":73,"symbol":"toHttpDateOrNull","kind":"function","lang":"kotlin","doc":"Returns the date for this string, or null if the value couldn't be parsed.","code":"fun String.toHttpDateOrNull(): Date? {\n if (isEmpty()) return null\n\n val position = ParsePosition(0)\n var result = STANDARD_DATE_FORMAT.get().parse(this, position)\n if (position.index == length) {\n // STANDARD_DATE_FORMAT must match exactly; all text must be consumed, e.g. no ignored\n // non-standard trailing \"+01:00\". Those cases are covered below.\n return result\n }\n synchronized(BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS) {\n for (i in 0 until BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS.size) {\n var format: DateFormat? = BROWSER_COMPATIBLE_DATE_FORMATS[i]\n if (format == null) {\n format =\n SimpleDateFormat(BROWSER_COMPATIBLE_DATE_FORMAT_STRINGS[i], Locale.US).apply {\n // Set the timezone to use when interpreting formats that don't have a timezone. GMT is\n // specified by RFC 7231.\n timeZone = UTC\n }\n BROWSER_COMPATIBLE_DATE_FORMATS[i] = format\n }\n position.index = 0\n result = format.parse(this, position)\n if (position.index != 0) {\n // Something was parsed. It's possible the entire string was not consumed but we ignore\n // that. If any of the BROWSER_COMPATIBLE_DATE"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/DateFormatting.kt","line":111,"symbol":"toHttpDateString","kind":"function","lang":"kotlin","doc":"Returns the string for this date.","code":"fun Date.toHttpDateString(): String = STANDARD_DATE_FORMAT.get().format(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":30,"symbol":"ExchangeCodec","kind":"interface","lang":"kotlin","doc":"Encodes HTTP requests and decodes HTTP responses.","code":"@OkHttpInternalApi\ninterface ExchangeCodec {\n /** The connection or CONNECT tunnel that owns this codec. */\n val carrier: Carrier\n\n /** Returns true if the response body and (possibly empty) trailers have been received. */\n val isResponseComplete: Boolean\n\n /** The socket that carries this exchange. */\n val socket: Socket\n\n /** Returns an output stream where the request body can be streamed. */\n @Throws(IOException::class)\n fun createRequestBody(\n request: Request,\n contentLength: Long,\n ): Sink\n\n /** This should update the HTTP engine's sentRequestMillis field. */\n @Throws(IOException::class)\n fun writeRequestHeaders(request: Request)\n\n /** Flush the request to the underlying socket. */\n @Throws(IOException::class)\n fun flushRequest()\n\n /** Flush the request to the underlying socket and signal no more bytes will be transmitted. */\n @Throws(IOException::class)\n fun finishRequest()\n\n /**\n * Parses bytes of a response header from an HTTP transport.\n *\n * @param expectContinue true to return null if this is an intermediate response with a \"100\"\n * response code. Otherwise this method never returns null.\n */\n @Throws(IOException::class)\n fun readRe"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":42,"symbol":"createRequestBody","kind":"function","lang":"kotlin","doc":"Returns an output stream where the request body can be streamed.","code":"@Throws(IOException::class)\n fun createRequestBody(\n request: Request,\n contentLength: Long,\n ): Sink"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":49,"symbol":"writeRequestHeaders","kind":"function","lang":"kotlin","doc":"This should update the HTTP engine's sentRequestMillis field.","code":"@Throws(IOException::class)\n fun writeRequestHeaders(request: Request)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":53,"symbol":"flushRequest","kind":"function","lang":"kotlin","doc":"Flush the request to the underlying socket.","code":"@Throws(IOException::class)\n fun flushRequest()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":57,"symbol":"finishRequest","kind":"function","lang":"kotlin","doc":"Flush the request to the underlying socket and signal no more bytes will be transmitted.","code":"@Throws(IOException::class)\n fun finishRequest()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":66,"symbol":"readResponseHeaders","kind":"function","lang":"kotlin","doc":"Parses bytes of a response header from an HTTP transport. @param expectContinue true to return null if this is an intermediate response with a \"100\" response code. Otherwise this method never returns null.","code":"@Throws(IOException::class)\n fun readResponseHeaders(expectContinue: Boolean): Response.Builder?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":69,"symbol":"reportedContentLength","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun reportedContentLength(response: Response): Long"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":72,"symbol":"openResponseBodySource","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun openResponseBodySource(response: Response): Source"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":76,"symbol":"peekTrailers","kind":"function","lang":"kotlin","doc":"Returns the trailers after the HTTP response if they're ready. May be empty.","code":"@Throws(IOException::class)\n fun peekTrailers(): Headers?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":83,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"Cancel this stream. Resources held by this stream will be cleaned up, though not synchronously. That may happen later by the connection pool thread.","code":"fun cancel()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":89,"symbol":"Carrier","kind":"interface","lang":"kotlin","doc":"Carries an exchange. This is usually a connection, but it could also be a connect plan for CONNECT tunnels. Note that CONNECT tunnels are significantly less capable than connections.","code":"interface Carrier {\n val route: Route\n\n fun trackFailure(\n call: RealCall,\n e: IOException?,\n )\n\n fun noNewExchanges()\n\n fun cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":92,"symbol":"trackFailure","kind":"function","lang":"kotlin","code":"fun trackFailure(\n call: RealCall,\n e: IOException?,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":97,"symbol":"noNewExchanges","kind":"function","lang":"kotlin","code":"fun noNewExchanges()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/ExchangeCodec.kt","line":99,"symbol":"cancel","kind":"function","lang":"kotlin","code":"fun cancel()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/GzipRequestBody.kt","line":23,"symbol":"GzipRequestBody","kind":"class","lang":"kotlin","code":"internal class GzipRequestBody(\n val delegate: RequestBody,\n) : RequestBody() {\n override fun contentType() = delegate.contentType()\n\n // We don't know the compressed length in advance!\n override fun contentLength() = -1L\n\n override fun writeTo(sink: BufferedSink) {\n GzipSink(sink).buffer().use(delegate::writeTo)\n }\n\n override fun isOneShot() = delegate.isOneShot()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/GzipRequestBody.kt","line":26,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = delegate.contentType()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/GzipRequestBody.kt","line":29,"symbol":"contentLength","kind":"function","lang":"kotlin","doc":"We don't know the compressed length in advance!","code":"override fun contentLength() = -1L"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/GzipRequestBody.kt","line":31,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n GzipSink(sink).buffer().use(delegate::writeTo)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/GzipRequestBody.kt","line":35,"symbol":"isOneShot","kind":"function","lang":"kotlin","code":"override fun isOneShot() = delegate.isOneShot()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpHeaders.kt","line":74,"symbol":"readChallengeHeader","kind":"function","lang":"kotlin","code":"private fun Buffer.readChallengeHeader(result: MutableList) {\n var peek: String? = null\n\n while (true) {\n // Read a scheme name for this challenge if we don't have one already.\n if (peek == null) {\n skipCommasAndWhitespace()\n peek = readToken()\n if (peek == null) return\n }\n\n val schemeName = peek\n\n // Read a token68, a sequence of parameters, or nothing.\n val commaPrefixed = skipCommasAndWhitespace()\n peek = readToken()\n if (peek == null) {\n if (!exhausted()) return // Expected a token; got something else.\n result.add(Challenge(schemeName, emptyMap()))\n return\n }\n\n var eqCount = skipAll('='.code.toByte())\n val commaSuffixed = skipCommasAndWhitespace()\n\n // It's a token68 because there isn't a value after it.\n if (!commaPrefixed && (commaSuffixed || exhausted())) {\n result.add(\n Challenge(\n schemeName,\n Collections.singletonMap(null, peek + \"=\".repeat(eqCount)),\n ),\n )\n peek = null\n continue\n }\n\n // It's a series of parameter names and values.\n val parameters = mutableMapOf()\n eqCount += skipAll('='.code.t"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpHeaders.kt","line":140,"symbol":"skipCommasAndWhitespace","kind":"function","lang":"kotlin","doc":"Returns true if any commas were skipped.","code":"private fun Buffer.skipCommasAndWhitespace(): Boolean {\n var commaFound = false\n loop@ while (!exhausted()) {\n when (this[0]) {\n ','.code.toByte() -> {\n // Consume ','.\n readByte()\n commaFound = true\n }\n\n ' '.code.toByte(), '\\t'.code.toByte() -> {\n readByte()\n // Consume space or tab.\n }\n\n else -> {\n break@loop\n }\n }\n }\n return commaFound\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpHeaders.kt","line":163,"symbol":"startsWith","kind":"function","lang":"kotlin","code":"private fun Buffer.startsWith(prefix: Byte): Boolean = !exhausted() && this[0] == prefix"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpHeaders.kt","line":170,"symbol":"readQuotedString","kind":"function","lang":"kotlin","doc":"Reads a double-quoted string, unescaping quoted pairs like `\\\"` to the 2nd character in each sequence. Returns the unescaped string, or null if the buffer isn't prefixed with a double-quoted string.","code":"@Throws(EOFException::class)\nprivate fun Buffer.readQuotedString(): String? {\n require(readByte() == '\\\"'.code.toByte())\n val result = Buffer()\n while (true) {\n val i = indexOfElement(QUOTED_STRING_DELIMITERS)\n if (i == -1L) return null // Unterminated quoted string.\n\n if (this[i] == '\"'.code.toByte()) {\n result.write(this, i)\n // Consume '\"'.\n readByte()\n return result.readUtf8()\n }\n\n if (size == i + 1L) return null // Dangling escape.\n result.write(this, i)\n // Consume '\\'.\n readByte()\n result.write(this, 1L) // The escaped character.\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpHeaders.kt","line":197,"symbol":"readToken","kind":"function","lang":"kotlin","doc":"Consumes and returns a non-empty token, terminating at special characters in [TOKEN_DELIMITERS]. Returns null if the buffer is empty or prefixed with a delimiter.","code":"private fun Buffer.readToken(): String? {\n var tokenSize = indexOfElement(TOKEN_DELIMITERS)\n if (tokenSize == -1L) tokenSize = size\n\n return when {\n tokenSize != 0L -> readUtf8(tokenSize)\n else -> null\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpHeaders.kt","line":207,"symbol":"receiveHeaders","kind":"function","lang":"kotlin","code":"fun CookieJar.receiveHeaders(\n url: HttpUrl,\n headers: Headers,\n) {\n if (this === CookieJar.NO_COOKIES) return\n\n val cookies = Cookie.parseAll(url, headers)\n if (cookies.isEmpty()) return\n\n saveFromResponse(url, cookies)\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpHeaders.kt","line":223,"symbol":"promisesBody","kind":"function","lang":"kotlin","doc":"Returns true if the response headers and status indicate that this response has a (possibly 0-length) body. See RFC 7231.","code":"fun Response.promisesBody(): Boolean {\n // HEAD requests never yield a body regardless of the response headers.\n if (request.method == \"HEAD\") {\n return false\n }\n\n val responseCode = code\n if ((responseCode < HTTP_CONTINUE || responseCode >= 200) &&\n responseCode != HTTP_NO_CONTENT &&\n responseCode != HTTP_NOT_MODIFIED\n ) {\n return true\n }\n\n // If the Content-Length or Transfer-Encoding headers disagree with the response code, the\n // response is malformed. For best compatibility, we honor the headers.\n if (headersContentLength() != -1L ||\n \"chunked\".equals(header(\"Transfer-Encoding\"), ignoreCase = true)\n ) {\n return true\n }\n\n return false\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpHeaders.kt","line":248,"symbol":"hasBody","kind":"function","lang":"kotlin","code":"@Deprecated(\n message = \"No longer supported\",\n level = DeprecationLevel.ERROR,\n replaceWith = ReplaceWith(expression = \"response.promisesBody()\"),\n)\nfun hasBody(response: Response): Boolean = response.promisesBody()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpMethod.kt","line":21,"symbol":"HttpMethod","kind":"object","lang":"kotlin","code":"object HttpMethod {\n @JvmStatic // Despite being 'internal', this method is called by popular 3rd party SDKs.\n fun invalidatesCache(method: String): Boolean =\n (\n method == \"POST\" ||\n method == \"PATCH\" ||\n method == \"PUT\" ||\n method == \"DELETE\" ||\n method == \"MOVE\"\n )\n\n @JvmStatic // Despite being 'internal', this method is called by popular 3rd party SDKs.\n fun requiresRequestBody(method: String): Boolean =\n (\n method == \"POST\" ||\n method == \"PUT\" ||\n method == \"PATCH\" ||\n method == \"PROPPATCH\" ||\n method == \"QUERY\" ||\n // WebDAV\n method == \"REPORT\"\n )\n\n @JvmStatic // Despite being 'internal', this method is called by popular 3rd party SDKs.\n fun permitsRequestBody(method: String): Boolean = !(method == \"GET\" || method == \"HEAD\")\n\n fun redirectsToGet(\n method: String,\n responseCode: Int,\n ): Boolean {\n if (responseCode == HTTP_SEE_OTHER) return method != \"PROPFIND\"\n if (responseCode == HTTP_TEMP_REDIRECT || responseCode == HTTP_PERM_REDIRECT) return false\n return method != \"PROPFIND\" && method != \"QUERY\"\n }\n\n fun isCacheable(requestMethod: String): Boolean = request"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpMethod.kt","line":22,"symbol":"invalidatesCache","kind":"function","lang":"kotlin","code":"@JvmStatic // Despite being 'internal', this method is called by popular 3rd party SDKs.\n fun invalidatesCache(method: String): Boolean =\n (\n method == \"POST\" ||\n method == \"PATCH\" ||\n method == \"PUT\" ||\n method == \"DELETE\" ||\n method == \"MOVE\"\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpMethod.kt","line":32,"symbol":"requiresRequestBody","kind":"function","lang":"kotlin","code":"@JvmStatic // Despite being 'internal', this method is called by popular 3rd party SDKs.\n fun requiresRequestBody(method: String): Boolean =\n (\n method == \"POST\" ||\n method == \"PUT\" ||\n method == \"PATCH\" ||\n method == \"PROPPATCH\" ||\n method == \"QUERY\" ||\n // WebDAV\n method == \"REPORT\"\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpMethod.kt","line":44,"symbol":"permitsRequestBody","kind":"function","lang":"kotlin","code":"@JvmStatic // Despite being 'internal', this method is called by popular 3rd party SDKs.\n fun permitsRequestBody(method: String): Boolean = !(method == \"GET\" || method == \"HEAD\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpMethod.kt","line":47,"symbol":"redirectsToGet","kind":"function","lang":"kotlin","code":"fun redirectsToGet(\n method: String,\n responseCode: Int,\n ): Boolean {\n if (responseCode == HTTP_SEE_OTHER) return method != \"PROPFIND\"\n if (responseCode == HTTP_TEMP_REDIRECT || responseCode == HTTP_PERM_REDIRECT) return false\n return method != \"PROPFIND\" && method != \"QUERY\"\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/HttpMethod.kt","line":56,"symbol":"isCacheable","kind":"function","lang":"kotlin","code":"fun isCacheable(requestMethod: String): Boolean = requestMethod == \"GET\" || requestMethod == \"QUERY\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":53,"symbol":"RealInterceptorChain","kind":"class","lang":"kotlin","doc":"A concrete interceptor chain that carries the entire interceptor chain: all application interceptors, the OkHttp core, all network interceptors, and finally the network caller. If the chain is for an application interceptor then [exchange] must be null. Otherwise it is for a network interceptor and [exchange] must be non-null.","code":"class RealInterceptorChain(\n internal val call: RealCall,\n private val interceptors: List,\n private val index: Int,\n internal val exchange: Exchange?,\n internal val request: Request,\n internal val connectTimeoutMillis: Int,\n internal val readTimeoutMillis: Int,\n internal val writeTimeoutMillis: Int,\n override val authenticator: Authenticator,\n override val cache: Cache?,\n override val certificatePinner: CertificatePinner,\n override val connectionPool: ConnectionPool,\n override val cookieJar: CookieJar,\n override val dns: Dns,\n override val hostnameVerifier: HostnameVerifier,\n override val proxy: Proxy?,\n override val proxyAuthenticator: Authenticator,\n override val proxySelector: ProxySelector,\n override val retryOnConnectionFailure: Boolean,\n override val socketFactory: SocketFactory,\n override val sslSocketFactoryOrNull: SSLSocketFactory?,\n override val x509TrustManagerOrNull: X509TrustManager?,\n val certificateChainCleaner: CertificateChainCleaner?,\n) : Interceptor.Chain {\n internal constructor(\n call: RealCall,\n interceptors: List,\n index: Int,\n exchange: Nothing?,\n request: Request,\n client: OkHttpClient = cal"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":113,"symbol":"copy","kind":"function","lang":"kotlin","code":"internal fun copy(\n index: Int = this.index,\n exchange: Exchange? = this.exchange,\n request: Request = this.request,\n connectTimeoutMillis: Int = this.connectTimeoutMillis,\n readTimeoutMillis: Int = this.readTimeoutMillis,\n writeTimeoutMillis: Int = this.writeTimeoutMillis,\n authenticator: Authenticator = this.authenticator,\n cache: Cache? = this.cache,\n certificatePinner: CertificatePinner = this.certificatePinner,\n connectionPool: ConnectionPool = this.connectionPool,\n cookieJar: CookieJar = this.cookieJar,\n dns: Dns = this.dns,\n hostnameVerifier: HostnameVerifier = this.hostnameVerifier,\n proxy: Proxy? = this.proxy,\n proxyAuthenticator: Authenticator = this.proxyAuthenticator,\n proxySelector: ProxySelector = this.proxySelector,\n retryOnConnectionFailure: Boolean = this.retryOnConnectionFailure,\n socketFactory: SocketFactory = this.socketFactory,\n sslSocketFactory: SSLSocketFactory? = this.sslSocketFactoryOrNull,\n x509TrustManager: X509TrustManager? = this.x509TrustManagerOrNull,\n certificateChainCleaner: CertificateChainCleaner? = this.certificateChainCleaner,\n ) = RealInterceptorChain(\n call = call,\n intercep"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":170,"symbol":"connection","kind":"function","lang":"kotlin","code":"override fun connection(): Connection? = exchange?.connection"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":172,"symbol":"connectTimeoutMillis","kind":"function","lang":"kotlin","code":"override fun connectTimeoutMillis(): Int = connectTimeoutMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":174,"symbol":"withConnectTimeout","kind":"function","lang":"kotlin","code":"override fun withConnectTimeout(\n timeout: Int,\n unit: TimeUnit,\n ): Interceptor.Chain {\n check(exchange == null) { \"Timeouts can't be adjusted in a network interceptor\" }\n\n return copy(connectTimeoutMillis = checkDuration(\"connectTimeout\", timeout.toLong(), unit))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":183,"symbol":"readTimeoutMillis","kind":"function","lang":"kotlin","code":"override fun readTimeoutMillis(): Int = readTimeoutMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":185,"symbol":"withReadTimeout","kind":"function","lang":"kotlin","code":"override fun withReadTimeout(\n timeout: Int,\n unit: TimeUnit,\n ): Interceptor.Chain {\n check(exchange == null) { \"Timeouts can't be adjusted in a network interceptor\" }\n\n return copy(readTimeoutMillis = checkDuration(\"readTimeout\", timeout.toLong(), unit))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":194,"symbol":"writeTimeoutMillis","kind":"function","lang":"kotlin","code":"override fun writeTimeoutMillis(): Int = writeTimeoutMillis"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":196,"symbol":"withWriteTimeout","kind":"function","lang":"kotlin","code":"override fun withWriteTimeout(\n timeout: Int,\n unit: TimeUnit,\n ): Interceptor.Chain {\n check(exchange == null) { \"Timeouts can't be adjusted in a network interceptor\" }\n\n return copy(writeTimeoutMillis = checkDuration(\"writeTimeout\", timeout.toLong(), unit))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":205,"symbol":"withDns","kind":"function","lang":"kotlin","code":"override fun withDns(dns: Dns): Interceptor.Chain {\n check(exchange == null) { \"dns can't be adjusted in a network interceptor\" }\n\n return copy(dns = dns)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":211,"symbol":"withSocketFactory","kind":"function","lang":"kotlin","code":"override fun withSocketFactory(socketFactory: SocketFactory): Interceptor.Chain {\n check(exchange == null) { \"socketFactory can't be adjusted in a network interceptor\" }\n\n return copy(socketFactory = socketFactory)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":217,"symbol":"withRetryOnConnectionFailure","kind":"function","lang":"kotlin","code":"override fun withRetryOnConnectionFailure(retryOnConnectionFailure: Boolean): Interceptor.Chain {\n check(exchange == null) { \"retryOnConnectionFailure can't be adjusted in a network interceptor\" }\n\n return copy(retryOnConnectionFailure = retryOnConnectionFailure)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":223,"symbol":"withAuthenticator","kind":"function","lang":"kotlin","code":"override fun withAuthenticator(authenticator: Authenticator): Interceptor.Chain {\n check(exchange == null) { \"authenticator can't be adjusted in a network interceptor\" }\n\n return copy(authenticator = authenticator)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":229,"symbol":"withCookieJar","kind":"function","lang":"kotlin","code":"override fun withCookieJar(cookieJar: CookieJar): Interceptor.Chain {\n check(exchange == null) { \"cookieJar can't be adjusted in a network interceptor\" }\n\n return copy(cookieJar = cookieJar)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":235,"symbol":"withCache","kind":"function","lang":"kotlin","code":"override fun withCache(cache: Cache?): Interceptor.Chain {\n check(exchange == null) { \"cache can't be adjusted in a network interceptor\" }\n\n return copy(cache = cache)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":241,"symbol":"withProxy","kind":"function","lang":"kotlin","code":"override fun withProxy(proxy: Proxy?): Interceptor.Chain {\n check(exchange == null) { \"proxy can't be adjusted in a network interceptor\" }\n\n return copy(proxy = proxy)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":247,"symbol":"withProxySelector","kind":"function","lang":"kotlin","code":"override fun withProxySelector(proxySelector: ProxySelector): Interceptor.Chain {\n check(exchange == null) { \"proxySelector can't be adjusted in a network interceptor\" }\n\n return copy(proxySelector = proxySelector)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":253,"symbol":"withProxyAuthenticator","kind":"function","lang":"kotlin","code":"override fun withProxyAuthenticator(proxyAuthenticator: Authenticator): Interceptor.Chain {\n check(exchange == null) { \"proxyAuthenticator can't be adjusted in a network interceptor\" }\n\n return copy(proxyAuthenticator = proxyAuthenticator)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":259,"symbol":"withSslSocketFactory","kind":"function","lang":"kotlin","code":"override fun withSslSocketFactory(\n sslSocketFactory: SSLSocketFactory?,\n x509TrustManager: X509TrustManager?,\n ): Interceptor.Chain {\n check(exchange == null) { \"sslSocketFactory can't be adjusted in a network interceptor\" }\n\n if (sslSocketFactory != null && x509TrustManager != null) {\n val newCertificateChainCleaner = CertificateChainCleaner.get(x509TrustManager)\n return copy(\n sslSocketFactory = sslSocketFactory,\n x509TrustManager = x509TrustManager,\n certificateChainCleaner = newCertificateChainCleaner,\n certificatePinner = certificatePinner.withCertificateChainCleaner(newCertificateChainCleaner),\n )\n } else {\n return copy(\n sslSocketFactory = null,\n x509TrustManager = null,\n certificateChainCleaner = null,\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":282,"symbol":"withHostnameVerifier","kind":"function","lang":"kotlin","code":"override fun withHostnameVerifier(hostnameVerifier: HostnameVerifier): Interceptor.Chain {\n check(exchange == null) { \"hostnameVerifier can't be adjusted in a network interceptor\" }\n\n return copy(hostnameVerifier = hostnameVerifier)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":288,"symbol":"withCertificatePinner","kind":"function","lang":"kotlin","code":"override fun withCertificatePinner(certificatePinner: CertificatePinner): Interceptor.Chain {\n check(exchange == null) { \"certificatePinner can't be adjusted in a network interceptor\" }\n\n val newCertificatePinner =\n if (certificateChainCleaner != null) {\n certificatePinner.withCertificateChainCleaner(certificateChainCleaner)\n } else {\n certificatePinner\n }\n\n return copy(certificatePinner = newCertificatePinner)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":301,"symbol":"withConnectionPool","kind":"function","lang":"kotlin","code":"override fun withConnectionPool(connectionPool: ConnectionPool): Interceptor.Chain {\n check(exchange == null) { \"connectionPool can't be adjusted in a network interceptor\" }\n\n return copy(connectionPool = connectionPool)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":307,"symbol":"call","kind":"function","lang":"kotlin","code":"override fun call(): Call = call"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":309,"symbol":"request","kind":"function","lang":"kotlin","code":"override fun request(): Request = request"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":311,"symbol":"proceed","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun proceed(request: Request): Response {\n check(index < interceptors.size)\n\n calls++\n\n if (exchange != null) {\n check(exchange.finder.routePlanner.sameHostAndPort(request.url)) {\n \"network interceptor ${interceptors[index - 1]} must retain the same host and port\"\n }\n check(calls == 1) {\n \"network interceptor ${interceptors[index - 1]} must call proceed() exactly once\"\n }\n }\n\n // Call the next interceptor in the chain.\n val next = copy(index = index + 1, request = request)\n val interceptor = interceptors[index]\n\n @Suppress(\"USELESS_ELVIS\")\n val response =\n interceptor.intercept(next) ?: throw NullPointerException(\n \"interceptor $interceptor returned null\",\n )\n\n if (exchange != null) {\n check(index + 1 >= interceptors.size || next.calls == 1) {\n \"network interceptor $interceptor must call proceed() exactly once\"\n }\n }\n\n return response\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealInterceptorChain.kt","line":349,"symbol":"address","kind":"function","lang":"kotlin","doc":"Creates an [Address] of out of the provided [HttpUrl] that uses this client’s DNS, TLS, and proxy configuration.","code":"fun address(url: HttpUrl): Address {\n var useSslSocketFactory: SSLSocketFactory? = null\n var useHostnameVerifier: HostnameVerifier? = null\n var useCertificatePinner: CertificatePinner? = null\n if (url.isHttps) {\n useSslSocketFactory = this.sslSocketFactoryOrNull\n useHostnameVerifier = this.hostnameVerifier\n useCertificatePinner = this.certificatePinner\n }\n\n return Address(\n uriHost = url.host,\n uriPort = url.port,\n dns = dns,\n socketFactory = socketFactory,\n sslSocketFactory = useSslSocketFactory,\n hostnameVerifier = useHostnameVerifier,\n certificatePinner = useCertificatePinner,\n proxyAuthenticator = proxyAuthenticator,\n proxy = proxy,\n protocols = call.client.protocols,\n connectionSpecs = call.client.connectionSpecs,\n proxySelector = proxySelector,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealResponseBody.kt","line":23,"symbol":"RealResponseBody","kind":"class","lang":"kotlin","code":"class RealResponseBody(\n /**\n * Use a string to avoid parsing the content type until needed. This also defers problems caused\n * by malformed content types.\n */\n private val contentTypeString: String?,\n private val contentLength: Long,\n private val source: BufferedSource,\n) : ResponseBody() {\n override fun contentLength(): Long = contentLength\n\n override fun contentType(): MediaType? = contentTypeString?.toMediaTypeOrNull()\n\n override fun source(): BufferedSource = source\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealResponseBody.kt","line":32,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = contentLength"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealResponseBody.kt","line":34,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = contentTypeString?.toMediaTypeOrNull()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RealResponseBody.kt","line":36,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource = source"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RequestLine.kt","line":22,"symbol":"RequestLine","kind":"object","lang":"kotlin","code":"object RequestLine {\n /**\n * Returns the request status line, like \"GET / HTTP/1.1\". This is exposed to the application by\n * [HttpURLConnection.getHeaderFields], so it needs to be set even if the transport is\n * HTTP/2.\n */\n fun get(\n request: Request,\n proxyType: Proxy.Type,\n ): String =\n buildString {\n append(request.method)\n append(' ')\n if (includeAuthorityInRequestLine(request, proxyType)) {\n append(request.url)\n } else {\n append(requestPath(request.url))\n }\n append(\" HTTP/1.1\")\n }\n\n /**\n * Returns true if the request line should contain the full URL with host and port (like \"GET\n * http://android.com/foo HTTP/1.1\") or only the path (like \"GET /foo HTTP/1.1\").\n */\n private fun includeAuthorityInRequestLine(\n request: Request,\n proxyType: Proxy.Type,\n ): Boolean = !request.isHttps && proxyType == Proxy.Type.HTTP\n\n /**\n * Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty, even if the request\n * URL is. Includes the query component if it exists.\n */\n fun requestPath(url: HttpUrl): String {\n val path = url.encodedPath\n val query = url.encodedQuery\n return if"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RequestLine.kt","line":28,"symbol":"get","kind":"function","lang":"kotlin","doc":"Returns the request status line, like \"GET / HTTP/1.1\". This is exposed to the application by [HttpURLConnection.getHeaderFields], so it needs to be set even if the transport is HTTP/2.","code":"fun get(\n request: Request,\n proxyType: Proxy.Type,\n ): String =\n buildString {\n append(request.method)\n append(' ')\n if (includeAuthorityInRequestLine(request, proxyType)) {\n append(request.url)\n } else {\n append(requestPath(request.url))\n }\n append(\" HTTP/1.1\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RequestLine.kt","line":47,"symbol":"includeAuthorityInRequestLine","kind":"function","lang":"kotlin","doc":"Returns true if the request line should contain the full URL with host and port (like \"GET http://android.com/foo HTTP/1.1\") or only the path (like \"GET /foo HTTP/1.1\").","code":"private fun includeAuthorityInRequestLine(\n request: Request,\n proxyType: Proxy.Type,\n ): Boolean = !request.isHttps && proxyType == Proxy.Type.HTTP"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RequestLine.kt","line":56,"symbol":"requestPath","kind":"function","lang":"kotlin","doc":"Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty, even if the request URL is. Includes the query component if it exists.","code":"fun requestPath(url: HttpUrl): String {\n val path = url.encodedPath\n val query = url.encodedQuery\n return if (query != null) \"$path?$query\" else path\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt","line":51,"symbol":"RetryAndFollowUpInterceptor","kind":"class","lang":"kotlin","doc":"This interceptor recovers from failures and follows redirects as necessary. It may throw an [IOException] if the call was canceled.","code":"class RetryAndFollowUpInterceptor : Interceptor {\n @Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val realChain = chain as RealInterceptorChain\n var request = chain.request\n val call = realChain.call\n var followUpCount = 0\n var priorResponse: Response? = null\n var newRoutePlanner = true\n var recoveredFailures = listOf()\n while (true) {\n call.enterNetworkInterceptorExchange(request, newRoutePlanner, chain)\n\n var response: Response\n var closeActiveExchange = true\n try {\n if (call.isCanceled()) {\n throw IOException(\"Canceled\")\n }\n\n try {\n response = realChain.proceed(request)\n newRoutePlanner = true\n } catch (e: IOException) {\n // An attempt to communicate with a server failed. The request may have been sent.\n val isRecoverable = recover(e, call, chain, request)\n call.eventListener.retryDecision(call, e, isRecoverable)\n if (!isRecoverable) throw e.withSuppressed(recoveredFailures)\n recoveredFailures += e\n newRoutePlanner = false\n continue\n }\n\n // Clear o"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt","line":52,"symbol":"intercept","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun intercept(chain: Interceptor.Chain): Response {\n val realChain = chain as RealInterceptorChain\n var request = chain.request\n val call = realChain.call\n var followUpCount = 0\n var priorResponse: Response? = null\n var newRoutePlanner = true\n var recoveredFailures = listOf()\n while (true) {\n call.enterNetworkInterceptorExchange(request, newRoutePlanner, chain)\n\n var response: Response\n var closeActiveExchange = true\n try {\n if (call.isCanceled()) {\n throw IOException(\"Canceled\")\n }\n\n try {\n response = realChain.proceed(request)\n newRoutePlanner = true\n } catch (e: IOException) {\n // An attempt to communicate with a server failed. The request may have been sent.\n val isRecoverable = recover(e, call, chain, request)\n call.eventListener.retryDecision(call, e, isRecoverable)\n if (!isRecoverable) throw e.withSuppressed(recoveredFailures)\n recoveredFailures += e\n newRoutePlanner = false\n continue\n }\n\n // Clear out downstream interceptor's additional request heade"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt","line":133,"symbol":"recover","kind":"function","lang":"kotlin","doc":"Report and attempt to recover from a failure to communicate with a server. Returns true if `e` is recoverable, or false if the failure is permanent. Requests with a body can only be recovered if the body is buffered or if the failure occurred before the request has been sent.","code":"private fun recover(\n e: IOException,\n call: RealCall,\n chain: Interceptor.Chain,\n userRequest: Request,\n ): Boolean {\n val requestSendStarted = e !is ConnectionShutdownException\n\n // The application layer has forbidden retries.\n if (!chain.retryOnConnectionFailure) return false\n\n // We can't send the request body again.\n if (requestSendStarted && requestIsOneShot(e, userRequest)) return false\n\n // This exception is fatal.\n if (!isRecoverable(e, requestSendStarted)) return false\n\n // No more routes to attempt.\n if (!call.retryAfterFailure()) return false\n\n // For failure recovery, use the same route selector with a new connection.\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt","line":157,"symbol":"requestIsOneShot","kind":"function","lang":"kotlin","code":"private fun requestIsOneShot(\n e: IOException,\n userRequest: Request,\n ): Boolean {\n val requestBody = userRequest.body\n return (requestBody != null && requestBody.isOneShot()) ||\n e is FileNotFoundException\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt","line":166,"symbol":"isRecoverable","kind":"function","lang":"kotlin","code":"private fun isRecoverable(\n e: IOException,\n requestSendStarted: Boolean,\n ): Boolean {\n // If there was a protocol problem, don't recover.\n if (e is ProtocolException) {\n return false\n }\n\n // If there was an interruption don't recover, but if there was a timeout connecting to a route\n // we should try the next route (if there is one).\n if (e is InterruptedIOException) {\n return e is SocketTimeoutException && !requestSendStarted\n }\n\n // Look for known client-side or negotiation errors that are unlikely to be fixed by trying\n // again with a different route.\n if (e is SSLHandshakeException) {\n // If the problem was a CertificateException from the X509TrustManager,\n // do not retry.\n if (e.cause is CertificateException) {\n return false\n }\n }\n if (e is SSLPeerUnverifiedException) {\n // e.g. a certificate pinning error.\n return false\n }\n // An example of one we might want to retry with a different route is a problem connecting to a\n // proxy and would manifest as a standard IOException. Unless it is one we know we should not\n // retry, we return true and try a new route.\n return tru"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt","line":205,"symbol":"followUpRequest","kind":"function","lang":"kotlin","doc":"Figures out the HTTP request to make in response to receiving [userResponse]. This will either add authentication headers, follow redirects or handle a client request timeout. If a follow-up is either unnecessary or not applicable, this returns null.","code":"@Throws(IOException::class)\n private fun followUpRequest(\n userResponse: Response,\n exchange: Exchange?,\n chain: Interceptor.Chain,\n ): Request? {\n val route = exchange?.connection?.route()\n val responseCode = userResponse.code\n\n val method = userResponse.request.method\n when (responseCode) {\n HTTP_PROXY_AUTH -> {\n val selectedProxy = route!!.proxy\n if (selectedProxy.type() != Proxy.Type.HTTP) {\n throw ProtocolException(\"Received HTTP_PROXY_AUTH (407) code while not using proxy\")\n }\n return chain.proxyAuthenticator.authenticate(route, userResponse)\n }\n\n HTTP_UNAUTHORIZED -> {\n return chain.authenticator.authenticate(route, userResponse)\n }\n\n HTTP_PERM_REDIRECT, HTTP_TEMP_REDIRECT, HTTP_MULT_CHOICE, HTTP_MOVED_PERM, HTTP_MOVED_TEMP, HTTP_SEE_OTHER -> {\n return buildRedirectRequest(userResponse, method, chain)\n }\n\n HTTP_CLIENT_TIMEOUT -> {\n // 408's are rare in practice, but some servers like HAProxy use this response code. The\n // spec says that we may repeat the request without modifications. Modern browsers also\n // repeat the request (even non-idempote"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt","line":296,"symbol":"buildRedirectRequest","kind":"function","lang":"kotlin","code":"private fun buildRedirectRequest(\n userResponse: Response,\n method: String,\n chain: Interceptor.Chain,\n ): Request? {\n // Does the client allow redirects?\n if (!chain.followRedirects) return null\n\n val location = userResponse.header(\"Location\") ?: return null\n // Don't follow redirects to unsupported protocols.\n val url = userResponse.request.url.resolve(location) ?: return null\n\n // If configured, don't follow redirects between SSL and non-SSL.\n val sameScheme = url.scheme == userResponse.request.url.scheme\n if (!sameScheme && !chain.followSslRedirects) return null\n\n // Most redirects don't include a request body.\n val requestBuilder = userResponse.request.newBuilder()\n if (HttpMethod.permitsRequestBody(method)) {\n val responseCode = userResponse.code\n if (HttpMethod.redirectsToGet(method, responseCode)) {\n requestBuilder.method(\"GET\", null)\n requestBuilder.removeHeader(\"Transfer-Encoding\")\n requestBuilder.removeHeader(\"Content-Length\")\n requestBuilder.removeHeader(\"Content-Type\")\n } else {\n requestBuilder.method(method, userResponse.request.body)\n }\n }\n\n // When redirecting acr"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/RetryAndFollowUpInterceptor.kt","line":336,"symbol":"retryAfter","kind":"function","lang":"kotlin","code":"private fun retryAfter(\n userResponse: Response,\n defaultDelay: Int,\n ): Int {\n val header = userResponse.header(\"Retry-After\") ?: return defaultDelay\n\n // https://tools.ietf.org/html/rfc7231#section-7.1.3\n // currently ignores a HTTP-date, and assumes any non int 0 is a delay\n if (header.matches(\"\\\\d+\".toRegex())) {\n return Integer.valueOf(header)\n }\n return Integer.MAX_VALUE\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/StatusLine.kt","line":25,"symbol":"StatusLine","kind":"class","lang":"kotlin","doc":"An HTTP response status line like \"HTTP/1.1 200 OK\".","code":"class StatusLine(\n @JvmField val protocol: Protocol,\n @JvmField val code: Int,\n @JvmField val message: String,\n) {\n override fun toString(): String =\n buildString {\n if (protocol == Protocol.HTTP_1_0) {\n append(\"HTTP/1.0\")\n } else {\n append(\"HTTP/1.1\")\n }\n append(' ').append(code)\n append(' ').append(message)\n }\n\n companion object {\n fun get(response: Response): StatusLine = StatusLine(response.protocol, response.code, response.message)\n\n @Throws(IOException::class)\n fun parse(statusLine: String): StatusLine {\n // H T T P / 1 . 1 2 0 0 T e m p o r a r y R e d i r e c t\n // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0\n\n // Parse protocol like \"HTTP/1.1\" followed by a space.\n val codeStart: Int\n val protocol: Protocol\n if (statusLine.startsWith(\"HTTP/1.\")) {\n if (statusLine.length < 9 || statusLine[8] != ' ') {\n throw ProtocolException(\"Unexpected status line: $statusLine\")\n }\n val httpMinorVersion = statusLine[7] - '0'\n codeStart = 9\n protocol =\n when (httpMinorVersion) {\n 0 -> Protocol.HTTP_1_0\n 1 "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/StatusLine.kt","line":30,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n buildString {\n if (protocol == Protocol.HTTP_1_0) {\n append(\"HTTP/1.0\")\n } else {\n append(\"HTTP/1.1\")\n }\n append(' ').append(code)\n append(' ').append(message)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/StatusLine.kt","line":42,"symbol":"get","kind":"function","lang":"kotlin","code":"fun get(response: Response): StatusLine = StatusLine(response.protocol, response.code, response.message)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http/StatusLine.kt","line":44,"symbol":"parse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun parse(statusLine: String): StatusLine {\n // H T T P / 1 . 1 2 0 0 T e m p o r a r y R e d i r e c t\n // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0\n\n // Parse protocol like \"HTTP/1.1\" followed by a space.\n val codeStart: Int\n val protocol: Protocol\n if (statusLine.startsWith(\"HTTP/1.\")) {\n if (statusLine.length < 9 || statusLine[8] != ' ') {\n throw ProtocolException(\"Unexpected status line: $statusLine\")\n }\n val httpMinorVersion = statusLine[7] - '0'\n codeStart = 9\n protocol =\n when (httpMinorVersion) {\n 0 -> Protocol.HTTP_1_0\n 1 -> Protocol.HTTP_1_1\n else -> throw ProtocolException(\"Unexpected status line: $statusLine\")\n }\n } else if (statusLine.startsWith(\"ICY \")) {\n // Shoutcast uses ICY instead of \"HTTP/1.0\".\n protocol = Protocol.HTTP_1_0\n codeStart = 4\n } else if (statusLine.startsWith(\"SOURCETABLE \")) {\n // NTRIP r1 uses SOURCETABLE instead of HTTP/1.1\n protocol = Protocol.HTTP_1_1\n codeStart = 12\n } else {\n throw ProtocolException"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/HeadersReader.kt","line":25,"symbol":"HeadersReader","kind":"class","lang":"kotlin","doc":"Parse all headers delimited by \"\\r\\n\" until an empty line. This throws if headers exceed 256 KiB.","code":"class HeadersReader(\n val source: BufferedSource,\n) {\n private var headerLimit = HEADER_LIMIT\n\n /** Read a single line counted against the header size limit. */\n fun readLine(): String {\n val line = source.readUtf8LineStrict(headerLimit)\n headerLimit -= line.length.toLong()\n return line\n }\n\n /** Reads headers or trailers. */\n fun readHeaders(): Headers {\n val result = Headers.Builder()\n while (true) {\n val line = readLine()\n if (line.isEmpty()) break\n result.addLenient(line)\n }\n return result.build()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/HeadersReader.kt","line":31,"symbol":"readLine","kind":"function","lang":"kotlin","doc":"Read a single line counted against the header size limit.","code":"fun readLine(): String {\n val line = source.readUtf8LineStrict(headerLimit)\n headerLimit -= line.length.toLong()\n return line\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/HeadersReader.kt","line":38,"symbol":"readHeaders","kind":"function","lang":"kotlin","doc":"Reads headers or trailers.","code":"fun readHeaders(): Headers {\n val result = Headers.Builder()\n while (true) {\n val line = readLine()\n if (line.isEmpty()) break\n result.addLenient(line)\n }\n return result.build()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":93,"symbol":"createRequestBody","kind":"function","lang":"kotlin","code":"override fun createRequestBody(\n request: Request,\n contentLength: Long,\n ): Sink =\n when {\n request.body?.isDuplex() == true -> {\n throw ProtocolException(\n \"Duplex connections are not supported for HTTP/1\",\n )\n }\n\n request.isChunked -> {\n newChunkedSink()\n }\n\n // Stream a request body of unknown length.\n contentLength != -1L -> {\n newKnownLengthSink()\n }\n\n // Stream a request body of a known length.\n else -> {\n // Stream a request body of a known length.\n throw IllegalStateException(\n \"Cannot stream a request body without chunked encoding or a known content length!\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":122,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n carrier.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":136,"symbol":"writeRequestHeaders","kind":"function","lang":"kotlin","doc":"been written to. Otherwise the body would need to be buffered! For non-streaming requests with a body, headers must be prepared **after** the output stream has been written to and closed. This ensures that the `Content-Length` header field receives the proper value.","code":"override fun writeRequestHeaders(request: Request) {\n val requestLine = RequestLine.get(request, carrier.route.proxy.type())\n writeRequest(request.headers, requestLine)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":141,"symbol":"reportedContentLength","kind":"function","lang":"kotlin","code":"override fun reportedContentLength(response: Response): Long =\n when {\n !response.promisesBody() -> 0L\n response.isChunked -> -1L\n else -> response.headersContentLength()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":148,"symbol":"openResponseBodySource","kind":"function","lang":"kotlin","code":"override fun openResponseBodySource(response: Response): Source =\n when {\n !response.promisesBody() -> {\n newFixedLengthSource(response.request.url, 0)\n }\n\n response.isChunked -> {\n newChunkedSource(response.request.url)\n }\n\n else -> {\n val contentLength = response.headersContentLength()\n if (contentLength != -1L) {\n newFixedLengthSource(response.request.url, contentLength)\n } else {\n newUnknownLengthSource(response.request.url)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":168,"symbol":"peekTrailers","kind":"function","lang":"kotlin","code":"override fun peekTrailers(): Headers? {\n if (trailers === TRAILERS_RESPONSE_BODY_TRUNCATED) {\n throw IOException(\"Trailers cannot be read because the response body was truncated\")\n }\n check(state == STATE_READING_RESPONSE_BODY || state == STATE_CLOSED) {\n \"Trailers cannot be read because the state is $state\"\n }\n return trailers\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":178,"symbol":"flushRequest","kind":"function","lang":"kotlin","code":"override fun flushRequest() {\n socket.sink.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":182,"symbol":"finishRequest","kind":"function","lang":"kotlin","code":"override fun finishRequest() {\n socket.sink.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":187,"symbol":"writeRequest","kind":"function","lang":"kotlin","doc":"Returns bytes of a request header for sending on an HTTP transport.","code":"fun writeRequest(\n headers: Headers,\n requestLine: String,\n ) {\n check(state == STATE_IDLE) { \"state: $state\" }\n socket.sink.writeUtf8(requestLine).writeUtf8(\"\\r\\n\")\n for (i in 0 until headers.size) {\n socket.sink\n .writeUtf8(headers.name(i))\n .writeUtf8(\": \")\n .writeUtf8(headers.value(i))\n .writeUtf8(\"\\r\\n\")\n }\n socket.sink.writeUtf8(\"\\r\\n\")\n state = STATE_OPEN_REQUEST_BODY\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":204,"symbol":"readResponseHeaders","kind":"function","lang":"kotlin","code":"override fun readResponseHeaders(expectContinue: Boolean): Response.Builder? {\n check(\n state == STATE_IDLE ||\n state == STATE_OPEN_REQUEST_BODY ||\n state == STATE_WRITING_REQUEST_BODY ||\n state == STATE_READ_RESPONSE_HEADERS,\n ) {\n \"state: $state\"\n }\n\n try {\n val statusLine = StatusLine.parse(headersReader.readLine())\n\n val responseBuilder =\n Response\n .Builder()\n .protocol(statusLine.protocol)\n .code(statusLine.code)\n .message(statusLine.message)\n .headers(headersReader.readHeaders())\n\n return when {\n expectContinue && statusLine.code == HTTP_CONTINUE -> {\n null\n }\n\n statusLine.code == HTTP_CONTINUE -> {\n state = STATE_READ_RESPONSE_HEADERS\n responseBuilder\n }\n\n statusLine.code in (102 until 200) -> {\n // Processing and Early Hints will mean a second headers are coming.\n // Treat others the same for now\n state = STATE_READ_RESPONSE_HEADERS\n responseBuilder\n }\n\n else -> {\n state = STATE_OPEN_RESPONSE_BODY\n responseBuilder\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":256,"symbol":"newChunkedSink","kind":"function","lang":"kotlin","code":"private fun newChunkedSink(): Sink {\n check(state == STATE_OPEN_REQUEST_BODY) { \"state: $state\" }\n state = STATE_WRITING_REQUEST_BODY\n return ChunkedSink()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":262,"symbol":"newKnownLengthSink","kind":"function","lang":"kotlin","code":"private fun newKnownLengthSink(): Sink {\n check(state == STATE_OPEN_REQUEST_BODY) { \"state: $state\" }\n state = STATE_WRITING_REQUEST_BODY\n return KnownLengthSink()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":268,"symbol":"newFixedLengthSource","kind":"function","lang":"kotlin","code":"private fun newFixedLengthSource(\n url: HttpUrl,\n length: Long,\n ): Source {\n check(state == STATE_OPEN_RESPONSE_BODY) { \"state: $state\" }\n state = STATE_READING_RESPONSE_BODY\n return FixedLengthSource(url, length)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":277,"symbol":"newChunkedSource","kind":"function","lang":"kotlin","code":"private fun newChunkedSource(url: HttpUrl): Source {\n check(state == STATE_OPEN_RESPONSE_BODY) { \"state: $state\" }\n state = STATE_READING_RESPONSE_BODY\n return ChunkedSource(url)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":283,"symbol":"newUnknownLengthSource","kind":"function","lang":"kotlin","code":"private fun newUnknownLengthSource(url: HttpUrl): Source {\n check(state == STATE_OPEN_RESPONSE_BODY) { \"state: $state\" }\n state = STATE_READING_RESPONSE_BODY\n carrier.noNewExchanges()\n return UnknownLengthSource(url)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":295,"symbol":"detachTimeout","kind":"function","lang":"kotlin","doc":"Sets the delegate of `timeout` to [Timeout.NONE] and resets its underlying timeout to the default configuration. Use this to avoid unexpected sharing of timeouts between pooled connections.","code":"private fun detachTimeout(timeout: ForwardingTimeout) {\n val oldDelegate = timeout.delegate\n timeout.setDelegate(Timeout.NONE)\n oldDelegate.clearDeadline()\n oldDelegate.clearTimeout()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":306,"symbol":"skipConnectBody","kind":"function","lang":"kotlin","doc":"The response body from a CONNECT should be empty, but if it is not then we should consume it before proceeding.","code":"fun skipConnectBody(response: Response) {\n val contentLength = response.headersContentLength()\n if (contentLength == -1L) return\n val body = newFixedLengthSource(response.request.url, contentLength)\n body.skipAll(Int.MAX_VALUE, MILLISECONDS)\n body.close()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":315,"symbol":"KnownLengthSink","kind":"class","lang":"kotlin","doc":"An HTTP request body.","code":"private inner class KnownLengthSink : Sink {\n private val timeout = ForwardingTimeout(socket.sink.timeout())\n private var closed: Boolean = false\n\n override fun timeout(): Timeout = timeout\n\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n check(!closed) { \"closed\" }\n checkOffsetAndCount(source.size, 0, byteCount)\n socket.sink.write(source, byteCount)\n }\n\n override fun flush() {\n if (closed) return // Don't throw; this stream might have been closed on the caller's behalf.\n socket.sink.flush()\n }\n\n override fun close() {\n if (closed) return\n closed = true\n // Flush before detachTimeout().\n socket.sink.flush()\n detachTimeout(timeout)\n state = STATE_READ_RESPONSE_HEADERS\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":319,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = timeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":321,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n check(!closed) { \"closed\" }\n checkOffsetAndCount(source.size, 0, byteCount)\n socket.sink.write(source, byteCount)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":330,"symbol":"flush","kind":"function","lang":"kotlin","code":"override fun flush() {\n if (closed) return // Don't throw; this stream might have been closed on the caller's behalf.\n socket.sink.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":335,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n if (closed) return\n closed = true\n // Flush before detachTimeout().\n socket.sink.flush()\n detachTimeout(timeout)\n state = STATE_READ_RESPONSE_HEADERS\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":349,"symbol":"ChunkedSink","kind":"class","lang":"kotlin","doc":"An HTTP body with alternating chunk sizes and chunk bodies. It is the caller's responsibility to buffer chunks; typically by using a buffered sink with this sink.","code":"private inner class ChunkedSink : Sink {\n private val timeout = ForwardingTimeout(socket.sink.timeout())\n private var closed: Boolean = false\n\n override fun timeout(): Timeout = timeout\n\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n check(!closed) { \"closed\" }\n if (byteCount == 0L) return\n\n with(socket.sink) {\n writeHexadecimalUnsignedLong(byteCount)\n writeUtf8(\"\\r\\n\")\n write(source, byteCount)\n writeUtf8(\"\\r\\n\")\n }\n }\n\n @Synchronized\n override fun flush() {\n if (closed) return // Don't throw; this stream might have been closed on the caller's behalf.\n socket.sink.flush()\n }\n\n @Synchronized\n override fun close() {\n if (closed) return\n closed = true\n socket.sink.writeUtf8(\"0\\r\\n\\r\\n\")\n // Flush before detachTimeout().\n socket.sink.flush()\n detachTimeout(timeout)\n state = STATE_READ_RESPONSE_HEADERS\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":353,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = timeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":355,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n check(!closed) { \"closed\" }\n if (byteCount == 0L) return\n\n with(socket.sink) {\n writeHexadecimalUnsignedLong(byteCount)\n writeUtf8(\"\\r\\n\")\n write(source, byteCount)\n writeUtf8(\"\\r\\n\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":370,"symbol":"flush","kind":"function","lang":"kotlin","code":"@Synchronized\n override fun flush() {\n if (closed) return // Don't throw; this stream might have been closed on the caller's behalf.\n socket.sink.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":376,"symbol":"close","kind":"function","lang":"kotlin","code":"@Synchronized\n override fun close() {\n if (closed) return\n closed = true\n socket.sink.writeUtf8(\"0\\r\\n\\r\\n\")\n // Flush before detachTimeout().\n socket.sink.flush()\n detachTimeout(timeout)\n state = STATE_READ_RESPONSE_HEADERS\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":388,"symbol":"AbstractSource","kind":"class","lang":"kotlin","code":"private abstract inner class AbstractSource(\n val url: HttpUrl,\n ) : Source {\n protected val timeout = ForwardingTimeout(socket.source.timeout())\n protected var closed: Boolean = false\n\n override fun timeout(): Timeout = timeout\n\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long =\n try {\n socket.source.read(sink, byteCount)\n } catch (e: IOException) {\n carrier.noNewExchanges()\n responseBodyComplete(TRAILERS_RESPONSE_BODY_TRUNCATED)\n throw e\n }\n\n /**\n * Closes the cache entry and makes the socket available for reuse. This should be invoked when\n * the end of the body has been reached.\n */\n fun responseBodyComplete(trailers: Headers) {\n if (state == STATE_CLOSED) return\n if (state != STATE_READING_RESPONSE_BODY) throw IllegalStateException(\"state: $state\")\n\n detachTimeout(timeout)\n\n this@Http1ExchangeCodec.trailers = trailers\n state = STATE_CLOSED\n if (trailers.size > 0) {\n client?.cookieJar?.receiveHeaders(url, trailers)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":394,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = timeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":396,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long =\n try {\n socket.source.read(sink, byteCount)\n } catch (e: IOException) {\n carrier.noNewExchanges()\n responseBodyComplete(TRAILERS_RESPONSE_BODY_TRUNCATED)\n throw e\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":412,"symbol":"responseBodyComplete","kind":"function","lang":"kotlin","doc":"Closes the cache entry and makes the socket available for reuse. This should be invoked when the end of the body has been reached.","code":"fun responseBodyComplete(trailers: Headers) {\n if (state == STATE_CLOSED) return\n if (state != STATE_READING_RESPONSE_BODY) throw IllegalStateException(\"state: $state\")\n\n detachTimeout(timeout)\n\n this@Http1ExchangeCodec.trailers = trailers\n state = STATE_CLOSED\n if (trailers.size > 0) {\n client?.cookieJar?.receiveHeaders(url, trailers)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":427,"symbol":"FixedLengthSource","kind":"class","lang":"kotlin","doc":"An HTTP body with a fixed length specified in advance.","code":"private inner class FixedLengthSource(\n url: HttpUrl,\n private var bytesRemaining: Long,\n ) : AbstractSource(url) {\n init {\n if (bytesRemaining == 0L) {\n responseBodyComplete(trailers = Headers.EMPTY)\n }\n }\n\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n require(byteCount >= 0L) { \"byteCount < 0: $byteCount\" }\n check(!closed) { \"closed\" }\n if (bytesRemaining == 0L) return -1\n\n val read = super.read(sink, minOf(bytesRemaining, byteCount))\n if (read == -1L) {\n carrier.noNewExchanges() // The server didn't supply the promised content length.\n val e = ProtocolException(\"unexpected end of stream\")\n responseBodyComplete(TRAILERS_RESPONSE_BODY_TRUNCATED)\n throw e\n }\n\n bytesRemaining -= read\n if (bytesRemaining == 0L) {\n responseBodyComplete(trailers = Headers.EMPTY)\n }\n return read\n }\n\n override fun close() {\n if (closed) return\n\n if (bytesRemaining != 0L &&\n !discard(ExchangeCodec.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)\n ) {\n carrier.noNewExchanges() // Unread bytes remain on the stream.\n respon"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":437,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n require(byteCount >= 0L) { \"byteCount < 0: $byteCount\" }\n check(!closed) { \"closed\" }\n if (bytesRemaining == 0L) return -1\n\n val read = super.read(sink, minOf(bytesRemaining, byteCount))\n if (read == -1L) {\n carrier.noNewExchanges() // The server didn't supply the promised content length.\n val e = ProtocolException(\"unexpected end of stream\")\n responseBodyComplete(TRAILERS_RESPONSE_BODY_TRUNCATED)\n throw e\n }\n\n bytesRemaining -= read\n if (bytesRemaining == 0L) {\n responseBodyComplete(trailers = Headers.EMPTY)\n }\n return read\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":460,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n if (closed) return\n\n if (bytesRemaining != 0L &&\n !discard(ExchangeCodec.DISCARD_STREAM_TIMEOUT_MILLIS, MILLISECONDS)\n ) {\n carrier.noNewExchanges() // Unread bytes remain on the stream.\n responseBodyComplete(TRAILERS_RESPONSE_BODY_TRUNCATED)\n }\n\n closed = true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http1/Http1ExchangeCodec.kt","line":481,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n require(byteCount >= 0L) { \"byteCount < 0: $byteCount\" }\n check(!closed) { \"closed\" }\n if (!hasMoreChunks) return -1\n\n if (bytesRemainingInChunk == 0L || bytesRemainingInChunk == NO_CHUNK_YET) {\n readChunkSize()\n if (!hasMoreChunks) return -1\n }\n\n val read = super.read(sink, minOf(byteCount, bytesRemainingInChunk))\n if (read == -1L) {\n carrier.noNewExchanges() // The server didn't supply the promised chunk length.\n val e = ProtocolException(\"unexpected end of stream\")\n responseBodyComplete(TRAILERS_RESPONSE_BODY_TRUNCATED)\n throw e\n }\n bytesRemainingInChunk -= read\n return read\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":19,"symbol":"ErrorCode","kind":"enum","lang":"kotlin","doc":"http://tools.ietf.org/html/draft-ietf-httpbis-http2-17#section-7","code":"enum class ErrorCode constructor(\n val httpCode: Int,\n) {\n /** Not an error! */\n NO_ERROR(0),\n\n PROTOCOL_ERROR(1),\n\n INTERNAL_ERROR(2),\n\n FLOW_CONTROL_ERROR(3),\n\n SETTINGS_TIMEOUT(4),\n\n STREAM_CLOSED(5),\n\n FRAME_SIZE_ERROR(6),\n\n REFUSED_STREAM(7),\n\n CANCEL(8),\n\n COMPRESSION_ERROR(9),\n\n CONNECT_ERROR(0xa),\n\n ENHANCE_YOUR_CALM(0xb),\n\n INADEQUATE_SECURITY(0xc),\n\n HTTP_1_1_REQUIRED(0xd),\n ;\n\n companion object {\n fun fromHttp2(code: Int): ErrorCode? = values().find { it.httpCode == code }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":23,"symbol":"NO_ERROR","kind":"enum_member","lang":"kotlin","doc":"Not an error!","code":"NO_ERROR(0)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":25,"symbol":"PROTOCOL_ERROR","kind":"enum_member","lang":"kotlin","code":"PROTOCOL_ERROR(1)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":27,"symbol":"INTERNAL_ERROR","kind":"enum_member","lang":"kotlin","code":"INTERNAL_ERROR(2)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":29,"symbol":"FLOW_CONTROL_ERROR","kind":"enum_member","lang":"kotlin","code":"FLOW_CONTROL_ERROR(3)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":31,"symbol":"SETTINGS_TIMEOUT","kind":"enum_member","lang":"kotlin","code":"SETTINGS_TIMEOUT(4)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":33,"symbol":"STREAM_CLOSED","kind":"enum_member","lang":"kotlin","code":"STREAM_CLOSED(5)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":35,"symbol":"FRAME_SIZE_ERROR","kind":"enum_member","lang":"kotlin","code":"FRAME_SIZE_ERROR(6)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":37,"symbol":"REFUSED_STREAM","kind":"enum_member","lang":"kotlin","code":"REFUSED_STREAM(7)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":39,"symbol":"CANCEL","kind":"enum_member","lang":"kotlin","code":"CANCEL(8)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":41,"symbol":"COMPRESSION_ERROR","kind":"enum_member","lang":"kotlin","code":"COMPRESSION_ERROR(9)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":43,"symbol":"CONNECT_ERROR","kind":"enum_member","lang":"kotlin","code":"CONNECT_ERROR(0xa)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":45,"symbol":"ENHANCE_YOUR_CALM","kind":"enum_member","lang":"kotlin","code":"ENHANCE_YOUR_CALM(0xb)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":47,"symbol":"INADEQUATE_SECURITY","kind":"enum_member","lang":"kotlin","code":"INADEQUATE_SECURITY(0xc)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":49,"symbol":"HTTP_1_1_REQUIRED","kind":"enum_member","lang":"kotlin","code":"HTTP_1_1_REQUIRED(0xd)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/ErrorCode.kt","line":53,"symbol":"fromHttp2","kind":"function","lang":"kotlin","code":"fun fromHttp2(code: Int): ErrorCode? = values().find { it.httpCode == code }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/FlowControlListener.kt","line":20,"symbol":"FlowControlListener","kind":"interface","lang":"kotlin","code":"interface FlowControlListener {\n /**\n * Notification that the receiving stream flow control window has changed.\n * [WindowCounter] generally carries the client view of total and acked bytes.\n */\n fun receivingStreamWindowChanged(\n streamId: Int,\n windowCounter: WindowCounter,\n bufferSize: Long,\n )\n\n /**\n * Notification that the receiving connection flow control window has changed.\n * [WindowCounter] generally carries the client view of total and acked bytes.\n */\n fun receivingConnectionWindowChanged(windowCounter: WindowCounter)\n\n /** Noop implementation */\n object None : FlowControlListener {\n override fun receivingStreamWindowChanged(\n streamId: Int,\n windowCounter: WindowCounter,\n bufferSize: Long,\n ) {\n }\n\n override fun receivingConnectionWindowChanged(windowCounter: WindowCounter) {\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/FlowControlListener.kt","line":25,"symbol":"receivingStreamWindowChanged","kind":"function","lang":"kotlin","doc":"Notification that the receiving stream flow control window has changed. [WindowCounter] generally carries the client view of total and acked bytes.","code":"fun receivingStreamWindowChanged(\n streamId: Int,\n windowCounter: WindowCounter,\n bufferSize: Long,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/FlowControlListener.kt","line":35,"symbol":"receivingConnectionWindowChanged","kind":"function","lang":"kotlin","doc":"Notification that the receiving connection flow control window has changed. [WindowCounter] generally carries the client view of total and acked bytes.","code":"fun receivingConnectionWindowChanged(windowCounter: WindowCounter)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/FlowControlListener.kt","line":38,"symbol":"None","kind":"object","lang":"kotlin","doc":"Noop implementation","code":"object None : FlowControlListener {\n override fun receivingStreamWindowChanged(\n streamId: Int,\n windowCounter: WindowCounter,\n bufferSize: Long,\n ) {\n }\n\n override fun receivingConnectionWindowChanged(windowCounter: WindowCounter) {\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/FlowControlListener.kt","line":39,"symbol":"receivingStreamWindowChanged","kind":"function","lang":"kotlin","code":"override fun receivingStreamWindowChanged(\n streamId: Int,\n windowCounter: WindowCounter,\n bufferSize: Long,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/FlowControlListener.kt","line":46,"symbol":"receivingConnectionWindowChanged","kind":"function","lang":"kotlin","code":"override fun receivingConnectionWindowChanged(windowCounter: WindowCounter) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Header.kt","line":22,"symbol":"Header","kind":"class","lang":"kotlin","doc":"HTTP header: the name is an ASCII string, but the value can be UTF-8.","code":"data class Header(\n /** Name in case-insensitive ASCII encoding. */\n @JvmField val name: ByteString,\n /** Value in UTF-8 encoding. */\n @JvmField val value: ByteString,\n) {\n @JvmField val hpackSize = 32 + name.size + value.size\n\n // TODO: search for toLowerCase and consider moving logic here.\n constructor(name: String, value: String) : this(name.encodeUtf8(), value.encodeUtf8())\n\n constructor(name: ByteString, value: String) : this(name, value.encodeUtf8())\n\n override fun toString(): String = \"${name.utf8()}: ${value.utf8()}\"\n\n companion object {\n // Special header names defined in HTTP/2 spec.\n @JvmField val PSEUDO_PREFIX: ByteString = \":\".encodeUtf8()\n\n const val RESPONSE_STATUS_UTF8 = \":status\"\n const val TARGET_METHOD_UTF8 = \":method\"\n const val TARGET_PATH_UTF8 = \":path\"\n const val TARGET_SCHEME_UTF8 = \":scheme\"\n const val TARGET_AUTHORITY_UTF8 = \":authority\"\n\n @JvmField val RESPONSE_STATUS: ByteString = RESPONSE_STATUS_UTF8.encodeUtf8()\n\n @JvmField val TARGET_METHOD: ByteString = TARGET_METHOD_UTF8.encodeUtf8()\n\n @JvmField val TARGET_PATH: ByteString = TARGET_PATH_UTF8.encodeUtf8()\n\n @JvmField val TARGET_SCHEME: ByteString = TARGET_SC"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Header.kt","line":35,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"${name.utf8()}: ${value.utf8()}\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":43,"symbol":"Hpack","kind":"object","lang":"kotlin","doc":"http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12 This implementation uses an array for the dynamic table and a list for indexed entries. Dynamic entries are added to the array, starting in the last position moving forward. When the array fills, it is doubled.","code":"@Suppress(\"NAME_SHADOWING\")\nobject Hpack {\n private const val PREFIX_4_BITS = 0x0f\n private const val PREFIX_5_BITS = 0x1f\n private const val PREFIX_6_BITS = 0x3f\n private const val PREFIX_7_BITS = 0x7f\n\n private const val SETTINGS_HEADER_TABLE_SIZE = 4_096\n\n /**\n * The decoder has ultimate control of the maximum size of the dynamic table but we can choose\n * to use less. We'll put a cap at 16K. This is arbitrary but should be enough for most purposes.\n */\n private const val SETTINGS_HEADER_TABLE_SIZE_LIMIT = 16_384\n\n val STATIC_HEADER_TABLE =\n arrayOf(\n Header(TARGET_AUTHORITY, \"\"),\n Header(TARGET_METHOD, \"GET\"),\n Header(TARGET_METHOD, \"POST\"),\n Header(TARGET_PATH, \"/\"),\n Header(TARGET_PATH, \"/index.html\"),\n Header(TARGET_SCHEME, \"http\"),\n Header(TARGET_SCHEME, \"https\"),\n Header(RESPONSE_STATUS, \"200\"),\n Header(RESPONSE_STATUS, \"204\"),\n Header(RESPONSE_STATUS, \"206\"),\n Header(RESPONSE_STATUS, \"304\"),\n Header(RESPONSE_STATUS, \"400\"),\n Header(RESPONSE_STATUS, \"404\"),\n Header(RESPONSE_STATUS, \"500\"),\n Header(\"accept-charset\", \"\"),\n Header(\"accept-encoding\", \"gzip, deflate\"),\n Header("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":147,"symbol":"getAndResetHeaderList","kind":"function","lang":"kotlin","code":"fun getAndResetHeaderList(): List
{\n val result = headerList.toList()\n headerList.clear()\n headerListByteCount = 0L\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":154,"symbol":"maxDynamicTableByteCount","kind":"function","lang":"kotlin","code":"fun maxDynamicTableByteCount(): Int = maxDynamicTableByteCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":156,"symbol":"adjustDynamicTableByteCount","kind":"function","lang":"kotlin","code":"private fun adjustDynamicTableByteCount() {\n if (maxDynamicTableByteCount < dynamicTableByteCount) {\n if (maxDynamicTableByteCount == 0) {\n clearDynamicTable()\n } else {\n evictToRecoverBytes(dynamicTableByteCount - maxDynamicTableByteCount)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":166,"symbol":"clearDynamicTable","kind":"function","lang":"kotlin","code":"private fun clearDynamicTable() {\n dynamicTable.fill(null)\n nextHeaderIndex = dynamicTable.size - 1\n headerCount = 0\n dynamicTableByteCount = 0\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":174,"symbol":"evictToRecoverBytes","kind":"function","lang":"kotlin","doc":"Returns the count of entries evicted.","code":"private fun evictToRecoverBytes(bytesToRecover: Int): Int {\n var bytesToRecover = bytesToRecover\n var entriesToEvict = 0\n if (bytesToRecover > 0) {\n // determine how many headers need to be evicted.\n var j = dynamicTable.size - 1\n while (j >= nextHeaderIndex && bytesToRecover > 0) {\n val toEvict = dynamicTable[j]!!\n bytesToRecover -= toEvict.hpackSize\n dynamicTableByteCount -= toEvict.hpackSize\n headerCount--\n entriesToEvict++\n j--\n }\n System.arraycopy(\n dynamicTable,\n nextHeaderIndex + 1,\n dynamicTable,\n nextHeaderIndex + 1 + entriesToEvict,\n headerCount,\n )\n nextHeaderIndex += entriesToEvict\n }\n return entriesToEvict\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":205,"symbol":"readHeaders","kind":"function","lang":"kotlin","doc":"Read `byteCount` bytes of headers from the source stream. This implementation does not propagate the never indexed flag of a header.","code":"fun readHeaders() {\n while (!source.exhausted()) {\n val b = source.readByte() and 0xff\n when {\n b == 0x80 -> {\n // 10000000\n throw IOException(\"index == 0\")\n }\n\n b and 0x80 == 0x80 -> {\n // 1NNNNNNN\n val index = readInt(b, PREFIX_7_BITS)\n readIndexedHeader(index - 1)\n }\n\n b == 0x40 -> {\n // 01000000\n readLiteralHeaderWithIncrementalIndexingNewName()\n }\n\n b and 0x40 == 0x40 -> {\n // 01NNNNNN\n val index = readInt(b, PREFIX_6_BITS)\n readLiteralHeaderWithIncrementalIndexingIndexedName(index - 1)\n }\n\n b and 0x20 == 0x20 -> {\n // 001NNNNN\n maxDynamicTableByteCount = readInt(b, PREFIX_5_BITS)\n if (maxDynamicTableByteCount < 0 || maxDynamicTableByteCount > headerTableSizeSetting) {\n throw IOException(\"Invalid dynamic table size update $maxDynamicTableByteCount\")\n }\n adjustDynamicTableByteCount()\n }\n\n b == 0x10 || b == 0 -> {\n /"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":255,"symbol":"readIndexedHeader","kind":"function","lang":"kotlin","code":"private fun readIndexedHeader(index: Int) {\n if (isStaticHeader(index)) {\n val staticEntry = STATIC_HEADER_TABLE[index]\n addHeader(staticEntry)\n } else {\n val dynamicTableIndex = dynamicTableIndex(index - STATIC_HEADER_TABLE.size)\n if (dynamicTableIndex < 0 || dynamicTableIndex >= dynamicTable.size) {\n throw IOException(\"Header index too large ${index + 1}\")\n }\n addHeader(dynamicTable[dynamicTableIndex]!!)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":269,"symbol":"dynamicTableIndex","kind":"function","lang":"kotlin","doc":"referencedHeaders is relative to nextHeaderIndex + 1.","code":"private fun dynamicTableIndex(index: Int): Int = nextHeaderIndex + 1 + index"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":272,"symbol":"readLiteralHeaderWithoutIndexingIndexedName","kind":"function","lang":"kotlin","code":"private fun readLiteralHeaderWithoutIndexingIndexedName(index: Int) {\n val name = getName(index)\n val value = readByteString()\n addHeader(Header(name, value))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":279,"symbol":"readLiteralHeaderWithoutIndexingNewName","kind":"function","lang":"kotlin","code":"private fun readLiteralHeaderWithoutIndexingNewName() {\n val name = checkLowercase(readByteString())\n val value = readByteString()\n addHeader(Header(name, value))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":286,"symbol":"readLiteralHeaderWithIncrementalIndexingIndexedName","kind":"function","lang":"kotlin","code":"private fun readLiteralHeaderWithIncrementalIndexingIndexedName(nameIndex: Int) {\n val name = getName(nameIndex)\n val value = readByteString()\n insertIntoDynamicTable(-1, Header(name, value))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":293,"symbol":"readLiteralHeaderWithIncrementalIndexingNewName","kind":"function","lang":"kotlin","code":"private fun readLiteralHeaderWithIncrementalIndexingNewName() {\n val name = checkLowercase(readByteString())\n val value = readByteString()\n insertIntoDynamicTable(-1, Header(name, value))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":300,"symbol":"getName","kind":"function","lang":"kotlin","code":"private fun getName(index: Int): ByteString =\n if (isStaticHeader(index)) {\n STATIC_HEADER_TABLE[index].name\n } else {\n val dynamicTableIndex = dynamicTableIndex(index - STATIC_HEADER_TABLE.size)\n if (dynamicTableIndex < 0 || dynamicTableIndex >= dynamicTable.size) {\n throw IOException(\"Header index too large ${index + 1}\")\n }\n\n dynamicTable[dynamicTableIndex]!!.name\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":312,"symbol":"isStaticHeader","kind":"function","lang":"kotlin","code":"private fun isStaticHeader(index: Int): Boolean = index >= 0 && index <= STATIC_HEADER_TABLE.size - 1"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":315,"symbol":"insertIntoDynamicTable","kind":"function","lang":"kotlin","doc":"index == -1 when new.","code":"private fun insertIntoDynamicTable(\n index: Int,\n entry: Header,\n ) {\n var index = index\n addHeader(entry)\n\n var delta = entry.hpackSize\n if (index != -1) { // Index -1 == new header.\n delta -= dynamicTable[dynamicTableIndex(index)]!!.hpackSize\n }\n\n // if the new or replacement header is too big, drop all entries.\n if (delta > maxDynamicTableByteCount) {\n clearDynamicTable()\n return\n }\n\n // Evict headers to the required length.\n val bytesToRecover = dynamicTableByteCount + delta - maxDynamicTableByteCount\n val entriesEvicted = evictToRecoverBytes(bytesToRecover)\n\n if (index == -1) { // Adding a value to the dynamic table.\n if (headerCount + 1 > dynamicTable.size) { // Need to grow the dynamic table.\n val doubled = arrayOfNulls
(dynamicTable.size * 2)\n System.arraycopy(dynamicTable, 0, doubled, dynamicTable.size, dynamicTable.size)\n nextHeaderIndex = dynamicTable.size - 1\n dynamicTable = doubled\n }\n index = nextHeaderIndex--\n dynamicTable[index] = entry\n header"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":354,"symbol":"readByte","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readByte(): Int = source.readByte() and 0xff"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":357,"symbol":"readInt","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun readInt(\n firstByte: Int,\n prefixMask: Int,\n ): Int {\n val prefix = firstByte and prefixMask\n if (prefix < prefixMask) {\n return prefix // This was a single byte value.\n }\n\n // This is a multibyte value. Read 7 bits at a time.\n var result = prefixMask.toLong()\n var shift = 0\n var byteCount = 0\n while (true) {\n // An Int.MAX_VALUE payload needs at most 5 continuation bytes after the prefix.\n if (byteCount == 5) {\n throw IOException(\"HPACK integer overflow\")\n }\n val b = readByte()\n byteCount++\n val increment = (b and 0x7f).toLong() shl shift\n if (increment > Int.MAX_VALUE.toLong() - result) {\n throw IOException(\"HPACK integer overflow\")\n }\n result += increment\n if (b and 0x80 == 0) break\n shift += 7\n }\n return result.toInt()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":390,"symbol":"readByteString","kind":"function","lang":"kotlin","doc":"Reads a potentially Huffman encoded byte string.","code":"@Throws(IOException::class)\n fun readByteString(): ByteString {\n val firstByte = readByte()\n val huffmanDecode = firstByte and 0x80 == 0x80 // 1NNNNNNN\n val length = readInt(firstByte, PREFIX_7_BITS).toLong()\n\n // If the compressed or decompressed length exceeds the limit, don't even bother.\n if (headerListByteCount + length > HEADER_LIMIT) {\n throw IOException(\"header byte count limit of $HEADER_LIMIT exceeded\")\n }\n\n return if (huffmanDecode) {\n val decodeBuffer = Buffer()\n Huffman.decode(source, length, decodeBuffer)\n decodeBuffer.readByteString()\n } else {\n source.readByteString(length)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":410,"symbol":"addHeader","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun addHeader(header: Header) {\n headerList.add(header)\n\n val headerSize = header.name.size + header.value.size\n val newHeaderListSize = headerListByteCount + headerSize\n headerListByteCount = newHeaderListSize\n if (newHeaderListSize > HEADER_LIMIT) {\n throw IOException(\"header byte count limit of $HEADER_LIMIT exceeded\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":423,"symbol":"nameToFirstIndex","kind":"function","lang":"kotlin","code":"private fun nameToFirstIndex(): Map {\n val result = LinkedHashMap(STATIC_HEADER_TABLE.size, 1.0F)\n for (i in STATIC_HEADER_TABLE.indices) {\n if (!result.containsKey(STATIC_HEADER_TABLE[i].name)) {\n result[STATIC_HEADER_TABLE[i].name] = i\n }\n }\n return result.unmodifiable()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":459,"symbol":"clearDynamicTable","kind":"function","lang":"kotlin","code":"private fun clearDynamicTable() {\n dynamicTable.fill(null)\n nextHeaderIndex = dynamicTable.size - 1\n headerCount = 0\n dynamicTableByteCount = 0\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":467,"symbol":"evictToRecoverBytes","kind":"function","lang":"kotlin","doc":"Returns the count of entries evicted.","code":"private fun evictToRecoverBytes(bytesToRecover: Int): Int {\n var bytesToRecover = bytesToRecover\n var entriesToEvict = 0\n if (bytesToRecover > 0) {\n // determine how many headers need to be evicted.\n var j = dynamicTable.size - 1\n while (j >= nextHeaderIndex && bytesToRecover > 0) {\n bytesToRecover -= dynamicTable[j]!!.hpackSize\n dynamicTableByteCount -= dynamicTable[j]!!.hpackSize\n headerCount--\n entriesToEvict++\n j--\n }\n System.arraycopy(\n dynamicTable,\n nextHeaderIndex + 1,\n dynamicTable,\n nextHeaderIndex + 1 + entriesToEvict,\n headerCount,\n )\n Arrays.fill(dynamicTable, nextHeaderIndex + 1, nextHeaderIndex + 1 + entriesToEvict, null)\n nextHeaderIndex += entriesToEvict\n }\n return entriesToEvict\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":493,"symbol":"insertIntoDynamicTable","kind":"function","lang":"kotlin","code":"private fun insertIntoDynamicTable(entry: Header) {\n val delta = entry.hpackSize\n\n // if the new or replacement header is too big, drop all entries.\n if (delta > maxDynamicTableByteCount) {\n clearDynamicTable()\n return\n }\n\n // Evict headers to the required length.\n val bytesToRecover = dynamicTableByteCount + delta - maxDynamicTableByteCount\n evictToRecoverBytes(bytesToRecover)\n\n if (headerCount + 1 > dynamicTable.size) { // Need to grow the dynamic table.\n val doubled = arrayOfNulls
(dynamicTable.size * 2)\n System.arraycopy(dynamicTable, 0, doubled, dynamicTable.size, dynamicTable.size)\n nextHeaderIndex = dynamicTable.size - 1\n dynamicTable = doubled\n }\n val index = nextHeaderIndex--\n dynamicTable[index] = entry\n headerCount++\n dynamicTableByteCount += delta\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":523,"symbol":"writeHeaders","kind":"function","lang":"kotlin","doc":"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","code":"@Throws(IOException::class)\n fun writeHeaders(headerBlock: List
) {\n if (emitDynamicTableSizeUpdate) {\n if (smallestHeaderTableSizeSetting < maxDynamicTableByteCount) {\n // Multiple dynamic table size updates!\n writeInt(smallestHeaderTableSizeSetting, PREFIX_5_BITS, 0x20)\n }\n emitDynamicTableSizeUpdate = false\n smallestHeaderTableSizeSetting = Integer.MAX_VALUE\n writeInt(maxDynamicTableByteCount, PREFIX_5_BITS, 0x20)\n }\n\n for (i in 0 until headerBlock.size) {\n val header = headerBlock[i]\n val name = header.name.toAsciiLowercase()\n val value = header.value\n var headerIndex = -1\n var headerNameIndex = -1\n\n val staticIndex = NAME_TO_FIRST_INDEX[name]\n if (staticIndex != null) {\n headerNameIndex = staticIndex + 1\n if (headerNameIndex in 2..7) {\n // Only search a subset of the static header table. Most entries have an empty value, so\n // it's unnecessary to waste cycles looking at them. This check is built on the\n // observation that the header entries we care about "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":603,"symbol":"writeInt","kind":"function","lang":"kotlin","doc":"http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#section-4.1.1","code":"fun writeInt(\n value: Int,\n prefixMask: Int,\n bits: Int,\n ) {\n var value = value\n // Write the raw value for a single byte value.\n if (value < prefixMask) {\n out.writeByte(bits or value)\n return\n }\n\n // Write the mask to start a multibyte value.\n out.writeByte(bits or prefixMask)\n value -= prefixMask\n\n // Write 7 bits at a time 'til we're done.\n while (value >= 0x80) {\n val b = value and 0x7f\n out.writeByte(b or 0x80)\n value = value ushr 7\n }\n out.writeByte(value)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":628,"symbol":"writeByteString","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun writeByteString(data: ByteString) {\n if (useCompression && Huffman.encodedLength(data) < data.size) {\n val huffmanBuffer = Buffer()\n Huffman.encode(data, huffmanBuffer)\n val huffmanBytes = huffmanBuffer.readByteString()\n writeInt(huffmanBytes.size, PREFIX_7_BITS, 0x80)\n out.write(huffmanBytes)\n } else {\n writeInt(data.size, PREFIX_7_BITS, 0)\n out.write(data)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":642,"symbol":"resizeHeaderTable","kind":"function","lang":"kotlin","code":"fun resizeHeaderTable(headerTableSizeSetting: Int) {\n this.headerTableSizeSetting = headerTableSizeSetting\n val effectiveHeaderTableSize = minOf(headerTableSizeSetting, SETTINGS_HEADER_TABLE_SIZE_LIMIT)\n\n if (maxDynamicTableByteCount == effectiveHeaderTableSize) return // No change.\n\n if (effectiveHeaderTableSize < maxDynamicTableByteCount) {\n smallestHeaderTableSizeSetting =\n minOf(smallestHeaderTableSizeSetting, effectiveHeaderTableSize)\n }\n emitDynamicTableSizeUpdate = true\n maxDynamicTableByteCount = effectiveHeaderTableSize\n adjustDynamicTableByteCount()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":657,"symbol":"adjustDynamicTableByteCount","kind":"function","lang":"kotlin","code":"private fun adjustDynamicTableByteCount() {\n if (maxDynamicTableByteCount < dynamicTableByteCount) {\n if (maxDynamicTableByteCount == 0) {\n clearDynamicTable()\n } else {\n evictToRecoverBytes(dynamicTableByteCount - maxDynamicTableByteCount)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Hpack.kt","line":672,"symbol":"checkLowercase","kind":"function","lang":"kotlin","doc":"An HTTP/2 response cannot contain uppercase header characters and must be treated as malformed.","code":"@Throws(IOException::class)\n fun checkLowercase(name: ByteString): ByteString {\n for (i in 0 until name.size) {\n if (name[i] in 'A'.code.toByte()..'Z'.code.toByte()) {\n throw IOException(\"PROTOCOL_ERROR response malformed: mixed case name: ${name.utf8()}\")\n }\n }\n return name\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2.kt","line":21,"symbol":"Http2","kind":"object","lang":"kotlin","code":"object Http2 {\n @JvmField\n val CONNECTION_PREFACE = \"PRI * HTTP/2.0\\r\\n\\r\\nSM\\r\\n\\r\\n\".encodeUtf8()\n\n /** The initial max frame size, applied independently writing to, or reading from the peer. */\n const val INITIAL_MAX_FRAME_SIZE = 0x4000 // 16384\n\n const val TYPE_DATA = 0x0\n const val TYPE_HEADERS = 0x1\n const val TYPE_PRIORITY = 0x2\n const val TYPE_RST_STREAM = 0x3\n const val TYPE_SETTINGS = 0x4\n const val TYPE_PUSH_PROMISE = 0x5\n const val TYPE_PING = 0x6\n const val TYPE_GOAWAY = 0x7\n const val TYPE_WINDOW_UPDATE = 0x8\n const val TYPE_CONTINUATION = 0x9\n\n const val FLAG_NONE = 0x0\n const val FLAG_ACK = 0x1 // Used for settings and ping.\n const val FLAG_END_STREAM = 0x1 // Used for headers and data.\n const val FLAG_END_HEADERS = 0x4 // Used for headers and continuation.\n const val FLAG_END_PUSH_PROMISE = 0x4\n const val FLAG_PADDED = 0x8 // Used for headers and data.\n const val FLAG_PRIORITY = 0x20 // Used for headers.\n const val FLAG_COMPRESSED = 0x20 // Used for data.\n\n /** Lookup table for valid frame types. */\n private val FRAME_NAMES =\n arrayOf(\n \"DATA\",\n \"HEADERS\",\n \"PRIORITY\",\n \"RST_STREAM\",\n \"SETTINGS\",\n \"PUSH_PROMI"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2.kt","line":118,"symbol":"frameLog","kind":"function","lang":"kotlin","doc":"For example, the following would indicate a HEAD request sent from the client. ``` `<< 0x0000000f 12 HEADERS END_HEADERS|END_STREAM ```","code":"fun frameLog(\n inbound: Boolean,\n streamId: Int,\n length: Int,\n type: Int,\n flags: Int,\n ): String {\n val formattedType = formattedType(type)\n val formattedFlags = formatFlags(type, flags)\n val direction = if (inbound) \"<<\" else \">>\"\n return format(\n \"%s 0x%08x %5d %-13s %s\",\n direction,\n streamId,\n length,\n formattedType,\n formattedFlags,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2.kt","line":142,"symbol":"frameLogWindowUpdate","kind":"function","lang":"kotlin","doc":"Returns a human-readable representation of a `WINDOW_UPDATE` frame. This frame includes the window size increment instead of flags.","code":"fun frameLogWindowUpdate(\n inbound: Boolean,\n streamId: Int,\n length: Int,\n windowSizeIncrement: Long,\n ): String {\n val formattedType = formattedType(TYPE_WINDOW_UPDATE)\n val direction = if (inbound) \"<<\" else \">>\"\n return format(\n \"%s 0x%08x %5d %-13s %d\",\n direction,\n streamId,\n length,\n formattedType,\n windowSizeIncrement,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2.kt","line":160,"symbol":"formattedType","kind":"function","lang":"kotlin","code":"internal fun formattedType(type: Int): String = if (type < FRAME_NAMES.size) FRAME_NAMES[type] else format(\"0x%02x\", type)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2.kt","line":166,"symbol":"formatFlags","kind":"function","lang":"kotlin","doc":"Looks up valid string representing flags from the table. Invalid combinations are represented in binary.","code":"fun formatFlags(\n type: Int,\n flags: Int,\n ): String {\n if (flags == 0) return \"\"\n when (type) {\n // Special case types that have 0 or 1 flag.\n TYPE_SETTINGS, TYPE_PING -> return if (flags == FLAG_ACK) \"ACK\" else BINARY[flags]\n\n TYPE_PRIORITY, TYPE_RST_STREAM, TYPE_GOAWAY, TYPE_WINDOW_UPDATE -> return BINARY[flags]\n }\n val result = if (flags < FLAGS.size) FLAGS[flags]!! else BINARY[flags]\n // Special case types that have overlap flag values.\n return when {\n type == TYPE_PUSH_PROMISE && flags and FLAG_END_PUSH_PROMISE != 0 -> {\n result.replace(\"HEADERS\", \"PUSH_PROMISE\") // TODO: Avoid allocation.\n }\n\n type == TYPE_DATA && flags and FLAG_COMPRESSED != 0 -> {\n result.replace(\"PRIORITY\", \"COMPRESSED\") // TODO: Avoid allocation.\n }\n\n else -> {\n result\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":53,"symbol":"Http2Connection","kind":"class","lang":"kotlin","doc":"data. Many methods in this API are **synchronous:** the call is completed before the method returns. This is typical for Java but atypical for HTTP/2. This is motivated by exception transparency: an [IOException] that was triggered by a certain caller can be caught and handled by that caller.","code":"class Http2Connection internal constructor(\n builder: Builder,\n) : Closeable,\n Lockable {\n // Internal state of this connection is guarded by 'lock'. No blocking operations may be\n // performed while holding this lock!\n //\n // Socket writes are guarded by frameWriter.\n //\n // Socket reads are unguarded but are only made by the reader thread.\n //\n // Certain operations (like SYN_STREAM) need to synchronize on both the frameWriter (to do\n // blocking I/O) and this (to create streams). Such operations must synchronize on 'this' last.\n // This ensures that we never wait for a blocking operation while holding 'this'.\n\n /** True if this peer initiated the connection. */\n internal val client: Boolean = builder.client\n\n /** User code to run in response to incoming streams or settings. */\n internal val listener: Listener = builder.listener\n internal val streams = mutableMapOf()\n internal val connectionName: String = builder.connectionName\n internal var lastGoodStreamId = 0\n\n /** http://tools.ietf.org/html/draft-ietf-httpbis-http2-17#section-5.1.1 */\n internal var nextStreamId = if (builder.client) 3 else 2\n\n private var isShutdown = false\n\n /** For s"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":174,"symbol":"openStreamCount","kind":"function","lang":"kotlin","doc":"Returns the number of [open streams][Http2Stream.isOpen] on this connection.","code":"fun openStreamCount(): Int = withLock { streams.size }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":176,"symbol":"getStream","kind":"function","lang":"kotlin","code":"fun getStream(id: Int): Http2Stream? = withLock { streams[id] }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":178,"symbol":"removeStream","kind":"function","lang":"kotlin","code":"internal fun removeStream(streamId: Int): Http2Stream? {\n withLock {\n val stream = streams.remove(streamId)\n\n // The removed stream may be blocked on a connection-wide window update.\n notifyAll()\n\n return stream\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":189,"symbol":"updateConnectionFlowControl","kind":"function","lang":"kotlin","code":"internal fun updateConnectionFlowControl(read: Long) {\n withLock {\n readBytes.update(total = read)\n val readBytesToAcknowledge = readBytes.unacknowledged\n if (readBytesToAcknowledge >= okHttpSettings.initialWindowSize / 2) {\n writeWindowUpdateLater(0, readBytesToAcknowledge)\n readBytes.update(acknowledged = readBytesToAcknowledge)\n }\n flowControlListener.receivingConnectionWindowChanged(readBytes)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":208,"symbol":"pushStream","kind":"function","lang":"kotlin","doc":"Returns a new server-initiated stream. @param associatedStreamId the stream that triggered the sender to create this stream. @param out true to create an output stream that we can use to send data to the remote peer. Corresponds to `FLAG_FIN`.","code":"@Throws(IOException::class)\n fun pushStream(\n associatedStreamId: Int,\n requestHeaders: List
,\n out: Boolean,\n ): Http2Stream {\n check(!client) { \"Client cannot push requests.\" }\n return newStream(associatedStreamId, requestHeaders, out)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":224,"symbol":"newStream","kind":"function","lang":"kotlin","doc":"Returns a new locally-initiated stream. @param out true to create an output stream that we can use to send data to the remote peer. Corresponds to `FLAG_FIN`.","code":"@Throws(IOException::class)\n fun newStream(\n requestHeaders: List
,\n out: Boolean,\n ): Http2Stream = newStream(0, requestHeaders, out)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":230,"symbol":"newStream","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun newStream(\n associatedStreamId: Int,\n requestHeaders: List
,\n out: Boolean,\n ): Http2Stream {\n val outFinished = !out\n val inFinished = false\n val flushHeaders: Boolean\n val stream: Http2Stream\n val streamId: Int\n\n writer.withLock {\n withLock {\n if (nextStreamId > Int.MAX_VALUE / 2) {\n shutdown(REFUSED_STREAM)\n }\n if (isShutdown) {\n throw ConnectionShutdownException()\n }\n streamId = nextStreamId\n nextStreamId += 2\n stream = Http2Stream(streamId, this, outFinished, inFinished, null)\n flushHeaders = !out ||\n writeBytesTotal >= writeBytesMaximum ||\n stream.writeBytesTotal >= stream.writeBytesMaximum\n if (stream.isOpen) {\n streams[streamId] = stream\n }\n }\n if (associatedStreamId == 0) {\n writer.headers(outFinished, streamId, requestHeaders)\n } else {\n require(!client) { \"client streams shouldn't have associated stream IDs\" }\n // HTTP/2 has a PUSH_PROMISE frame.\n writer.pushPromise(associatedStreamId, streamId, requestHeaders)\n }\n }\n\n if (f"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":276,"symbol":"writeHeaders","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n internal fun writeHeaders(\n streamId: Int,\n outFinished: Boolean,\n alternating: List
,\n ) {\n writer.headers(outFinished, streamId, alternating)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":297,"symbol":"writeData","kind":"function","lang":"kotlin","doc":"`HttpURLConnection` who flushes more bytes to the output stream than the connection's write window will block. Zero [byteCount] writes are not subject to flow control and will not block. The only use case for zero [byteCount] is closing a flushed output stream.","code":"@Throws(IOException::class)\n fun writeData(\n streamId: Int,\n outFinished: Boolean,\n buffer: Buffer?,\n byteCount: Long,\n ) {\n // Empty data frames are not flow-controlled.\n if (byteCount == 0L) {\n writer.data(outFinished, streamId, buffer, 0)\n return\n }\n\n var byteCount = byteCount\n while (byteCount > 0L) {\n var toWrite: Int\n withLock {\n try {\n while (writeBytesTotal >= writeBytesMaximum) {\n // Before blocking, confirm that the stream we're writing is still open. It's possible\n // that the stream has since been closed (such as if this write timed out.)\n if (!streams.containsKey(streamId)) {\n throw IOException(\"stream closed\")\n }\n wait() // Wait until we receive a WINDOW_UPDATE.\n }\n } catch (e: InterruptedException) {\n Thread.currentThread().interrupt() // Retain interrupted status.\n throw InterruptedIOException()\n }\n\n toWrite = minOf(byteCount, writeBytesMaximum - writeBytesTotal).toInt()\n toWrite = minOf(toWrite, writer.maxDataLength())\n writeBytesTotal += toWrite.toLong()\n }\n\n byt"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":338,"symbol":"writeSynResetLater","kind":"function","lang":"kotlin","code":"internal fun writeSynResetLater(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n writerQueue.execute(\"$connectionName[$streamId] writeSynReset\") {\n try {\n writeSynReset(streamId, errorCode)\n } catch (e: IOException) {\n failConnection(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":351,"symbol":"writeSynReset","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n internal fun writeSynReset(\n streamId: Int,\n statusCode: ErrorCode,\n ) {\n writer.rstStream(streamId, statusCode)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":359,"symbol":"writeWindowUpdateLater","kind":"function","lang":"kotlin","code":"internal fun writeWindowUpdateLater(\n streamId: Int,\n unacknowledgedBytesRead: Long,\n ) {\n writerQueue.execute(\"$connectionName[$streamId] windowUpdate\") {\n try {\n writer.windowUpdate(streamId, unacknowledgedBytesRead)\n } catch (e: IOException) {\n failConnection(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":372,"symbol":"writePing","kind":"function","lang":"kotlin","code":"fun writePing(\n reply: Boolean,\n payload1: Int,\n payload2: Int,\n ) {\n try {\n writer.ping(reply, payload1, payload2)\n } catch (e: IOException) {\n failConnection(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":385,"symbol":"writePingAndAwaitPong","kind":"function","lang":"kotlin","doc":"For testing: sends a ping and waits for a pong.","code":"@Throws(InterruptedException::class)\n fun writePingAndAwaitPong() {\n writePing()\n awaitPong()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":392,"symbol":"writePing","kind":"function","lang":"kotlin","doc":"For testing: sends a ping to be awaited with [awaitPong].","code":"@Throws(InterruptedException::class)\n fun writePing() {\n withLock {\n awaitPingsSent++\n }\n\n // 0x4f 0x4b 0x6f 0x6b is \"OKok\".\n writePing(false, AWAIT_PING, 0x4f4b6f6b)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":403,"symbol":"awaitPong","kind":"function","lang":"kotlin","doc":"For testing: awaits a pong.","code":"@Throws(InterruptedException::class)\n fun awaitPong() {\n withLock {\n while (awaitPongsReceived < awaitPingsSent) {\n wait()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":412,"symbol":"flush","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun flush() {\n writer.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":422,"symbol":"shutdown","kind":"function","lang":"kotlin","doc":"Degrades this connection such that new streams can neither be created locally, nor accepted from the remote peer. Existing streams are not impacted. This is intended to permit an endpoint to gracefully stop accepting new requests without harming previously established streams.","code":"@Throws(IOException::class)\n fun shutdown(statusCode: ErrorCode) {\n writer.withLock {\n val lastGoodStreamId: Int\n withLock {\n if (isShutdown) {\n return\n }\n isShutdown = true\n lastGoodStreamId = this.lastGoodStreamId\n }\n // TODO: propagate exception message into debugData.\n // TODO: configure a timeout on the reader so that it doesn’t block forever.\n writer.goAway(lastGoodStreamId, statusCode, EMPTY_BYTE_ARRAY)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":443,"symbol":"close","kind":"function","lang":"kotlin","doc":"Closes this connection. This cancels all open streams and unanswered pings. It closes the underlying input and output streams and shuts down internal task queues.","code":"override fun close() {\n close(ErrorCode.NO_ERROR, ErrorCode.CANCEL, null)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":447,"symbol":"close","kind":"function","lang":"kotlin","code":"internal fun close(\n connectionCode: ErrorCode,\n streamCode: ErrorCode,\n cause: IOException?,\n ) {\n assertLockNotHeld()\n\n ignoreIoExceptions {\n shutdown(connectionCode)\n }\n\n var streamsToClose: Array? = null\n withLock {\n if (streams.isNotEmpty()) {\n streamsToClose = streams.values.toTypedArray()\n streams.clear()\n }\n }\n\n streamsToClose?.forEach { stream ->\n ignoreIoExceptions {\n stream.close(streamCode, cause)\n }\n }\n\n // Close the writer to release its resources (such as deflaters).\n ignoreIoExceptions {\n writer.close()\n }\n\n // Cancel the socket to break out the reader thread, which will clean up after itself.\n ignoreIoExceptions {\n socket.cancel()\n }\n\n // Release the threads.\n writerQueue.shutdown()\n pushQueue.shutdown()\n settingsListenerQueue.shutdown()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":488,"symbol":"failConnection","kind":"function","lang":"kotlin","code":"private fun failConnection(e: IOException?) {\n close(ErrorCode.PROTOCOL_ERROR, ErrorCode.PROTOCOL_ERROR, e)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":500,"symbol":"start","kind":"function","lang":"kotlin","doc":"after [Builder.build] for all new connections. @param sendConnectionPreface true to send connection preface frames. This should always be true except for in tests that don't check for a connection preface. @param taskRunner the TaskRunner to use, daemon by default.","code":"@Throws(IOException::class)\n @JvmOverloads\n fun start(sendConnectionPreface: Boolean = true) {\n if (sendConnectionPreface) {\n writer.connectionPreface()\n writer.settings(okHttpSettings)\n val windowSize = okHttpSettings.initialWindowSize\n if (windowSize != DEFAULT_INITIAL_WINDOW_SIZE) {\n writer.windowUpdate(0, (windowSize - DEFAULT_INITIAL_WINDOW_SIZE).toLong())\n }\n }\n // Thread doesn't use client Dispatcher, since it is scoped potentially across clients via\n // ConnectionPool.\n taskRunner.newQueue().execute(name = connectionName, block = readerRunnable)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":517,"symbol":"setSettings","kind":"function","lang":"kotlin","doc":"Merges [settings] into this peer's settings and sends them to the remote peer.","code":"@Throws(IOException::class)\n fun setSettings(settings: Settings) {\n writer.withLock {\n withLock {\n if (isShutdown) {\n throw ConnectionShutdownException()\n }\n okHttpSettings.merge(settings)\n }\n writer.settings(settings)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":530,"symbol":"isHealthy","kind":"function","lang":"kotlin","code":"fun isHealthy(nowNs: Long): Boolean {\n withLock {\n if (isShutdown) return false\n\n // A degraded pong is overdue.\n if (degradedPongsReceived < degradedPingsSent && nowNs >= degradedPongDeadlineNs) return false\n\n return true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":556,"symbol":"sendDegradedPingLater","kind":"function","lang":"kotlin","doc":"long, streams created while we await the pong will reuse broken connections and inevitably fail. If it is too short, slow connections will be marked as failed and extra TCP and TLS handshakes will be required. The deadline is currently hardcoded. We may make this configurable in the future!","code":"internal fun sendDegradedPingLater() {\n withLock {\n if (degradedPongsReceived < degradedPingsSent) return // Already awaiting a degraded pong.\n degradedPingsSent++\n degradedPongDeadlineNs = System.nanoTime() + DEGRADED_PONG_TIMEOUT_NS\n }\n writerQueue.execute(\"$connectionName ping\") {\n writePing(false, DEGRADED_PING, 0)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":567,"symbol":"Builder","kind":"class","lang":"kotlin","code":"class Builder(\n /** True if this peer initiated the connection; false if this peer accepted the connection. */\n internal var client: Boolean,\n internal val taskRunner: TaskRunner,\n ) {\n internal lateinit var socket: BufferedSocket\n internal lateinit var connectionName: String\n internal var listener = Listener.REFUSE_INCOMING_STREAMS\n internal var pushObserver = PushObserver.CANCEL\n internal var pingIntervalMillis: Int = 0\n internal var flowControlListener: FlowControlListener = FlowControlListener.None\n\n @Throws(IOException::class)\n fun socket(\n socket: BufferedSocket,\n peerName: String,\n ) = apply {\n this.socket = socket\n this.connectionName =\n when {\n client -> \"$okHttpName $peerName\"\n else -> \"MockWebServer $peerName\"\n }\n }\n\n fun listener(listener: Listener) =\n apply {\n this.listener = listener\n }\n\n fun pushObserver(pushObserver: PushObserver) =\n apply {\n this.pushObserver = pushObserver\n }\n\n fun pingIntervalMillis(pingIntervalMillis: Int) =\n apply {\n this.pingIntervalMillis = pingIntervalMillis\n }\n\n fun flowControlListener(fl"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":579,"symbol":"socket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun socket(\n socket: BufferedSocket,\n peerName: String,\n ) = apply {\n this.socket = socket\n this.connectionName =\n when {\n client -> \"$okHttpName $peerName\"\n else -> \"MockWebServer $peerName\"\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":592,"symbol":"listener","kind":"function","lang":"kotlin","code":"fun listener(listener: Listener) =\n apply {\n this.listener = listener\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":597,"symbol":"pushObserver","kind":"function","lang":"kotlin","code":"fun pushObserver(pushObserver: PushObserver) =\n apply {\n this.pushObserver = pushObserver\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":602,"symbol":"pingIntervalMillis","kind":"function","lang":"kotlin","code":"fun pingIntervalMillis(pingIntervalMillis: Int) =\n apply {\n this.pingIntervalMillis = pingIntervalMillis\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":607,"symbol":"flowControlListener","kind":"function","lang":"kotlin","code":"fun flowControlListener(flowControlListener: FlowControlListener) =\n apply {\n this.flowControlListener = flowControlListener\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":612,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): Http2Connection = Http2Connection(this)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":619,"symbol":"ReaderRunnable","kind":"class","lang":"kotlin","doc":"Methods in this class must not lock FrameWriter. If a method needs to write a frame, create an async task to do so.","code":"inner class ReaderRunnable internal constructor(\n internal val reader: Http2Reader,\n ) : Http2Reader.Handler,\n () -> Unit {\n override fun invoke() {\n var connectionErrorCode = ErrorCode.INTERNAL_ERROR\n var streamErrorCode = ErrorCode.INTERNAL_ERROR\n var errorException: IOException? = null\n try {\n reader.readConnectionPreface(this)\n while (reader.nextFrame(false, this)) {\n }\n connectionErrorCode = ErrorCode.NO_ERROR\n streamErrorCode = ErrorCode.CANCEL\n } catch (e: IOException) {\n errorException = e\n connectionErrorCode = ErrorCode.PROTOCOL_ERROR\n streamErrorCode = ErrorCode.PROTOCOL_ERROR\n } finally {\n close(connectionErrorCode, streamErrorCode, errorException)\n reader.closeQuietly()\n }\n }\n\n @Throws(IOException::class)\n override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n if (pushedStream(streamId)) {\n pushDataLater(streamId, source, length, inFinished)\n return\n }\n val dataStream = getStream(streamId)\n if (dataStream == null) {\n writeSynResetLater(st"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":623,"symbol":"invoke","kind":"function","lang":"kotlin","code":"override fun invoke() {\n var connectionErrorCode = ErrorCode.INTERNAL_ERROR\n var streamErrorCode = ErrorCode.INTERNAL_ERROR\n var errorException: IOException? = null\n try {\n reader.readConnectionPreface(this)\n while (reader.nextFrame(false, this)) {\n }\n connectionErrorCode = ErrorCode.NO_ERROR\n streamErrorCode = ErrorCode.CANCEL\n } catch (e: IOException) {\n errorException = e\n connectionErrorCode = ErrorCode.PROTOCOL_ERROR\n streamErrorCode = ErrorCode.PROTOCOL_ERROR\n } finally {\n close(connectionErrorCode, streamErrorCode, errorException)\n reader.closeQuietly()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":643,"symbol":"data","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n if (pushedStream(streamId)) {\n pushDataLater(streamId, source, length, inFinished)\n return\n }\n val dataStream = getStream(streamId)\n if (dataStream == null) {\n writeSynResetLater(streamId, ErrorCode.PROTOCOL_ERROR)\n updateConnectionFlowControl(length.toLong())\n source.skip(length.toLong())\n return\n }\n dataStream.receiveData(source, length)\n if (inFinished) {\n dataStream.receiveHeaders(Headers.EMPTY, true)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":667,"symbol":"headers","kind":"function","lang":"kotlin","code":"override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n if (pushedStream(streamId)) {\n pushHeadersLater(streamId, headerBlock, inFinished)\n return\n }\n val stream: Http2Stream?\n withLock {\n stream = getStream(streamId)\n\n if (stream == null) {\n // If we're shutdown, don't bother with this stream.\n if (isShutdown) return\n\n // If the stream ID is less than the last created ID, assume it's already closed.\n if (streamId <= lastGoodStreamId) return\n\n // If the stream ID is in the client's namespace, assume it's already closed.\n if (streamId % 2 == nextStreamId % 2) return\n\n // Create a stream.\n val headers = headerBlock.toHeaders()\n val newStream = Http2Stream(streamId, this@Http2Connection, false, inFinished, headers)\n lastGoodStreamId = streamId\n streams[streamId] = newStream\n\n // Use a different task queue for each stream because they should be handled in parallel.\n taskRunner.newQueue().execute(\"$connectionName[$streamId] onStream\") {\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":716,"symbol":"rstStream","kind":"function","lang":"kotlin","code":"override fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n if (pushedStream(streamId)) {\n pushResetLater(streamId, errorCode)\n return\n }\n val rstStream = removeStream(streamId)\n rstStream?.receiveRstStream(errorCode)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":728,"symbol":"settings","kind":"function","lang":"kotlin","code":"override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n writerQueue.execute(\"$connectionName applyAndAckSettings\") {\n applyAndAckSettings(clearPrevious, settings)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":750,"symbol":"applyAndAckSettings","kind":"function","lang":"kotlin","doc":"Since we can't ACK settings on the current reader thread (the reader thread can't write) we execute all peer settings logic on the writer thread. This relies on the fact that the writer task queue won't reorder tasks; otherwise settings could be applied in the opposite order than received.","code":"fun applyAndAckSettings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n var delta: Long\n var streamsToNotify: Array?\n var newPeerSettings: Settings\n writer.withLock {\n withLock {\n val previousPeerSettings = peerSettings\n newPeerSettings =\n if (clearPrevious) {\n settings\n } else {\n Settings().apply {\n merge(previousPeerSettings)\n merge(settings)\n }\n }\n\n val peerInitialWindowSize = newPeerSettings.initialWindowSize.toLong()\n delta = peerInitialWindowSize - previousPeerSettings.initialWindowSize.toLong()\n streamsToNotify =\n when {\n delta == 0L || streams.isEmpty() -> null\n\n // No adjustment is necessary.\n else -> streams.values.toTypedArray()\n }\n\n peerSettings = newPeerSettings\n\n settingsListenerQueue.execute(\"$connectionName onSettings\") {\n listener.onSettings(this@Http2Connection, newPeerSettings)\n }\n }\n try {\n writer.applyAndAckSettings(newPeerSettings)\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":801,"symbol":"ackSettings","kind":"function","lang":"kotlin","code":"override fun ackSettings() {\n // TODO: If we don't get this callback after sending settings to the peer, SETTINGS_TIMEOUT.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":805,"symbol":"ping","kind":"function","lang":"kotlin","code":"override fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n ) {\n if (ack) {\n withLock {\n when (payload1) {\n INTERVAL_PING -> {\n intervalPongsReceived++\n }\n\n DEGRADED_PING -> {\n degradedPongsReceived++\n }\n\n AWAIT_PING -> {\n awaitPongsReceived++\n notifyAll()\n }\n\n else -> {\n // Ignore an unexpected pong.\n }\n }\n }\n } else {\n // Send a reply to a client ping if this is a server and vice versa.\n writerQueue.execute(\"$connectionName ping\") {\n writePing(true, payload1, payload2)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":839,"symbol":"goAway","kind":"function","lang":"kotlin","code":"override fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n ) {\n if (debugData.size > 0) {\n // TODO: log the debugData\n }\n\n // Copy the streams first. We don't want to hold a lock when we call receiveRstStream().\n val streamsCopy: Array\n withLock {\n streamsCopy = streams.values.toTypedArray()\n isShutdown = true\n }\n\n // Fail all streams created after the last good stream ID.\n for (http2Stream in streamsCopy) {\n if (http2Stream.id > lastGoodStreamId && http2Stream.isLocallyInitiated) {\n http2Stream.receiveRstStream(REFUSED_STREAM)\n removeStream(http2Stream.id)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":864,"symbol":"windowUpdate","kind":"function","lang":"kotlin","code":"override fun windowUpdate(\n streamId: Int,\n windowSizeIncrement: Long,\n ) {\n if (streamId == 0) {\n withLock {\n writeBytesMaximum += windowSizeIncrement\n notifyAll()\n }\n } else {\n val stream = getStream(streamId)\n if (stream != null) {\n stream.withLock {\n stream.addBytesToWriteWindow(windowSizeIncrement)\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":883,"symbol":"priority","kind":"function","lang":"kotlin","code":"override fun priority(\n streamId: Int,\n streamDependency: Int,\n weight: Int,\n exclusive: Boolean,\n ) {\n // TODO: honor priority.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":892,"symbol":"pushPromise","kind":"function","lang":"kotlin","code":"override fun pushPromise(\n streamId: Int,\n promisedStreamId: Int,\n requestHeaders: List
,\n ) {\n pushRequestLater(promisedStreamId, requestHeaders)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":900,"symbol":"alternateService","kind":"function","lang":"kotlin","code":"override fun alternateService(\n streamId: Int,\n origin: String,\n protocol: ByteString,\n host: String,\n port: Int,\n maxAge: Long,\n ) {\n // TODO: register alternate service.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":913,"symbol":"pushedStream","kind":"function","lang":"kotlin","doc":"Even, positive numbered streams are pushed streams in HTTP/2.","code":"internal fun pushedStream(streamId: Int): Boolean = streamId != 0 && streamId and 1 == 0"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":915,"symbol":"pushRequestLater","kind":"function","lang":"kotlin","code":"internal fun pushRequestLater(\n streamId: Int,\n requestHeaders: List
,\n ) {\n withLock {\n if (streamId in currentPushRequests) {\n writeSynResetLater(streamId, ErrorCode.PROTOCOL_ERROR)\n return\n }\n currentPushRequests.add(streamId)\n }\n pushQueue.execute(\"$connectionName[$streamId] onRequest\") {\n val cancel = pushObserver.onRequest(streamId, requestHeaders)\n ignoreIoExceptions {\n if (cancel) {\n writer.rstStream(streamId, ErrorCode.CANCEL)\n withLock {\n currentPushRequests.remove(streamId)\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":939,"symbol":"pushHeadersLater","kind":"function","lang":"kotlin","code":"internal fun pushHeadersLater(\n streamId: Int,\n requestHeaders: List
,\n inFinished: Boolean,\n ) {\n pushQueue.execute(\"$connectionName[$streamId] onHeaders\") {\n val cancel = pushObserver.onHeaders(streamId, requestHeaders, inFinished)\n ignoreIoExceptions {\n if (cancel) writer.rstStream(streamId, ErrorCode.CANCEL)\n if (cancel || inFinished) {\n withLock {\n currentPushRequests.remove(streamId)\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":961,"symbol":"pushDataLater","kind":"function","lang":"kotlin","doc":"Eagerly reads `byteCount` bytes from the source before launching a background task to process the data. This avoids corrupting the stream.","code":"@Throws(IOException::class)\n internal fun pushDataLater(\n streamId: Int,\n source: BufferedSource,\n byteCount: Int,\n inFinished: Boolean,\n ) {\n val buffer = Buffer()\n source.require(byteCount.toLong()) // Eagerly read the frame before firing client thread.\n source.read(buffer, byteCount.toLong())\n pushQueue.execute(\"$connectionName[$streamId] onData\") {\n ignoreIoExceptions {\n val cancel = pushObserver.onData(streamId, buffer, byteCount, inFinished)\n if (cancel) writer.rstStream(streamId, ErrorCode.CANCEL)\n if (cancel || inFinished) {\n withLock {\n currentPushRequests.remove(streamId)\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":984,"symbol":"pushResetLater","kind":"function","lang":"kotlin","code":"internal fun pushResetLater(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n pushQueue.execute(\"$connectionName[$streamId] onReset\") {\n pushObserver.onReset(streamId, errorCode)\n withLock {\n currentPushRequests.remove(streamId)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":997,"symbol":"Listener","kind":"class","lang":"kotlin","doc":"Listener of streams and settings initiated by the peer.","code":"abstract class Listener {\n /**\n * Handle a new stream from this connection's peer. Implementations should respond by either\n * [replying to the stream][Http2Stream.writeHeaders] or [closing it][Http2Stream.close]. This\n * response does not need to be synchronous.\n *\n * Multiple calls to this method may be made concurrently.\n */\n @Throws(IOException::class)\n abstract fun onStream(stream: Http2Stream)\n\n /**\n * Notification that the connection's peer's settings may have changed to [settings].\n * Implementations should take appropriate action to handle the updated settings.\n *\n * Methods to this method may be made concurrently with [onStream]. But a calls to this method\n * are serialized.\n */\n open fun onSettings(\n connection: Http2Connection,\n settings: Settings,\n ) {}\n\n companion object {\n @JvmField\n val REFUSE_INCOMING_STREAMS: Listener =\n object : Listener() {\n @Throws(IOException::class)\n override fun onStream(stream: Http2Stream) {\n stream.close(REFUSED_STREAM, null)\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":1005,"symbol":"onStream","kind":"function","lang":"kotlin","doc":"Handle a new stream from this connection's peer. Implementations should respond by either [replying to the stream][Http2Stream.writeHeaders] or [closing it][Http2Stream.close]. This response does not need to be synchronous. Multiple calls to this method may be made concurrently.","code":"@Throws(IOException::class)\n abstract fun onStream(stream: Http2Stream)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":1015,"symbol":"onSettings","kind":"function","lang":"kotlin","doc":"Notification that the connection's peer's settings may have changed to [settings]. Implementations should take appropriate action to handle the updated settings. Methods to this method may be made concurrently with [onStream]. But a calls to this method are serialized.","code":"open fun onSettings(\n connection: Http2Connection,\n settings: Settings,\n ) {}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt","line":1024,"symbol":"onStream","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onStream(stream: Http2Stream) {\n stream.close(REFUSED_STREAM, null)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":50,"symbol":"Http2ExchangeCodec","kind":"class","lang":"kotlin","doc":"Encode requests and responses using HTTP/2 frames.","code":"class Http2ExchangeCodec(\n client: OkHttpClient,\n override val carrier: Carrier,\n private val chain: RealInterceptorChain,\n private val http2Connection: Http2Connection,\n) : ExchangeCodec {\n @Volatile private var stream: Http2Stream? = null\n\n private val protocol: Protocol =\n if (Protocol.H2_PRIOR_KNOWLEDGE in client.protocols) {\n Protocol.H2_PRIOR_KNOWLEDGE\n } else {\n Protocol.HTTP_2\n }\n\n @Volatile\n private var canceled = false\n\n override val isResponseComplete: Boolean\n get() = stream?.isSourceComplete == true\n\n override val socket: Socket\n get() = stream!!\n\n override fun createRequestBody(\n request: Request,\n contentLength: Long,\n ): Sink = stream!!.sink\n\n override fun writeRequestHeaders(request: Request) {\n if (stream != null) return\n\n val hasRequestBody = request.body != null\n val requestHeaders = http2HeadersList(request)\n stream = http2Connection.newStream(requestHeaders, hasRequestBody)\n // We may have been asked to cancel while creating the new stream and sending the request\n // headers, but there was still no stream to close.\n if (canceled) {\n stream!!.closeLater(ErrorCode.CANCEL)\n throw IOExcepti"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":74,"symbol":"createRequestBody","kind":"function","lang":"kotlin","code":"override fun createRequestBody(\n request: Request,\n contentLength: Long,\n ): Sink = stream!!.sink"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":79,"symbol":"writeRequestHeaders","kind":"function","lang":"kotlin","code":"override fun writeRequestHeaders(request: Request) {\n if (stream != null) return\n\n val hasRequestBody = request.body != null\n val requestHeaders = http2HeadersList(request)\n stream = http2Connection.newStream(requestHeaders, hasRequestBody)\n // We may have been asked to cancel while creating the new stream and sending the request\n // headers, but there was still no stream to close.\n if (canceled) {\n stream!!.closeLater(ErrorCode.CANCEL)\n throw IOException(\"Canceled\")\n }\n stream!!.readTimeout().timeout(chain.readTimeoutMillis.toLong(), TimeUnit.MILLISECONDS)\n stream!!.writeTimeout().timeout(chain.writeTimeoutMillis.toLong(), TimeUnit.MILLISECONDS)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":95,"symbol":"flushRequest","kind":"function","lang":"kotlin","code":"override fun flushRequest() {\n http2Connection.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":99,"symbol":"finishRequest","kind":"function","lang":"kotlin","code":"override fun finishRequest() {\n stream!!.sink.close()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":103,"symbol":"readResponseHeaders","kind":"function","lang":"kotlin","code":"override fun readResponseHeaders(expectContinue: Boolean): Response.Builder? {\n val stream = stream ?: throw IOException(\"stream wasn't created\")\n val headers = stream.takeHeaders(callerIsIdle = expectContinue)\n val responseBuilder = readHttp2HeadersList(headers, protocol)\n return if (expectContinue && responseBuilder.code == HTTP_CONTINUE) {\n null\n } else {\n responseBuilder\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":114,"symbol":"reportedContentLength","kind":"function","lang":"kotlin","code":"override fun reportedContentLength(response: Response): Long =\n when {\n !response.promisesBody() -> 0L\n else -> response.headersContentLength()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":120,"symbol":"openResponseBodySource","kind":"function","lang":"kotlin","code":"override fun openResponseBodySource(response: Response): Source = stream!!.source"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":122,"symbol":"peekTrailers","kind":"function","lang":"kotlin","code":"override fun peekTrailers(): Headers? = stream!!.peekTrailers()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":124,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n canceled = true\n stream?.closeLater(ErrorCode.CANCEL)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":167,"symbol":"http2HeadersList","kind":"function","lang":"kotlin","code":"fun http2HeadersList(request: Request): List
{\n val headers = request.headers\n val result = ArrayList
(headers.size + 4)\n result.add(Header(TARGET_METHOD, request.method))\n result.add(Header(TARGET_PATH, RequestLine.requestPath(request.url)))\n val host = request.header(\"Host\")\n if (host != null) {\n result.add(Header(TARGET_AUTHORITY, host)) // Optional.\n }\n result.add(Header(TARGET_SCHEME, request.url.scheme))\n\n for (i in 0 until headers.size) {\n // header names must be lowercase.\n val name = headers.name(i).lowercase(Locale.US)\n if (name !in HTTP_2_SKIPPED_REQUEST_HEADERS ||\n name == TE &&\n headers.value(i) == \"trailers\"\n ) {\n result.add(Header(name, headers.value(i)))\n }\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt","line":192,"symbol":"readHttp2HeadersList","kind":"function","lang":"kotlin","doc":"Returns headers for a name value block containing an HTTP/2 response.","code":"fun readHttp2HeadersList(\n headerBlock: Headers,\n protocol: Protocol,\n ): Response.Builder {\n var statusLine: StatusLine? = null\n val headersBuilder = Headers.Builder()\n for (i in 0 until headerBlock.size) {\n val name = headerBlock.name(i)\n val value = headerBlock.value(i)\n if (name == RESPONSE_STATUS_UTF8) {\n statusLine = StatusLine.parse(\"HTTP/1.1 $value\")\n } else if (name !in HTTP_2_SKIPPED_RESPONSE_HEADERS) {\n headersBuilder.addLenient(name, value)\n }\n }\n if (statusLine == null) throw ProtocolException(\"Expected ':status' header not present\")\n\n return Response\n .Builder()\n .protocol(protocol)\n .code(statusLine.code)\n .message(statusLine.message)\n .headers(headersBuilder.build())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":59,"symbol":"Http2Reader","kind":"class","lang":"kotlin","doc":"Reads HTTP/2 transport frames. This implementation assumes we do not send an increased [frame][Settings.getMaxFrameSize] to the peer. Hence, we expect all frames to have a max length of [Http2.INITIAL_MAX_FRAME_SIZE].","code":"class Http2Reader(\n /** Creates a frame reader with max header table size of 4096. */\n private val source: BufferedSource,\n private val client: Boolean,\n) : Closeable {\n private val continuation: ContinuationSource = ContinuationSource(this.source)\n private val hpackReader: Hpack.Reader =\n Hpack.Reader(\n source = continuation,\n headerTableSizeSetting = 4096,\n )\n\n @Throws(IOException::class)\n fun readConnectionPreface(handler: Handler) {\n if (client) {\n // The client reads the initial SETTINGS frame.\n if (!nextFrame(true, handler)) {\n throw IOException(\"Required SETTINGS preface not received\")\n }\n } else {\n // The server reads the CONNECTION_PREFACE byte string.\n val connectionPreface = source.readByteString(CONNECTION_PREFACE.size.toLong())\n if (logger.isLoggable(FINE)) logger.fine(format(\"<< CONNECTION ${connectionPreface.hex()}\"))\n if (CONNECTION_PREFACE != connectionPreface) {\n throw IOException(\"Expected a connection header but was ${connectionPreface.utf8()}\")\n }\n }\n }\n\n @Throws(IOException::class)\n fun nextFrame(\n requireSettings: Boolean,\n handler: Handler,\n ): Boolean {\n try {"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":71,"symbol":"readConnectionPreface","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun readConnectionPreface(handler: Handler) {\n if (client) {\n // The client reads the initial SETTINGS frame.\n if (!nextFrame(true, handler)) {\n throw IOException(\"Required SETTINGS preface not received\")\n }\n } else {\n // The server reads the CONNECTION_PREFACE byte string.\n val connectionPreface = source.readByteString(CONNECTION_PREFACE.size.toLong())\n if (logger.isLoggable(FINE)) logger.fine(format(\"<< CONNECTION ${connectionPreface.hex()}\"))\n if (CONNECTION_PREFACE != connectionPreface) {\n throw IOException(\"Expected a connection header but was ${connectionPreface.utf8()}\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":88,"symbol":"nextFrame","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun nextFrame(\n requireSettings: Boolean,\n handler: Handler,\n ): Boolean {\n try {\n source.require(9) // Frame header size.\n } catch (e: EOFException) {\n return false // This might be a normal socket close.\n }\n\n // 0 1 2 3\n // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n // | Length (24) |\n // +---------------+---------------+---------------+\n // | Type (8) | Flags (8) |\n // +-+-+-----------+---------------+-------------------------------+\n // |R| Stream Identifier (31) |\n // +=+=============================================================+\n // | Frame Payload (0...) ...\n // +---------------------------------------------------------------+\n val length = source.readMedium()\n if (length > INITIAL_MAX_FRAME_SIZE) {\n throw IOException(\"FRAME_SIZE_ERROR: $length\")\n }\n val type = source.readByte() and 0xff\n val flags = so"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":141,"symbol":"readHeaders","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readHeaders(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n if (streamId == 0) throw IOException(\"PROTOCOL_ERROR: TYPE_HEADERS streamId == 0\")\n\n val endStream = (flags and FLAG_END_STREAM) != 0\n val padding = if (flags and FLAG_PADDED != 0) source.readByte() and 0xff else 0\n\n var headerBlockLength = length\n if (flags and FLAG_PRIORITY != 0) {\n readPriority(handler, streamId)\n headerBlockLength -= 5 // account for above read.\n }\n headerBlockLength = lengthWithoutPadding(headerBlockLength, flags, padding)\n val headerBlock = readHeaderBlock(headerBlockLength, padding, flags, streamId)\n\n handler.headers(endStream, streamId, -1, headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":164,"symbol":"readHeaderBlock","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readHeaderBlock(\n length: Int,\n padding: Int,\n flags: Int,\n streamId: Int,\n ): List
{\n continuation.left = length\n continuation.padding = padding\n continuation.flags = flags\n continuation.streamId = streamId\n\n // TODO: Concat multi-value headers with 0x0, except COOKIE, which uses 0x3B, 0x20.\n // http://tools.ietf.org/html/draft-ietf-httpbis-http2-17#section-8.1.2.5\n hpackReader.readHeaders()\n return hpackReader.getAndResetHeaderList()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":182,"symbol":"readData","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readData(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n if (streamId == 0) throw IOException(\"PROTOCOL_ERROR: TYPE_DATA streamId == 0\")\n\n // TODO: checkState open or half-closed (local) or raise STREAM_CLOSED\n val inFinished = flags and FLAG_END_STREAM != 0\n val gzipped = flags and FLAG_COMPRESSED != 0\n if (gzipped) {\n throw IOException(\"PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA\")\n }\n\n val padding = if (flags and FLAG_PADDED != 0) source.readByte() and 0xff else 0\n val dataLength = lengthWithoutPadding(length, flags, padding)\n\n handler.data(inFinished, streamId, source, dataLength)\n source.skip(padding.toLong())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":205,"symbol":"readPriority","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readPriority(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n if (length != 5) throw IOException(\"TYPE_PRIORITY length: $length != 5\")\n if (streamId == 0) throw IOException(\"TYPE_PRIORITY streamId == 0\")\n readPriority(handler, streamId)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":217,"symbol":"readPriority","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readPriority(\n handler: Handler,\n streamId: Int,\n ) {\n val w1 = source.readInt()\n val exclusive = w1 and 0x80000000.toInt() != 0\n val streamDependency = w1 and 0x7fffffff\n val weight = (source.readByte() and 0xff) + 1\n handler.priority(streamId, streamDependency, weight, exclusive)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":229,"symbol":"readRstStream","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readRstStream(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n if (length != 4) throw IOException(\"TYPE_RST_STREAM length: $length != 4\")\n if (streamId == 0) throw IOException(\"TYPE_RST_STREAM streamId == 0\")\n val errorCodeInt = source.readInt()\n val errorCode =\n ErrorCode.fromHttp2(errorCodeInt) ?: throw IOException(\n \"TYPE_RST_STREAM unexpected error code: $errorCodeInt\",\n )\n handler.rstStream(streamId, errorCode)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":246,"symbol":"readSettings","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readSettings(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n if (streamId != 0) throw IOException(\"TYPE_SETTINGS streamId != 0\")\n if (flags and FLAG_ACK != 0) {\n if (length != 0) throw IOException(\"FRAME_SIZE_ERROR ack frame should be empty!\")\n handler.ackSettings()\n return\n }\n\n if (length % 6 != 0) throw IOException(\"TYPE_SETTINGS length % 6 != 0: $length\")\n val settings = Settings()\n for (i in 0 until length step 6) {\n val id = source.readShort() and 0xffff\n val value = source.readInt()\n\n when (id) {\n // SETTINGS_HEADER_TABLE_SIZE\n 1 -> {\n }\n\n // SETTINGS_ENABLE_PUSH\n 2 -> {\n if (value != 0 && value != 1) {\n throw IOException(\"PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1\")\n }\n }\n\n // SETTINGS_MAX_CONCURRENT_STREAMS\n 3 -> {\n }\n\n // SETTINGS_INITIAL_WINDOW_SIZE\n 4 -> {\n if (value < 0) {\n throw IOException(\"PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1\")\n }\n }\n\n // SETTINGS_MAX_FRAME_SIZE\n 5 -> {\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":309,"symbol":"readPushPromise","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readPushPromise(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n if (streamId == 0) {\n throw IOException(\"PROTOCOL_ERROR: TYPE_PUSH_PROMISE streamId == 0\")\n }\n val padding = if (flags and FLAG_PADDED != 0) source.readByte() and 0xff else 0\n val promisedStreamId = source.readInt() and 0x7fffffff\n val headerBlockLength = lengthWithoutPadding(length - 4, flags, padding) // - 4 for readInt().\n val headerBlock = readHeaderBlock(headerBlockLength, padding, flags, streamId)\n handler.pushPromise(streamId, promisedStreamId, headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":326,"symbol":"readPing","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readPing(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n if (length != 8) throw IOException(\"TYPE_PING length != 8: $length\")\n if (streamId != 0) throw IOException(\"TYPE_PING streamId != 0\")\n val payload1 = source.readInt()\n val payload2 = source.readInt()\n val ack = flags and FLAG_ACK != 0\n handler.ping(ack, payload1, payload2)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":341,"symbol":"readGoAway","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readGoAway(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n if (length < 8) throw IOException(\"TYPE_GOAWAY length < 8: $length\")\n if (streamId != 0) throw IOException(\"TYPE_GOAWAY streamId != 0\")\n val lastStreamId = source.readInt()\n val errorCodeInt = source.readInt()\n val opaqueDataLength = length - 8\n val errorCode =\n ErrorCode.fromHttp2(errorCodeInt) ?: throw IOException(\n \"TYPE_GOAWAY unexpected error code: $errorCodeInt\",\n )\n var debugData = ByteString.EMPTY\n if (opaqueDataLength > 0) { // Must read debug data in order to not corrupt the connection.\n debugData = source.readByteString(opaqueDataLength.toLong())\n }\n handler.goAway(lastStreamId, errorCode, debugData)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":365,"symbol":"readWindowUpdate","kind":"function","lang":"kotlin","doc":"Unlike other `readXxx()` functions, this one must log the frame before returning.","code":"@Throws(IOException::class)\n private fun readWindowUpdate(\n handler: Handler,\n length: Int,\n flags: Int,\n streamId: Int,\n ) {\n val increment: Long\n try {\n if (length != 4) throw IOException(\"TYPE_WINDOW_UPDATE length !=4: $length\")\n increment = source.readInt() and 0x7fffffffL\n if (increment == 0L) throw IOException(\"windowSizeIncrement was 0\")\n } catch (e: Exception) {\n logger.fine(frameLog(true, streamId, length, TYPE_WINDOW_UPDATE, flags))\n throw e\n }\n if (logger.isLoggable(FINE)) {\n logger.fine(\n frameLogWindowUpdate(\n inbound = true,\n streamId = streamId,\n length = length,\n windowSizeIncrement = increment,\n ),\n )\n }\n handler.windowUpdate(streamId, increment)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":394,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n source.close()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":403,"symbol":"ContinuationSource","kind":"class","lang":"kotlin","doc":"Decompression of the header block occurs above the framing layer. This class lazily reads continuation frames as they are needed by [Hpack.Reader.readHeaders].","code":"internal class ContinuationSource(\n private val source: BufferedSource,\n ) : Source {\n var flags: Int = 0\n var streamId: Int = 0\n\n var left: Int = 0\n var padding: Int = 0\n\n @Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n while (left == 0) {\n source.skip(padding.toLong())\n padding = 0\n if (flags and FLAG_END_HEADERS != 0) return -1L\n readContinuationHeader()\n // TODO: test case for empty continuation header?\n }\n\n val read = source.read(sink, minOf(byteCount, left.toLong()))\n if (read == -1L) return -1L\n left -= read.toInt()\n return read\n }\n\n override fun timeout(): Timeout = source.timeout()\n\n @Throws(IOException::class)\n override fun close() {\n }\n\n @Throws(IOException::class)\n private fun readContinuationHeader() {\n val previousStreamId = streamId\n\n val length = source.readMedium()\n left = length\n val type = source.readByte() and 0xff\n flags = source.readByte() and 0xff\n if (logger.isLoggable(FINE)) logger.fine(frameLog(true, streamId, length, type, flags))\n streamId = source.readInt("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":412,"symbol":"read","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n while (left == 0) {\n source.skip(padding.toLong())\n padding = 0\n if (flags and FLAG_END_HEADERS != 0) return -1L\n readContinuationHeader()\n // TODO: test case for empty continuation header?\n }\n\n val read = source.read(sink, minOf(byteCount, left.toLong()))\n if (read == -1L) return -1L\n left -= read.toInt()\n return read\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":431,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = source.timeout()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":433,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":437,"symbol":"readContinuationHeader","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readContinuationHeader() {\n val previousStreamId = streamId\n\n val length = source.readMedium()\n left = length\n val type = source.readByte() and 0xff\n flags = source.readByte() and 0xff\n if (logger.isLoggable(FINE)) logger.fine(frameLog(true, streamId, length, type, flags))\n streamId = source.readInt() and 0x7fffffff\n if (type != TYPE_CONTINUATION) throw IOException(\"$type != TYPE_CONTINUATION\")\n if (streamId != previousStreamId) throw IOException(\"TYPE_CONTINUATION streamId changed\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":452,"symbol":"Handler","kind":"interface","lang":"kotlin","code":"interface Handler {\n @Throws(IOException::class)\n fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n )\n\n /**\n * Create or update incoming headers, creating the corresponding streams if necessary. Frames\n * that trigger this are HEADERS and PUSH_PROMISE.\n *\n * @param inFinished true if the sender will not send further frames.\n * @param streamId the stream owning these headers.\n * @param associatedStreamId the stream that triggered the sender to create this stream.\n */\n fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n )\n\n fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n )\n\n fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n )\n\n /** HTTP/2 only. */\n fun ackSettings()\n\n /**\n * Read a connection-level ping from the peer. `ack` indicates this is a reply. The data\n * in `payload1` and `payload2` opaque binary, and there are no rules on the content.\n */\n fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n )\n\n /**\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":453,"symbol":"data","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":469,"symbol":"headers","kind":"function","lang":"kotlin","doc":"that trigger this are HEADERS and PUSH_PROMISE. @param inFinished true if the sender will not send further frames. @param streamId the stream owning these headers. @param associatedStreamId the stream that triggered the sender to create this stream.","code":"fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":476,"symbol":"rstStream","kind":"function","lang":"kotlin","code":"fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":481,"symbol":"settings","kind":"function","lang":"kotlin","code":"fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":487,"symbol":"ackSettings","kind":"function","lang":"kotlin","doc":"HTTP/2 only.","code":"fun ackSettings()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":493,"symbol":"ping","kind":"function","lang":"kotlin","doc":"Read a connection-level ping from the peer. `ack` indicates this is a reply. The data in `payload1` and `payload2` opaque binary, and there are no rules on the content.","code":"fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":509,"symbol":"goAway","kind":"function","lang":"kotlin","doc":"@param lastGoodStreamId the last stream ID the peer processed before sending this message. If [lastGoodStreamId] is zero, the peer processed no frames. @param errorCode reason for closing the connection. @param debugData only valid for HTTP/2; opaque debug data to send.","code":"fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":519,"symbol":"windowUpdate","kind":"function","lang":"kotlin","doc":"Notifies that an additional `windowSizeIncrement` bytes can be sent on `streamId`, or the connection if `streamId` is zero.","code":"fun windowUpdate(\n streamId: Int,\n windowSizeIncrement: Long,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":533,"symbol":"priority","kind":"function","lang":"kotlin","doc":"@param streamId stream which has a priority change. @param streamDependency the stream ID this stream is dependent on. @param weight relative proportion of priority in `[1..256]`. @param exclusive inserts this stream ID as the sole child of `streamDependency`.","code":"fun priority(\n streamId: Int,\n streamDependency: Int,\n weight: Int,\n exclusive: Boolean,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":551,"symbol":"pushPromise","kind":"function","lang":"kotlin","doc":"as a part of the response to `streamId`. @param streamId client-initiated stream ID. Must be an odd number. @param promisedStreamId server-initiated stream ID. Must be an even number. @param requestHeaders minimally includes `:method`, `:scheme`, `:authority`, and `:path`.","code":"@Throws(IOException::class)\n fun pushPromise(\n streamId: Int,\n promisedStreamId: Int,\n requestHeaders: List
,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":577,"symbol":"alternateService","kind":"function","lang":"kotlin","doc":"the `streamId`. @param protocol an ALPN protocol, such as `h2`. @param host an IP address or hostname. @param port the IP port associated with the service. @param maxAge time in seconds that this alternative is considered fresh.","code":"fun alternateService(\n streamId: Int,\n origin: String,\n protocol: ByteString,\n host: String,\n port: Int,\n maxAge: Long,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Reader.kt","line":590,"symbol":"lengthWithoutPadding","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun lengthWithoutPadding(\n length: Int,\n flags: Int,\n padding: Int,\n ): Int {\n var result = length\n if (flags and FLAG_PADDED != 0) result-- // Account for reading the padding length.\n if (padding > result) {\n throw IOException(\"PROTOCOL_ERROR padding $padding > remaining length $result\")\n }\n result -= padding\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":40,"symbol":"Http2Stream","kind":"class","lang":"kotlin","doc":"A logical bidirectional stream.","code":"@Suppress(\"NAME_SHADOWING\")\nclass Http2Stream internal constructor(\n val id: Int,\n val connection: Http2Connection,\n outFinished: Boolean,\n inFinished: Boolean,\n headers: Headers?,\n) : Lockable,\n Socket {\n // Internal state is guarded by `this`. No long-running or potentially blocking operations are\n // performed while the lock is held.\n\n /** The bytes consumed and acknowledged by the stream. */\n val readBytes: WindowCounter = WindowCounter(id)\n\n /** The total number of bytes produced by the application. */\n var writeBytesTotal = 0L\n internal set\n\n /** The total number of bytes permitted to be produced by incoming `WINDOW_UPDATE` frame. */\n var writeBytesMaximum: Long = connection.peerSettings.initialWindowSize.toLong()\n internal set\n\n /** Received headers yet to be [taken][takeHeaders]. */\n private val headersQueue = ArrayDeque()\n\n /** True if response headers have been sent or received. */\n private var hasResponseHeaders: Boolean = false\n\n override val source =\n FramingSource(\n maxByteCount = connection.okHttpSettings.initialWindowSize.toLong(),\n finished = inFinished,\n )\n override val sink =\n FramingSink(\n finished = out"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":147,"symbol":"takeHeaders","kind":"function","lang":"kotlin","doc":"delimited by 'null'. @param callerIsIdle true if the caller isn't sending any more bytes until the peer responds. This is true after a `Expect-Continue` request, false for duplex requests, and false for all other requests.","code":"@Throws(IOException::class)\n fun takeHeaders(callerIsIdle: Boolean = false): Headers {\n withLock {\n while (headersQueue.isEmpty() && errorCode == null) {\n val doReadTimeout = callerIsIdle || doReadTimeout()\n if (doReadTimeout) {\n readTimeout.enter()\n }\n try {\n waitForIo()\n } finally {\n if (doReadTimeout) {\n readTimeout.exitAndThrowIfTimedOut()\n }\n }\n }\n if (headersQueue.isNotEmpty()) {\n return headersQueue.removeFirst()\n }\n throw errorException ?: StreamResetException(errorCode!!)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":173,"symbol":"peekTrailers","kind":"function","lang":"kotlin","doc":"Returns the trailers if they're immediately available.","code":"@Throws(IOException::class)\n fun peekTrailers(): Headers? {\n withLock {\n if (source.finished && source.receiveBuffer.exhausted() && source.readBuffer.exhausted()) {\n return source.trailers ?: Headers.EMPTY\n }\n if (errorCode != null) {\n throw errorException ?: StreamResetException(errorCode!!)\n }\n return null\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":194,"symbol":"writeHeaders","kind":"function","lang":"kotlin","doc":"@param outFinished true to eagerly finish the output stream to send data to the remote peer. Corresponds to `FLAG_FIN`. @param flushHeaders true to force flush the response headers. This should be true unless the response body exists and will be written immediately.","code":"@Throws(IOException::class)\n fun writeHeaders(\n responseHeaders: List
,\n outFinished: Boolean,\n flushHeaders: Boolean,\n ) {\n assertLockNotHeld()\n\n var flushHeaders = flushHeaders\n withLock {\n this.hasResponseHeaders = true\n if (outFinished) {\n this.sink.finished = true\n notifyAll() // Because doReadTimeout() may have changed.\n }\n }\n\n // Only DATA frames are subject to flow-control. Transmit the HEADER frame if the connection\n // flow-control window is fully depleted.\n if (!flushHeaders) {\n withLock {\n flushHeaders = (connection.writeBytesTotal >= connection.writeBytesMaximum)\n }\n }\n\n connection.writeHeaders(id, outFinished, responseHeaders)\n\n if (flushHeaders) {\n connection.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":226,"symbol":"enqueueTrailers","kind":"function","lang":"kotlin","code":"fun enqueueTrailers(trailers: Headers) {\n withLock {\n check(!sink.finished) { \"already finished\" }\n require(trailers.size != 0) { \"trailers.size() == 0\" }\n this.sink.trailers = trailers\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":234,"symbol":"readTimeout","kind":"function","lang":"kotlin","code":"fun readTimeout(): Timeout = readTimeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":236,"symbol":"writeTimeout","kind":"function","lang":"kotlin","code":"fun writeTimeout(): Timeout = writeTimeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":242,"symbol":"close","kind":"function","lang":"kotlin","doc":"Abnormally terminate this stream. This blocks until the `RST_STREAM` frame has been transmitted.","code":"@Throws(IOException::class)\n fun close(\n rstStatusCode: ErrorCode,\n errorException: IOException?,\n ) {\n if (!closeInternal(rstStatusCode, errorException)) {\n return // Already closed.\n }\n connection.writeSynReset(id, rstStatusCode)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":253,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n closeLater(ErrorCode.CANCEL)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":260,"symbol":"closeLater","kind":"function","lang":"kotlin","doc":"Abnormally terminate this stream. This enqueues a `RST_STREAM` frame and returns immediately.","code":"fun closeLater(errorCode: ErrorCode) {\n if (!closeInternal(errorCode, null)) {\n return // Already closed.\n }\n connection.writeSynResetLater(id, errorCode)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":268,"symbol":"closeInternal","kind":"function","lang":"kotlin","doc":"Returns true if this stream was closed.","code":"private fun closeInternal(\n errorCode: ErrorCode,\n errorException: IOException?,\n ): Boolean {\n assertLockNotHeld()\n\n withLock {\n if (this.errorCode != null) {\n return false\n }\n this.errorCode = errorCode\n this.errorException = errorException\n notifyAll()\n if (source.finished && sink.finished) {\n return false\n }\n }\n connection.removeStream(id)\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":289,"symbol":"receiveData","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun receiveData(\n source: BufferedSource,\n length: Int,\n ) {\n assertLockNotHeld()\n\n this.source.receive(source, length.toLong())\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":300,"symbol":"receiveHeaders","kind":"function","lang":"kotlin","doc":"Accept headers from the network and store them until the client calls [takeHeaders].","code":"fun receiveHeaders(\n headers: Headers,\n inFinished: Boolean,\n ) {\n assertLockNotHeld()\n\n val open: Boolean\n withLock {\n if (!hasResponseHeaders ||\n headers[Header.RESPONSE_STATUS_UTF8] != null ||\n headers[Header.TARGET_METHOD_UTF8] != null\n ) {\n hasResponseHeaders = true\n headersQueue += headers\n } else {\n this.source.trailers = headers\n }\n if (inFinished) {\n this.source.finished = true\n }\n open = isOpen\n notifyAll()\n }\n if (!open) {\n connection.removeStream(id)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":328,"symbol":"receiveRstStream","kind":"function","lang":"kotlin","code":"fun receiveRstStream(errorCode: ErrorCode) {\n withLock {\n if (this.errorCode == null) {\n this.errorCode = errorCode\n notifyAll()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":345,"symbol":"doReadTimeout","kind":"function","lang":"kotlin","doc":"We always do timeouts in the HTTP server role. For clients, we only do timeouts after the request is transmitted. This is only interesting for duplex calls where the request and response may be interleaved. Read this value only once for each enter/exit pair because its value can change.","code":"private fun doReadTimeout() = !connection.client || sink.closed || sink.finished"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":352,"symbol":"FramingSource","kind":"class","lang":"kotlin","doc":"A source that reads the incoming data frames of a stream. Although this class uses synchronization to safely receive incoming data frames, it is not intended for use by multiple readers.","code":"inner class FramingSource internal constructor(\n /** Maximum number of bytes to buffer before reporting a flow control error. */\n private val maxByteCount: Long,\n /**\n * True if either side has cleanly shut down this stream. We will receive no more bytes beyond\n * those already in the buffer.\n */\n internal var finished: Boolean,\n ) : Source {\n /** Buffer to receive data from the network into. Only accessed by the reader thread. */\n val receiveBuffer = Buffer()\n\n /** Buffer with readable data. Guarded by Http2Stream.this. */\n val readBuffer = Buffer()\n\n /**\n * Received trailers. Null unless the server has provided trailers. Undefined until the stream\n * is exhausted. Guarded by Http2Stream.this.\n */\n var trailers: Headers? = null\n\n /** True if the caller has closed this stream. */\n internal var closed: Boolean = false\n\n @Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n require(byteCount >= 0L) { \"byteCount < 0: $byteCount\" }\n\n while (true) {\n var tryAgain = false\n var readBytesDelivered = -1L\n var errorExceptionToDeliver: IOExcepti"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":376,"symbol":"read","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n require(byteCount >= 0L) { \"byteCount < 0: $byteCount\" }\n\n while (true) {\n var tryAgain = false\n var readBytesDelivered = -1L\n var errorExceptionToDeliver: IOException? = null\n\n // 1. Decide what to do in a synchronized block.\n\n withLock {\n val doReadTimeout = doReadTimeout()\n if (doReadTimeout) {\n readTimeout.enter()\n }\n try {\n if (errorCode != null && !finished) {\n // Prepare to deliver an error.\n errorExceptionToDeliver = errorException ?: StreamResetException(errorCode!!)\n }\n\n if (closed) {\n throw IOException(\"stream closed\")\n } else if (readBuffer.size > 0L) {\n // Prepare to read bytes. Start by moving them to the caller's buffer.\n readBytesDelivered = readBuffer.read(sink, minOf(byteCount, readBuffer.size))\n readBytes.update(total = readBytesDelivered)\n\n val unacknowledgedBytesRead = readBytes.unacknowledged\n if (errorExceptionToDeli"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":452,"symbol":"updateConnectionFlowControl","kind":"function","lang":"kotlin","code":"private fun updateConnectionFlowControl(read: Long) {\n assertLockNotHeld()\n\n connection.updateConnectionFlowControl(read)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":462,"symbol":"receive","kind":"function","lang":"kotlin","doc":"Accept bytes on the connection's reader thread. This function avoids holding locks while it performs blocking reads for the incoming bytes.","code":"@Throws(IOException::class)\n internal fun receive(\n source: BufferedSource,\n byteCount: Long,\n ) {\n assertLockNotHeld()\n\n var remainingByteCount = byteCount\n\n while (remainingByteCount > 0L) {\n val finished: Boolean\n val flowControlError: Boolean\n withLock {\n finished = this.finished\n flowControlError = remainingByteCount + readBuffer.size > maxByteCount\n }\n\n // If the peer sends more data than we can handle, discard it and close the connection.\n if (flowControlError) {\n source.skip(remainingByteCount)\n closeLater(ErrorCode.FLOW_CONTROL_ERROR)\n return\n }\n\n // Discard data received after the stream is finished. It's probably a benign race.\n if (finished) {\n source.skip(remainingByteCount)\n return\n }\n\n // Fill the receive buffer without holding any locks.\n val read = source.read(receiveBuffer, remainingByteCount)\n if (read == -1L) throw EOFException()\n remainingByteCount -= read\n\n // Move the received data to the read buffer to the reader can read it. If this source has\n // been cl"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":523,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = readTimeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":525,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n val bytesDiscarded: Long\n withLock {\n closed = true\n bytesDiscarded = readBuffer.size\n readBuffer.clear()\n notifyAll() // TODO(jwilson): Unnecessary?\n }\n if (bytesDiscarded > 0L) {\n updateConnectionFlowControl(bytesDiscarded)\n }\n cancelStreamIfNecessary()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":541,"symbol":"cancelStreamIfNecessary","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n internal fun cancelStreamIfNecessary() {\n assertLockNotHeld()\n\n val open: Boolean\n val cancel: Boolean\n withLock {\n cancel = !source.finished && source.closed && (sink.finished || sink.closed)\n open = isOpen\n }\n if (cancel) {\n // RST this stream to prevent additional data from being sent. This is safe because the input\n // stream is closed (we won't use any further bytes) and the output stream is either finished\n // or closed (so RSTing both streams doesn't cause harm).\n this@Http2Stream.close(ErrorCode.CANCEL, null)\n } else if (!open) {\n connection.removeStream(id)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":562,"symbol":"FramingSink","kind":"class","lang":"kotlin","doc":"A sink that writes outgoing data frames of a stream. This class is not thread safe.","code":"inner class FramingSink(\n /** True if either side has cleanly shut down this stream. We shall send no more bytes. */\n var finished: Boolean = false,\n ) : Sink {\n /**\n * Buffer of outgoing data. This batches writes of small writes into this sink as larges frames\n * written to the outgoing connection. Batching saves the (small) framing overhead.\n */\n private val sendBuffer = Buffer()\n\n /** Trailers to send at the end of the stream. */\n var trailers: Headers? = null\n\n var closed: Boolean = false\n\n @Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n assertLockNotHeld()\n\n sendBuffer.write(source, byteCount)\n while (sendBuffer.size >= EMIT_BUFFER_SIZE) {\n emitFrame(false)\n }\n }\n\n /**\n * Emit a single data frame to the connection. The frame's size be limited by this stream's\n * write window. This method will block until the write window is nonempty.\n */\n @Throws(IOException::class)\n private fun emitFrame(outFinishedOnLastFrame: Boolean) {\n val toWrite: Long\n val outFinished: Boolean\n withLock {\n writeTimeout.enter()\n try"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":577,"symbol":"write","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n assertLockNotHeld()\n\n sendBuffer.write(source, byteCount)\n while (sendBuffer.size >= EMIT_BUFFER_SIZE) {\n emitFrame(false)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":594,"symbol":"emitFrame","kind":"function","lang":"kotlin","doc":"Emit a single data frame to the connection. The frame's size be limited by this stream's write window. This method will block until the write window is nonempty.","code":"@Throws(IOException::class)\n private fun emitFrame(outFinishedOnLastFrame: Boolean) {\n val toWrite: Long\n val outFinished: Boolean\n withLock {\n writeTimeout.enter()\n try {\n while (writeBytesTotal >= writeBytesMaximum &&\n !finished &&\n !closed &&\n errorCode == null\n ) {\n waitForIo() // Wait until we receive a WINDOW_UPDATE for this stream.\n }\n } finally {\n writeTimeout.exitAndThrowIfTimedOut()\n }\n\n checkOutNotClosed() // Kick out if the stream was reset or closed while waiting.\n toWrite = minOf(writeBytesMaximum - writeBytesTotal, sendBuffer.size)\n writeBytesTotal += toWrite\n outFinished = outFinishedOnLastFrame && toWrite == sendBuffer.size\n }\n\n writeTimeout.enter()\n try {\n connection.writeData(id, outFinished, sendBuffer, toWrite)\n } finally {\n writeTimeout.exitAndThrowIfTimedOut()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":626,"symbol":"flush","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun flush() {\n assertLockNotHeld()\n\n withLock {\n checkOutNotClosed()\n }\n // TODO(jwilson): flush the connection?!\n while (sendBuffer.size > 0L) {\n emitFrame(false)\n connection.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":640,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = writeTimeout"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":642,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n assertLockNotHeld()\n\n val outFinished: Boolean\n withLock {\n if (closed) return\n outFinished = errorCode == null\n }\n if (!sink.finished) {\n // We have 0 or more frames of data, and 0 or more frames of trailers. We need to send at\n // least one frame with the END_STREAM flag set. That must be the last frame, and the\n // trailers must be sent after all of the data.\n val hasData = sendBuffer.size > 0L\n val hasTrailers = trailers != null\n when {\n hasTrailers -> {\n while (sendBuffer.size > 0L) {\n emitFrame(false)\n }\n connection.writeHeaders(id, outFinished, trailers!!.toHeaderList())\n }\n\n hasData -> {\n while (sendBuffer.size > 0L) {\n emitFrame(true)\n }\n }\n\n outFinished -> {\n connection.writeData(id, true, null, 0L)\n }\n }\n }\n withLock {\n closed = true\n notifyAll() // Because doReadTimeout() may have changed.\n }\n connection.flush()\n cancelStreamIfNecessary()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":690,"symbol":"addBytesToWriteWindow","kind":"function","lang":"kotlin","doc":"[delta] will be negative if a settings frame initial window is smaller than the last.","code":"fun addBytesToWriteWindow(delta: Long) {\n writeBytesMaximum += delta\n if (delta > 0L) {\n notifyAll()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":697,"symbol":"checkOutNotClosed","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n internal fun checkOutNotClosed() {\n when {\n sink.closed -> throw IOException(\"stream closed\")\n sink.finished -> throw IOException(\"stream finished\")\n errorCode != null -> throw errorException ?: StreamResetException(errorCode!!)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":710,"symbol":"waitForIo","kind":"function","lang":"kotlin","doc":"Like [Object.wait], but throws an [InterruptedIOException] when interrupted instead of the more awkward [InterruptedException].","code":"@Throws(InterruptedIOException::class)\n internal fun waitForIo() {\n try {\n wait()\n } catch (_: InterruptedException) {\n Thread.currentThread().interrupt() // Retain interrupted status.\n throw InterruptedIOException()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":724,"symbol":"StreamTimeout","kind":"class","lang":"kotlin","doc":"The Okio timeout watchdog will call [timedOut] if the timeout is reached. In that case we close the stream (asynchronously) which will notify the waiting thread.","code":"internal inner class StreamTimeout : AsyncTimeout() {\n override fun timedOut() {\n closeLater(ErrorCode.CANCEL)\n connection.sendDegradedPingLater()\n }\n\n override fun newTimeoutException(cause: IOException?): IOException =\n SocketTimeoutException(\"timeout\").apply {\n if (cause != null) {\n initCause(cause)\n }\n }\n\n @Throws(IOException::class)\n fun exitAndThrowIfTimedOut() {\n if (exit()) throw newTimeoutException(null)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":725,"symbol":"timedOut","kind":"function","lang":"kotlin","code":"override fun timedOut() {\n closeLater(ErrorCode.CANCEL)\n connection.sendDegradedPingLater()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":730,"symbol":"newTimeoutException","kind":"function","lang":"kotlin","code":"override fun newTimeoutException(cause: IOException?): IOException =\n SocketTimeoutException(\"timeout\").apply {\n if (cause != null) {\n initCause(cause)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt","line":737,"symbol":"exitAndThrowIfTimedOut","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun exitAndThrowIfTimedOut() {\n if (exit()) throw newTimeoutException(null)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":47,"symbol":"Http2Writer","kind":"class","lang":"kotlin","doc":"Writes HTTP/2 transport frames.","code":"@Suppress(\"NAME_SHADOWING\")\nclass Http2Writer(\n private val sink: BufferedSink,\n private val client: Boolean,\n) : Closeable,\n Lockable {\n private val hpackBuffer: Buffer = Buffer()\n private var maxFrameSize: Int = INITIAL_MAX_FRAME_SIZE\n private var closed: Boolean = false\n val hpackWriter: Hpack.Writer = Hpack.Writer(out = hpackBuffer)\n\n @Throws(IOException::class)\n fun connectionPreface() {\n withLock {\n if (closed) throw IOException(\"closed\")\n if (!client) return // Nothing to write; servers don't send connection headers!\n if (logger.isLoggable(FINE)) {\n logger.fine(format(\">> CONNECTION ${CONNECTION_PREFACE.hex()}\"))\n }\n sink.write(CONNECTION_PREFACE)\n sink.flush()\n }\n }\n\n /** Applies `peerSettings` and then sends a settings ACK. */\n @Throws(IOException::class)\n fun applyAndAckSettings(peerSettings: Settings) {\n withLock {\n if (closed) throw IOException(\"closed\")\n this.maxFrameSize = peerSettings.getMaxFrameSize(maxFrameSize)\n if (peerSettings.headerTableSize != -1) {\n hpackWriter.resizeHeaderTable(peerSettings.headerTableSize)\n }\n frameHeader(\n streamId = 0,\n length = 0,\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":58,"symbol":"connectionPreface","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun connectionPreface() {\n withLock {\n if (closed) throw IOException(\"closed\")\n if (!client) return // Nothing to write; servers don't send connection headers!\n if (logger.isLoggable(FINE)) {\n logger.fine(format(\">> CONNECTION ${CONNECTION_PREFACE.hex()}\"))\n }\n sink.write(CONNECTION_PREFACE)\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":72,"symbol":"applyAndAckSettings","kind":"function","lang":"kotlin","doc":"Applies `peerSettings` and then sends a settings ACK.","code":"@Throws(IOException::class)\n fun applyAndAckSettings(peerSettings: Settings) {\n withLock {\n if (closed) throw IOException(\"closed\")\n this.maxFrameSize = peerSettings.getMaxFrameSize(maxFrameSize)\n if (peerSettings.headerTableSize != -1) {\n hpackWriter.resizeHeaderTable(peerSettings.headerTableSize)\n }\n frameHeader(\n streamId = 0,\n length = 0,\n type = TYPE_SETTINGS,\n flags = FLAG_ACK,\n )\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":102,"symbol":"pushPromise","kind":"function","lang":"kotlin","doc":"`streamId`. @param streamId client-initiated stream ID. Must be an odd number. @param promisedStreamId server-initiated stream ID. Must be an even number. @param requestHeaders minimally includes `:method`, `:scheme`, `:authority`, and `:path`.","code":"@Throws(IOException::class)\n fun pushPromise(\n streamId: Int,\n promisedStreamId: Int,\n requestHeaders: List
,\n ) {\n withLock {\n if (closed) throw IOException(\"closed\")\n hpackWriter.writeHeaders(requestHeaders)\n\n val byteCount = hpackBuffer.size\n val length = minOf(maxFrameSize - 4L, byteCount).toInt()\n frameHeader(\n streamId = streamId,\n length = length + 4,\n type = TYPE_PUSH_PROMISE,\n flags = if (byteCount == length.toLong()) FLAG_END_HEADERS else 0,\n )\n sink.writeInt(promisedStreamId and 0x7fffffff)\n sink.write(hpackBuffer, length.toLong())\n\n if (byteCount > length) writeContinuationFrames(streamId, byteCount - length)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":127,"symbol":"flush","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun flush() {\n withLock {\n if (closed) throw IOException(\"closed\")\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":135,"symbol":"rstStream","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n withLock {\n if (closed) throw IOException(\"closed\")\n require(errorCode.httpCode != -1)\n\n frameHeader(\n streamId = streamId,\n length = 4,\n type = TYPE_RST_STREAM,\n flags = FLAG_NONE,\n )\n sink.writeInt(errorCode.httpCode)\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":156,"symbol":"maxDataLength","kind":"function","lang":"kotlin","doc":"The maximum size of bytes that may be sent in a single call to [data].","code":"fun maxDataLength(): Int = maxFrameSize"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":165,"symbol":"data","kind":"function","lang":"kotlin","doc":"`source.length` may be longer than the max length of the variant's data frame. Implementations must send multiple frames as necessary. @param source the buffer to draw bytes from. May be null if byteCount is 0. @param byteCount must be between 0 and the minimum of `source.length` and [maxDataLength].","code":"@Throws(IOException::class)\n fun data(\n outFinished: Boolean,\n streamId: Int,\n source: Buffer?,\n byteCount: Int,\n ) {\n withLock {\n if (closed) throw IOException(\"closed\")\n var flags = FLAG_NONE\n if (outFinished) flags = flags or FLAG_END_STREAM\n dataFrame(streamId, flags, source, byteCount)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":180,"symbol":"dataFrame","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun dataFrame(\n streamId: Int,\n flags: Int,\n buffer: Buffer?,\n byteCount: Int,\n ) {\n frameHeader(\n streamId = streamId,\n length = byteCount,\n type = TYPE_DATA,\n flags = flags,\n )\n if (byteCount > 0) {\n sink.write(buffer!!, byteCount.toLong())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":199,"symbol":"settings","kind":"function","lang":"kotlin","doc":"Write okhttp's settings to the peer.","code":"@Throws(IOException::class)\n fun settings(settings: Settings) {\n withLock {\n if (closed) throw IOException(\"closed\")\n frameHeader(\n streamId = 0,\n length = settings.size() * 6,\n type = TYPE_SETTINGS,\n flags = FLAG_NONE,\n )\n for (i in 0 until Settings.COUNT) {\n if (!settings.isSet(i)) continue\n sink.writeShort(i)\n sink.writeInt(settings[i])\n }\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":222,"symbol":"ping","kind":"function","lang":"kotlin","doc":"Send a connection-level ping to the peer. `ack` indicates this is a reply. The data in `payload1` and `payload2` opaque binary, and there are no rules on the content.","code":"@Throws(IOException::class)\n fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n ) {\n withLock {\n if (closed) throw IOException(\"closed\")\n frameHeader(\n streamId = 0,\n length = 8,\n type = TYPE_PING,\n flags = if (ack) FLAG_ACK else FLAG_NONE,\n )\n sink.writeInt(payload1)\n sink.writeInt(payload2)\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":250,"symbol":"goAway","kind":"function","lang":"kotlin","doc":"if no streams were processed. @param lastGoodStreamId the last stream ID processed, or zero if no streams were processed. @param errorCode reason for closing the connection. @param debugData only valid for HTTP/2; opaque debug data to send.","code":"@Throws(IOException::class)\n fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteArray,\n ) {\n withLock {\n if (closed) throw IOException(\"closed\")\n require(errorCode.httpCode != -1) { \"errorCode.httpCode == -1\" }\n frameHeader(\n streamId = 0,\n length = 8 + debugData.size,\n type = TYPE_GOAWAY,\n flags = FLAG_NONE,\n )\n sink.writeInt(lastGoodStreamId)\n sink.writeInt(errorCode.httpCode)\n if (debugData.isNotEmpty()) {\n sink.write(debugData)\n }\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":278,"symbol":"windowUpdate","kind":"function","lang":"kotlin","doc":"Inform peer that an additional `windowSizeIncrement` bytes can be sent on `streamId`, or the connection if `streamId` is zero.","code":"@Throws(IOException::class)\n fun windowUpdate(\n streamId: Int,\n windowSizeIncrement: Long,\n ) {\n withLock {\n if (closed) throw IOException(\"closed\")\n require(windowSizeIncrement != 0L && windowSizeIncrement <= 0x7fffffffL) {\n \"windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: $windowSizeIncrement\"\n }\n if (logger.isLoggable(FINE)) {\n logger.fine(\n frameLogWindowUpdate(\n inbound = false,\n streamId = streamId,\n length = 4,\n windowSizeIncrement = windowSizeIncrement,\n ),\n )\n }\n frameHeader(\n streamId = streamId,\n length = 4,\n type = TYPE_WINDOW_UPDATE,\n flags = FLAG_NONE,\n )\n sink.writeInt(windowSizeIncrement.toInt())\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":309,"symbol":"frameHeader","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun frameHeader(\n streamId: Int,\n length: Int,\n type: Int,\n flags: Int,\n ) {\n if (type != TYPE_WINDOW_UPDATE && logger.isLoggable(FINE)) {\n logger.fine(frameLog(false, streamId, length, type, flags))\n }\n require(length <= maxFrameSize) { \"FRAME_SIZE_ERROR length > $maxFrameSize: $length\" }\n require(streamId and 0x80000000.toInt() == 0) { \"reserved bit set: $streamId\" }\n sink.writeMedium(length)\n sink.writeByte(type and 0xff)\n sink.writeByte(flags and 0xff)\n sink.writeInt(streamId and 0x7fffffff)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":327,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n withLock {\n closed = true\n sink.close()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":335,"symbol":"writeContinuationFrames","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun writeContinuationFrames(\n streamId: Int,\n byteCount: Long,\n ) {\n var byteCount = byteCount\n while (byteCount > 0L) {\n val length = minOf(maxFrameSize.toLong(), byteCount)\n byteCount -= length\n frameHeader(\n streamId = streamId,\n length = length.toInt(),\n type = TYPE_CONTINUATION,\n flags = if (byteCount == 0L) FLAG_END_HEADERS else 0,\n )\n sink.write(hpackBuffer, length)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Writer.kt","line":354,"symbol":"headers","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun headers(\n outFinished: Boolean,\n streamId: Int,\n headerBlock: List
,\n ) {\n withLock {\n if (closed) throw IOException(\"closed\")\n hpackWriter.writeHeaders(headerBlock)\n\n val byteCount = hpackBuffer.size\n val length = minOf(maxFrameSize.toLong(), byteCount)\n var flags = if (byteCount == length) FLAG_END_HEADERS else 0\n if (outFinished) flags = flags or FLAG_END_STREAM\n frameHeader(\n streamId = streamId,\n length = length.toInt(),\n type = TYPE_HEADERS,\n flags = flags,\n )\n sink.write(hpackBuffer, length)\n\n if (byteCount > length) writeContinuationFrames(streamId, byteCount - length)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Huffman.kt","line":34,"symbol":"Huffman","kind":"object","lang":"kotlin","doc":"* `com.twitter.hpack.HuffmanEncoder` * `com.twitter.hpack.HuffmanDecoder` * `com.twitter.hpack.HpackUtil` [twitter_hpack]: https://github.com/twitter/hpack","code":"object Huffman {\n // Appendix C: Huffman Codes\n // http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#appendix-B\n private val CODES =\n intArrayOf(\n 0x1ff8,\n 0x7fffd8,\n 0xfffffe2,\n 0xfffffe3,\n 0xfffffe4,\n 0xfffffe5,\n 0xfffffe6,\n 0xfffffe7,\n 0xfffffe8,\n 0xffffea,\n 0x3ffffffc,\n 0xfffffe9,\n 0xfffffea,\n 0x3ffffffd,\n 0xfffffeb,\n 0xfffffec,\n 0xfffffed,\n 0xfffffee,\n 0xfffffef,\n 0xffffff0,\n 0xffffff1,\n 0xffffff2,\n 0x3ffffffe,\n 0xffffff3,\n 0xffffff4,\n 0xffffff5,\n 0xffffff6,\n 0xffffff7,\n 0xffffff8,\n 0xffffff9,\n 0xffffffa,\n 0xffffffb,\n 0x14,\n 0x3f8,\n 0x3f9,\n 0xffa,\n 0x1ff9,\n 0x15,\n 0xf8,\n 0x7fa,\n 0x3fa,\n 0x3fb,\n 0xf9,\n 0x7fb,\n 0xfa,\n 0x16,\n 0x17,\n 0x18,\n 0x0,\n 0x1,\n 0x2,\n 0x19,\n 0x1a,\n 0x1b,\n 0x1c,\n 0x1d,\n 0x1e,\n 0x1f,\n 0x5c,\n 0xfb,\n 0x7ffc,\n 0x20,\n 0xffb,\n 0x3fc,\n 0x1ffa,\n 0x21,\n 0x5d,\n 0x5e,\n 0x5f,\n 0x60,\n 0x61,\n 0x"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Huffman.kt","line":565,"symbol":"encode","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun encode(\n source: ByteString,\n sink: BufferedSink,\n ) {\n var accumulator = 0L\n var accumulatorBitCount = 0\n\n for (i in 0 until source.size) {\n val symbol = source[i] and 0xff\n val code = CODES[symbol]\n val codeBitCount = CODE_BIT_COUNTS[symbol].toInt()\n\n accumulator = (accumulator shl codeBitCount) or code.toLong()\n accumulatorBitCount += codeBitCount\n\n while (accumulatorBitCount >= 8) {\n accumulatorBitCount -= 8\n sink.writeByte((accumulator shr accumulatorBitCount).toInt())\n }\n }\n\n if (accumulatorBitCount > 0) {\n accumulator = accumulator shl (8 - accumulatorBitCount)\n accumulator = accumulator or (0xffL ushr accumulatorBitCount)\n sink.writeByte(accumulator.toInt())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Huffman.kt","line":594,"symbol":"encodedLength","kind":"function","lang":"kotlin","code":"fun encodedLength(bytes: ByteString): Int {\n var bitCount = 0L\n\n for (i in 0 until bytes.size) {\n val byteIn = bytes[i] and 0xff\n bitCount += CODE_BIT_COUNTS[byteIn].toLong()\n }\n\n return ((bitCount + 7) shr 3).toInt() // Round up to an even byte.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Huffman.kt","line":605,"symbol":"decode","kind":"function","lang":"kotlin","code":"fun decode(\n source: BufferedSource,\n byteCount: Long,\n sink: BufferedSink,\n ) {\n var node = root\n var accumulator = 0\n var accumulatorBitCount = 0\n for (i in 0 until byteCount) {\n val byteIn = source.readByte() and 0xff\n accumulator = accumulator shl 8 or byteIn\n accumulatorBitCount += 8\n while (accumulatorBitCount >= 8) {\n val childIndex = (accumulator ushr (accumulatorBitCount - 8)) and 0xff\n node = node.children!![childIndex]!!\n if (node.children == null) {\n // Terminal node.\n sink.writeByte(node.symbol)\n accumulatorBitCount -= node.terminalBitCount\n node = root\n } else {\n // Non-terminal node.\n accumulatorBitCount -= 8\n }\n }\n }\n\n while (accumulatorBitCount > 0) {\n val childIndex = (accumulator shl (8 - accumulatorBitCount)) and 0xff\n node = node.children!![childIndex]!!\n if (node.children != null || node.terminalBitCount > accumulatorBitCount) {\n break\n }\n sink.writeByte(node.symbol)\n accumulatorBitCount -= node.terminalBitCount\n node = root\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Huffman.kt","line":644,"symbol":"addCode","kind":"function","lang":"kotlin","code":"private fun addCode(\n symbol: Int,\n code: Int,\n codeBitCount: Int,\n ) {\n val terminal = Node(symbol, codeBitCount)\n\n var accumulatorBitCount = codeBitCount\n var node = root\n while (accumulatorBitCount > 8) {\n accumulatorBitCount -= 8\n val childIndex = (code ushr accumulatorBitCount) and 0xff\n val children = node.children!!\n var child = children[childIndex]\n if (child == null) {\n child = Node()\n children[childIndex] = child\n }\n node = child\n }\n\n val shift = 8 - accumulatorBitCount\n val start = (code shl shift) and 0xff\n val end = 1 shl shift\n node.children!!.fill(terminal, start, start + end)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Huffman.kt","line":671,"symbol":"Node","kind":"class","lang":"kotlin","code":"private class Node {\n /** Null if terminal. */\n val children: Array?\n\n /** Terminal nodes have a symbol. */\n val symbol: Int\n\n /** Number of bits represented in the terminal node. */\n val terminalBitCount: Int\n\n /** Construct an internal node. */\n constructor() {\n this.children = arrayOfNulls(256)\n this.symbol = 0 // Not read.\n this.terminalBitCount = 0 // Not read.\n }\n\n /** Construct a terminal node. */\n constructor(symbol: Int, bits: Int) {\n this.children = null\n this.symbol = symbol\n val b = bits and 0x07\n this.terminalBitCount = if (b == 0) 8 else b\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":39,"symbol":"PushObserver","kind":"interface","lang":"kotlin","doc":"As a stream ID is scoped to a single HTTP/2 connection, implementations which target multiple connections should expect repetition of stream IDs. Return true to request cancellation of a pushed stream. Note that this does not guarantee future frames won't arrive on the stream ID.","code":"interface PushObserver {\n /**\n * Describes the request that the server intends to push a response for.\n *\n * @param streamId server-initiated stream ID: an even number.\n * @param requestHeaders minimally includes `:method`, `:scheme`, `:authority`,\n * and `:path`.\n */\n fun onRequest(\n streamId: Int,\n requestHeaders: List
,\n ): Boolean\n\n /**\n * The response headers corresponding to a pushed request. When [last] is true, there are\n * no data frames to follow.\n *\n * @param streamId server-initiated stream ID: an even number.\n * @param responseHeaders minimally includes `:status`.\n * @param last when true, there is no response data.\n */\n fun onHeaders(\n streamId: Int,\n responseHeaders: List
,\n last: Boolean,\n ): Boolean\n\n /**\n * A chunk of response data corresponding to a pushed request. This data must either be read or\n * skipped.\n *\n * @param streamId server-initiated stream ID: an even number.\n * @param source location of data corresponding with this stream ID.\n * @param byteCount number of bytes to read or skip from the source.\n * @param last when true, there are no data frames to follow.\n */\n @Throws("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":47,"symbol":"onRequest","kind":"function","lang":"kotlin","doc":"Describes the request that the server intends to push a response for. @param streamId server-initiated stream ID: an even number. @param requestHeaders minimally includes `:method`, `:scheme`, `:authority`, and `:path`.","code":"fun onRequest(\n streamId: Int,\n requestHeaders: List
,\n ): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":60,"symbol":"onHeaders","kind":"function","lang":"kotlin","doc":"no data frames to follow. @param streamId server-initiated stream ID: an even number. @param responseHeaders minimally includes `:status`. @param last when true, there is no response data.","code":"fun onHeaders(\n streamId: Int,\n responseHeaders: List
,\n last: Boolean,\n ): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":75,"symbol":"onData","kind":"function","lang":"kotlin","doc":"@param streamId server-initiated stream ID: an even number. @param source location of data corresponding with this stream ID. @param byteCount number of bytes to read or skip from the source. @param last when true, there are no data frames to follow.","code":"@Throws(IOException::class)\n fun onData(\n streamId: Int,\n source: BufferedSource,\n byteCount: Int,\n last: Boolean,\n ): Boolean"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":84,"symbol":"onReset","kind":"function","lang":"kotlin","doc":"Indicates the reason why this stream was canceled.","code":"fun onReset(\n streamId: Int,\n errorCode: ErrorCode,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":92,"symbol":"PushObserverCancel","kind":"class","lang":"kotlin","code":"private class PushObserverCancel : PushObserver {\n override fun onRequest(\n streamId: Int,\n requestHeaders: List
,\n ): Boolean = true\n\n override fun onHeaders(\n streamId: Int,\n responseHeaders: List
,\n last: Boolean,\n ): Boolean = true\n\n @Throws(IOException::class)\n override fun onData(\n streamId: Int,\n source: BufferedSource,\n byteCount: Int,\n last: Boolean,\n ): Boolean {\n source.skip(byteCount.toLong())\n return true\n }\n\n override fun onReset(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":93,"symbol":"onRequest","kind":"function","lang":"kotlin","code":"override fun onRequest(\n streamId: Int,\n requestHeaders: List
,\n ): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":98,"symbol":"onHeaders","kind":"function","lang":"kotlin","code":"override fun onHeaders(\n streamId: Int,\n responseHeaders: List
,\n last: Boolean,\n ): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":104,"symbol":"onData","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onData(\n streamId: Int,\n source: BufferedSource,\n byteCount: Int,\n last: Boolean,\n ): Boolean {\n source.skip(byteCount.toLong())\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/PushObserver.kt","line":115,"symbol":"onReset","kind":"function","lang":"kotlin","code":"override fun onReset(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":22,"symbol":"Settings","kind":"class","lang":"kotlin","doc":"Settings describe characteristics of the sending peer, which are used by the receiving peer. Settings are [connection][Http2Connection] scoped.","code":"class Settings {\n /** Bitfield of which flags that values. */\n private var set: Int = 0\n\n /** Flag values. */\n private val values = IntArray(COUNT)\n\n /** Returns -1 if unset. */\n val headerTableSize: Int\n get() {\n val bit = 1 shl HEADER_TABLE_SIZE\n return if (bit and set != 0) values[HEADER_TABLE_SIZE] else -1\n }\n\n val initialWindowSize: Int\n get() {\n val bit = 1 shl INITIAL_WINDOW_SIZE\n return if (bit and set != 0) values[INITIAL_WINDOW_SIZE] else DEFAULT_INITIAL_WINDOW_SIZE\n }\n\n fun clear() {\n set = 0\n values.fill(0)\n }\n\n operator fun set(\n id: Int,\n value: Int,\n ): Settings {\n if (id < 0 || id >= values.size) {\n return this // Discard unknown settings.\n }\n\n val bit = 1 shl id\n set = set or bit\n values[id] = value\n return this\n }\n\n /** Returns true if a value has been assigned for the setting `id`. */\n fun isSet(id: Int): Boolean {\n val bit = 1 shl id\n return set and bit != 0\n }\n\n /** Returns the value for the setting `id`, or 0 if unset. */\n operator fun get(id: Int): Int = values[id]\n\n /** Returns the number of settings that have values assigned. */\n fun size(): Int = Integer.bitCount(se"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":42,"symbol":"clear","kind":"function","lang":"kotlin","code":"fun clear() {\n set = 0\n values.fill(0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":47,"symbol":"set","kind":"function","lang":"kotlin","code":"operator fun set(\n id: Int,\n value: Int,\n ): Settings {\n if (id < 0 || id >= values.size) {\n return this // Discard unknown settings.\n }\n\n val bit = 1 shl id\n set = set or bit\n values[id] = value\n return this\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":62,"symbol":"isSet","kind":"function","lang":"kotlin","doc":"Returns true if a value has been assigned for the setting `id`.","code":"fun isSet(id: Int): Boolean {\n val bit = 1 shl id\n return set and bit != 0\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":68,"symbol":"get","kind":"function","lang":"kotlin","doc":"Returns the value for the setting `id`, or 0 if unset.","code":"operator fun get(id: Int): Int = values[id]"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":71,"symbol":"size","kind":"function","lang":"kotlin","doc":"Returns the number of settings that have values assigned.","code":"fun size(): Int = Integer.bitCount(set)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":74,"symbol":"getEnablePush","kind":"function","lang":"kotlin","doc":"TODO: honor this setting.","code":"fun getEnablePush(defaultValue: Boolean): Boolean {\n val bit = 1 shl ENABLE_PUSH\n return if (bit and set != 0) values[ENABLE_PUSH] == 1 else defaultValue\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":79,"symbol":"getMaxConcurrentStreams","kind":"function","lang":"kotlin","code":"fun getMaxConcurrentStreams(): Int {\n val bit = 1 shl MAX_CONCURRENT_STREAMS\n return if (bit and set != 0) values[MAX_CONCURRENT_STREAMS] else Int.MAX_VALUE\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":84,"symbol":"getMaxFrameSize","kind":"function","lang":"kotlin","code":"fun getMaxFrameSize(defaultValue: Int): Int {\n val bit = 1 shl MAX_FRAME_SIZE\n return if (bit and set != 0) values[MAX_FRAME_SIZE] else defaultValue\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":89,"symbol":"getMaxHeaderListSize","kind":"function","lang":"kotlin","code":"fun getMaxHeaderListSize(defaultValue: Int): Int {\n val bit = 1 shl MAX_HEADER_LIST_SIZE\n return if (bit and set != 0) values[MAX_HEADER_LIST_SIZE] else defaultValue\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Settings.kt","line":98,"symbol":"merge","kind":"function","lang":"kotlin","doc":"Writes `other` into this. If any setting is populated by this and `other`, the value and flags from `other` will be kept.","code":"fun merge(other: Settings) {\n for (i in 0 until COUNT) {\n if (!other.isSet(i)) continue\n set(i, other[i])\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/flowcontrol/WindowCounter.kt","line":18,"symbol":"WindowCounter","kind":"class","lang":"kotlin","code":"class WindowCounter(\n val streamId: Int,\n) {\n /** The total number of bytes consumed. */\n var total: Long = 0L\n private set\n\n /** The total number of bytes acknowledged by outgoing `WINDOW_UPDATE` frames. */\n var acknowledged: Long = 0L\n private set\n\n val unacknowledged: Long\n @Synchronized get() = total - acknowledged\n\n @Synchronized\n fun update(\n total: Long = 0,\n acknowledged: Long = 0,\n ) {\n check(total >= 0)\n check(acknowledged >= 0)\n\n this.total += total\n this.acknowledged += acknowledged\n\n check(this.acknowledged <= this.total)\n }\n\n override fun toString(): String =\n \"WindowCounter(streamId=$streamId, total=$total, acknowledged=$acknowledged, unacknowledged=$unacknowledged)\"\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/flowcontrol/WindowCounter.kt","line":32,"symbol":"update","kind":"function","lang":"kotlin","code":"@Synchronized\n fun update(\n total: Long = 0,\n acknowledged: Long = 0,\n ) {\n check(total >= 0)\n check(acknowledged >= 0)\n\n this.total += total\n this.acknowledged += acknowledged\n\n check(this.acknowledged <= this.total)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/flowcontrol/WindowCounter.kt","line":46,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n \"WindowCounter(streamId=$streamId, total=$total, acknowledged=$acknowledged, unacknowledged=$unacknowledged)\""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/IdnaMappingTable.kt","line":108,"symbol":"IdnaMappingTable","kind":"class","lang":"kotlin","doc":"Neither the section index nor the ranges data use bit 0x80 anywhere. That means the data is strictly ASCII. This is intended to make it efficient to encode this data as a string, and to index into it as a string. The mappings data contains non-ASCII characters.","code":"internal class IdnaMappingTable internal constructor(\n val sections: String,\n val ranges: String,\n val mappings: String,\n) {\n /**\n * Returns true if the [codePoint] was applied successfully. Returns false if it was disallowed.\n */\n fun map(\n codePoint: Int,\n sink: BufferedSink,\n ): Boolean {\n val sectionsIndex = findSectionsIndex(codePoint)\n\n val rangesPosition = sections.read14BitInt(sectionsIndex + 2)\n\n val rangesLimit =\n when {\n sectionsIndex + 4 < sections.length -> sections.read14BitInt(sectionsIndex + 6)\n else -> ranges.length / 4\n }\n\n val rangesIndex = findRangesOffset(codePoint, rangesPosition, rangesLimit)\n\n when (val b1 = ranges[rangesIndex + 1].code) {\n in 0..63 -> {\n // Length of the UTF-16 sequence that this range maps to. The offset is b2b3.\n val beginIndex = ranges.read14BitInt(rangesIndex + 2)\n sink.writeUtf8(mappings, beginIndex, beginIndex + b1)\n }\n\n in 64..79 -> {\n // Mapped inline as codePoint delta to subtract\n val b2 = ranges[rangesIndex + 2].code\n val b3 = ranges[rangesIndex + 3].code\n\n val codepointDelta = (b1 and 0xF shl 14) or (b2 shl 7) o"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/IdnaMappingTable.kt","line":116,"symbol":"map","kind":"function","lang":"kotlin","doc":"Returns true if the [codePoint] was applied successfully. Returns false if it was disallowed.","code":"fun map(\n codePoint: Int,\n sink: BufferedSink,\n ): Boolean {\n val sectionsIndex = findSectionsIndex(codePoint)\n\n val rangesPosition = sections.read14BitInt(sectionsIndex + 2)\n\n val rangesLimit =\n when {\n sectionsIndex + 4 < sections.length -> sections.read14BitInt(sectionsIndex + 6)\n else -> ranges.length / 4\n }\n\n val rangesIndex = findRangesOffset(codePoint, rangesPosition, rangesLimit)\n\n when (val b1 = ranges[rangesIndex + 1].code) {\n in 0..63 -> {\n // Length of the UTF-16 sequence that this range maps to. The offset is b2b3.\n val beginIndex = ranges.read14BitInt(rangesIndex + 2)\n sink.writeUtf8(mappings, beginIndex, beginIndex + b1)\n }\n\n in 64..79 -> {\n // Mapped inline as codePoint delta to subtract\n val b2 = ranges[rangesIndex + 2].code\n val b3 = ranges[rangesIndex + 3].code\n\n val codepointDelta = (b1 and 0xF shl 14) or (b2 shl 7) or b3\n sink.writeUtf8CodePoint(codePoint - codepointDelta)\n }\n\n in 80..95 -> {\n // Mapped inline as codePoint delta to add\n val b2 = ranges[rangesIndex + 2].code\n val b3 = ranges[rangesIndex + 3].code\n\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/IdnaMappingTable.kt","line":220,"symbol":"findSectionsIndex","kind":"function","lang":"kotlin","doc":"Binary search [sections] for [codePoint], looking at its top 14 bits. This binary searches over 4-byte entries, and so it needs to adjust binary search indices in (by dividing by 4) and out (by multiplying by 4).","code":"private fun findSectionsIndex(codePoint: Int): Int {\n val target = (codePoint and 0x1fff80) shr 7\n val offset =\n binarySearch(\n position = 0,\n limit = sections.length / 4,\n ) { index ->\n val entryIndex = index * 4\n val b0b1 = sections.read14BitInt(entryIndex)\n return@binarySearch target.compareTo(b0b1)\n }\n\n return when {\n offset >= 0 -> offset * 4\n\n // This section was found by binary search.\n else -> (-offset - 2) * 4 // Not found? Use the preceding element.\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/IdnaMappingTable.kt","line":246,"symbol":"findRangesOffset","kind":"function","lang":"kotlin","doc":"Binary search [ranges] for [codePoint], looking at its bottom 7 bits. This binary searches over 4-byte entries, and so it needs to adjust binary search indices in (by dividing by 4) and out (by multiplying by 4).","code":"private fun findRangesOffset(\n codePoint: Int,\n position: Int,\n limit: Int,\n ): Int {\n val target = codePoint and 0x7f\n val offset =\n binarySearch(\n position = position,\n limit = limit,\n ) { index ->\n val entryIndex = index * 4\n val b0 = ranges[entryIndex].code\n return@binarySearch target.compareTo(b0)\n }\n\n return when {\n offset >= 0 -> offset * 4\n\n // This entry was found by binary search.\n else -> (-offset - 2) * 4 // Not found? Use the preceding element.\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/IdnaMappingTable.kt","line":271,"symbol":"read14BitInt","kind":"function","lang":"kotlin","code":"internal fun String.read14BitInt(index: Int): Int {\n val b0 = this[index].code\n val b1 = this[index + 1].code\n return (b0 shl 7) + b1\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/IdnaMappingTable.kt","line":284,"symbol":"binarySearch","kind":"function","lang":"kotlin","doc":"An extremely generic binary search that doesn't know what data it's searching over. The caller provides indexes and a comparison function, and this calls that function iteratively. @return the index of the match. If no match is found this is `(-1 - insertionPoint)`, where the inserting the element at `insertionPoint` will retain sorted order.","code":"inline fun binarySearch(\n position: Int,\n limit: Int,\n compare: (Int) -> Int,\n): Int {\n // Do the binary searching bit.\n var low = position\n var high = limit - 1\n while (low <= high) {\n val mid = (low + high) / 2\n val compareResult = compare(mid)\n when {\n compareResult < 0 -> high = mid - 1\n compareResult > 0 -> low = mid + 1\n else -> return mid // Match!\n }\n }\n\n return -low - 1 // insertionPoint is before the first element.\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/Punycode.kt","line":34,"symbol":"Punycode","kind":"object","lang":"kotlin","doc":"Partner this class with [UTS #46] to implement IDNA2008 [RFC 5890] like most browsers do. [RFC 3492]: https://datatracker.ietf.org/doc/html/rfc3492 [RFC 5890]: https://datatracker.ietf.org/doc/html/rfc5890 [UTS #46]: https://www.unicode.org/reports/tr46/","code":"object Punycode {\n val PREFIX_STRING = \"xn--\"\n val PREFIX = PREFIX_STRING.encodeUtf8()\n\n private const val BASE = 36\n private const val TMIN = 1\n private const val TMAX = 26\n private const val SKEW = 38\n private const val DAMP = 700\n private const val INITIAL_BIAS = 72\n private const val INITIAL_N = 0x80\n\n /**\n * Returns null if any label is oversized so much that the encoder cannot encode it without\n * integer overflow. This will not return null for labels that fit within the DNS size\n * limits.\n */\n fun encode(string: String): String? {\n var pos = 0\n val limit = string.length\n val result = Buffer()\n\n while (pos < limit) {\n var dot = string.indexOf('.', startIndex = pos)\n if (dot == -1) dot = limit\n\n if (!encodeLabel(string, pos, dot, result)) {\n // If we couldn't encode the label, give up.\n return null\n }\n\n if (dot < limit) {\n result.writeByte('.'.code)\n pos = dot + 1\n } else {\n break\n }\n }\n\n return result.readUtf8()\n }\n\n private fun encodeLabel(\n string: String,\n pos: Int,\n limit: Int,\n result: Buffer,\n ): Boolean {\n if (!string.requiresEncode(pos, limit))"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/Punycode.kt","line":51,"symbol":"encode","kind":"function","lang":"kotlin","doc":"Returns null if any label is oversized so much that the encoder cannot encode it without integer overflow. This will not return null for labels that fit within the DNS size limits.","code":"fun encode(string: String): String? {\n var pos = 0\n val limit = string.length\n val result = Buffer()\n\n while (pos < limit) {\n var dot = string.indexOf('.', startIndex = pos)\n if (dot == -1) dot = limit\n\n if (!encodeLabel(string, pos, dot, result)) {\n // If we couldn't encode the label, give up.\n return null\n }\n\n if (dot < limit) {\n result.writeByte('.'.code)\n pos = dot + 1\n } else {\n break\n }\n }\n\n return result.readUtf8()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/Punycode.kt","line":76,"symbol":"encodeLabel","kind":"function","lang":"kotlin","code":"private fun encodeLabel(\n string: String,\n pos: Int,\n limit: Int,\n result: Buffer,\n ): Boolean {\n if (!string.requiresEncode(pos, limit)) {\n result.writeUtf8(string, pos, limit)\n return true\n }\n\n result.write(PREFIX)\n\n val input = string.codePoints(pos, limit)\n\n // Copy all the basic code points to the output.\n var b = 0\n for (codePoint in input) {\n if (codePoint < INITIAL_N) {\n result.writeByte(codePoint)\n b++\n }\n }\n\n // Copy a delimiter if any basic code points were emitted.\n if (b > 0) result.writeByte('-'.code)\n\n var n = INITIAL_N\n var delta = 0\n var bias = INITIAL_BIAS\n var h = b\n while (h < input.size) {\n val m = input.minBy { if (it >= n) it else Int.MAX_VALUE }\n\n val increment = (m - n) * (h + 1)\n if (delta > Int.MAX_VALUE - increment) return false // Prevent overflow.\n delta += increment\n\n n = m\n\n for (c in input) {\n if (c < n) {\n if (delta == Int.MAX_VALUE) return false // Prevent overflow.\n delta++\n } else if (c == n) {\n var q = delta\n\n for (k in BASE until Int.MAX_VALUE step BASE) {\n val t "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/Punycode.kt","line":152,"symbol":"decode","kind":"function","lang":"kotlin","doc":"Converts a punycode-encoded domain name with `.`-separated labels into a human-readable Internationalized Domain Name.","code":"fun decode(string: String): String? {\n var pos = 0\n val limit = string.length\n val result = Buffer()\n\n while (pos < limit) {\n var dot = string.indexOf('.', startIndex = pos)\n if (dot == -1) dot = limit\n\n if (!decodeLabel(string, pos, dot, result)) return null\n\n if (dot < limit) {\n result.writeByte('.'.code)\n pos = dot + 1\n } else {\n break\n }\n }\n\n return result.readUtf8()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/Punycode.kt","line":180,"symbol":"decodeLabel","kind":"function","lang":"kotlin","doc":"Converts a single label from Punycode to Unicode. @return true if the range of [string] from [pos] to [limit] was valid and decoded successfully. Otherwise, the decode failed.","code":"private fun decodeLabel(\n string: String,\n pos: Int,\n limit: Int,\n result: Buffer,\n ): Boolean {\n if (!string.regionMatches(pos, PREFIX_STRING, 0, 4, ignoreCase = true)) {\n result.writeUtf8(string, pos, limit)\n return true\n }\n\n var pos = pos + 4 // 'xn--'.size.\n\n // We'd prefer to operate directly on `result` but it doesn't offer insertCodePoint(), only\n // appendCodePoint(). The Punycode algorithm processes code points in increasing code-point\n // order, not in increasing index order.\n val codePoints = mutableListOf()\n\n // consume all code points before the last delimiter (if there is one)\n // and copy them to output, fail on any non-basic code point\n val lastDelimiter = string.lastIndexOf('-', limit)\n if (lastDelimiter >= pos) {\n while (pos < lastDelimiter) {\n when (val codePoint = string[pos++]) {\n in 'a'..'z', in 'A'..'Z', in '0'..'9', '-' -> {\n codePoints += codePoint.code\n }\n\n else -> {\n return false\n } // Malformed.\n }\n }\n pos++ // Consume '-'.\n }\n\n var n = INITIAL_N\n var i = 0\n var bias = INITIAL_BIAS\n\n while (po"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/Punycode.kt","line":268,"symbol":"adapt","kind":"function","lang":"kotlin","doc":"Returns a new bias.","code":"private fun adapt(\n delta: Int,\n numpoints: Int,\n first: Boolean,\n ): Int {\n var delta =\n when {\n first -> delta / DAMP\n else -> delta / 2\n }\n delta += (delta / numpoints)\n var k = 0\n while (delta > ((BASE - TMIN) * TMAX) / 2) {\n delta /= (BASE - TMIN)\n k += BASE\n }\n return k + (((BASE - TMIN + 1) * delta) / (delta + SKEW))\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/Punycode.kt","line":287,"symbol":"requiresEncode","kind":"function","lang":"kotlin","code":"private fun String.requiresEncode(\n pos: Int,\n limit: Int,\n ): Boolean {\n for (i in pos until limit) {\n if (this[i].code >= INITIAL_N) return true\n }\n return false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/idn/Punycode.kt","line":297,"symbol":"codePoints","kind":"function","lang":"kotlin","code":"private fun String.codePoints(\n pos: Int,\n limit: Int,\n ): List {\n val result = mutableListOf()\n var i = pos\n while (i < limit) {\n val c = this[i]\n result +=\n when {\n c.isSurrogate() -> {\n val low = (if (i + 1 < limit) this[i + 1] else '\\u0000')\n if (c.isLowSurrogate() || !low.isLowSurrogate()) {\n '?'.code\n } else {\n i++\n 0x010000 + (c.code and 0x03ff shl 10 or (low.code and 0x03ff))\n }\n }\n\n else -> {\n c.code\n }\n }\n i++\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":45,"symbol":"parseCookie","kind":"function","lang":"kotlin","code":"internal fun parseCookie(\n currentTimeMillis: Long,\n url: HttpUrl,\n setCookie: String,\n): Cookie? = Cookie.parse(currentTimeMillis, url, setCookie)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":51,"symbol":"cookieToString","kind":"function","lang":"kotlin","code":"internal fun cookieToString(\n cookie: Cookie,\n forObsoleteRfc2965: Boolean,\n): String = cookie.toString(forObsoleteRfc2965)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":56,"symbol":"addHeaderLenient","kind":"function","lang":"kotlin","code":"internal fun addHeaderLenient(\n builder: Headers.Builder,\n line: String,\n): Headers.Builder = builder.addLenient(line)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":61,"symbol":"addHeaderLenient","kind":"function","lang":"kotlin","code":"internal fun addHeaderLenient(\n builder: Headers.Builder,\n name: String,\n value: String,\n): Headers.Builder = builder.addLenient(name, value)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":67,"symbol":"cacheGet","kind":"function","lang":"kotlin","code":"internal fun cacheGet(\n cache: Cache,\n request: Request,\n): Response? = cache.get(request)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":72,"symbol":"applyConnectionSpec","kind":"function","lang":"kotlin","code":"internal fun applyConnectionSpec(\n connectionSpec: ConnectionSpec,\n sslSocket: SSLSocket,\n isFallback: Boolean,\n) = connectionSpec.apply(sslSocket, isFallback)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":78,"symbol":"effectiveCipherSuites","kind":"function","lang":"kotlin","code":"internal fun ConnectionSpec.effectiveCipherSuites(socketEnabledCipherSuites: Array): Array =\n if (cipherSuitesAsString != null) {\n // 3 options here for ordering\n // 1) Legacy Platform - based on the Platform/Provider existing ordering in\n // sslSocket.enabledCipherSuites\n // 2) OkHttp Client - based on MODERN_TLS source code ordering\n // 3) Caller specified but assuming the visible defaults in MODERN_CIPHER_SUITES are rejigged\n // to match legacy i.e. the platform/provider\n //\n // Opting for 2 here and keeping MODERN_TLS in line with secure browsers.\n cipherSuitesAsString.intersect(socketEnabledCipherSuites, CipherSuite.ORDER_BY_NAME)\n } else {\n socketEnabledCipherSuites\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":93,"symbol":"chooseCharset","kind":"function","lang":"kotlin","code":"internal fun MediaType?.chooseCharset(): Pair {\n var charset: Charset = Charsets.UTF_8\n var finalContentType: MediaType? = this\n if (this != null) {\n val resolvedCharset = this.charset()\n if (resolvedCharset == null) {\n charset = Charsets.UTF_8\n finalContentType = \"$this; charset=utf-8\".toMediaTypeOrNull()\n } else {\n charset = resolvedCharset\n }\n }\n return charset to finalContentType\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":108,"symbol":"charsetOrUtf8","kind":"function","lang":"kotlin","code":"internal fun MediaType?.charsetOrUtf8(): Charset = this?.charset() ?: Charsets.UTF_8"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":113,"symbol":"taskRunnerInternal","kind":"function","lang":"kotlin","code":"internal fun OkHttpClient.Builder.taskRunnerInternal(taskRunner: TaskRunner) = this.taskRunner(taskRunner)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/internal.kt","line":115,"symbol":"buildConnectionPool","kind":"function","lang":"kotlin","code":"internal fun buildConnectionPool(\n connectionListener: ConnectionListener,\n taskRunner: TaskRunner,\n): ConnectionPool =\n ConnectionPool(\n connectionListener = connectionListener,\n taskRunner = taskRunner,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Jdk9Platform.kt","line":32,"symbol":"Jdk9Platform","kind":"class","lang":"kotlin","doc":"OpenJDK 9+ and JDK8 build 252+. This may also be used for Android tests with Robolectric.","code":"@Suppress(\"NewApi\")\nopen class Jdk9Platform : Platform() {\n @SuppressSignatureCheck\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n val sslParameters = sslSocket.sslParameters\n\n val names = alpnProtocolNames(protocols)\n\n sslParameters.applicationProtocols = names.toTypedArray()\n\n sslSocket.sslParameters = sslParameters\n }\n\n @SuppressSignatureCheck\n override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n try {\n // SSLSocket.getApplicationProtocol returns \"\" if application protocols values will not\n // be used. Observed if you didn't specify SSLParameters.setApplicationProtocols\n when (val protocol = sslSocket.applicationProtocol) {\n null, \"\" -> null\n else -> protocol\n }\n } catch (e: UnsupportedOperationException) {\n // https://docs.oracle.com/javase/9/docs/api/javax/net/ssl/SSLSocket.html#getApplicationProtocol--\n null\n }\n\n override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? {\n // Not supported due to access checks on JDK 9+:\n // java.lang"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Jdk9Platform.kt","line":34,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"@SuppressSignatureCheck\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n val sslParameters = sslSocket.sslParameters\n\n val names = alpnProtocolNames(protocols)\n\n sslParameters.applicationProtocols = names.toTypedArray()\n\n sslSocket.sslParameters = sslParameters\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Jdk9Platform.kt","line":50,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"@SuppressSignatureCheck\n override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n try {\n // SSLSocket.getApplicationProtocol returns \"\" if application protocols values will not\n // be used. Observed if you didn't specify SSLParameters.setApplicationProtocols\n when (val protocol = sslSocket.applicationProtocol) {\n null, \"\" -> null\n else -> protocol\n }\n } catch (e: UnsupportedOperationException) {\n // https://docs.oracle.com/javase/9/docs/api/javax/net/ssl/SSLSocket.html#getApplicationProtocol--\n null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Jdk9Platform.kt","line":64,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? {\n // Not supported due to access checks on JDK 9+:\n // java.lang.reflect.InaccessibleObjectException: Unable to make member of class\n // sun.security.ssl.SSLSocketFactoryImpl accessible: module java.base does not export\n // sun.security.ssl to unnamed module @xxx\n throw UnsupportedOperationException(\n \"clientBuilder.sslSocketFactory(SSLSocketFactory) not supported on JDK 8 (>= 252) or JDK 9+\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Jdk9Platform.kt","line":74,"symbol":"newSSLContext","kind":"function","lang":"kotlin","code":"override fun newSSLContext(): SSLContext =\n when {\n majorVersion != null && majorVersion >= 9 -> {\n SSLContext.getInstance(\"TLS\")\n }\n\n else -> {\n try {\n // Based on SSLSocket.getApplicationProtocol check we should\n // have TLSv1.3 if we request it.\n // See https://www.oracle.com/java/technologies/javase/8u261-relnotes.html\n SSLContext.getInstance(\"TLSv1.3\")\n } catch (nsae: NoSuchAlgorithmException) {\n SSLContext.getInstance(\"TLS\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Jdk9Platform.kt","line":112,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): Jdk9Platform? = if (isAvailable) Jdk9Platform() else null"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":80,"symbol":"Platform","kind":"class","lang":"kotlin","doc":"Not supported by choice on JDK9+ due to access checks. ### Android Cleartext Permit Detection Supported on Android 6.0+ via `NetworkSecurityPolicy`.","code":"@OkHttpInternalApi\nopen class Platform {\n open val socketFactory: SocketFactory\n get() = SocketFactory.getDefault()\n\n open val serverSocketFactory: ServerSocketFactory\n get() = ServerSocketFactory.getDefault()\n\n /** The default [Dns] for the system, by default [InetAddressDns]. */\n open val systemDns: Dns\n get() = InetAddressDns\n\n /** Prefix used on custom headers. */\n val prefix: String\n get() = \"OkHttp\"\n\n open fun newSSLContext(): SSLContext = SSLContext.getInstance(\"TLS\")\n\n open fun platformTrustManager(): X509TrustManager {\n val factory =\n TrustManagerFactory.getInstance(\n TrustManagerFactory.getDefaultAlgorithm(),\n )\n factory.init(null as KeyStore?)\n val trustManagers = factory.trustManagers!!\n check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {\n \"Unexpected default trust managers: ${trustManagers.contentToString()}\"\n }\n return trustManagers[0] as X509TrustManager\n }\n\n open fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? {\n return try {\n // Attempt to get the trust manager from an OpenJDK socket factory. We attempt this on all\n // platforms in order to suppor"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":96,"symbol":"newSSLContext","kind":"function","lang":"kotlin","code":"open fun newSSLContext(): SSLContext = SSLContext.getInstance(\"TLS\")"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":98,"symbol":"platformTrustManager","kind":"function","lang":"kotlin","code":"open fun platformTrustManager(): X509TrustManager {\n val factory =\n TrustManagerFactory.getInstance(\n TrustManagerFactory.getDefaultAlgorithm(),\n )\n factory.init(null as KeyStore?)\n val trustManagers = factory.trustManagers!!\n check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {\n \"Unexpected default trust managers: ${trustManagers.contentToString()}\"\n }\n return trustManagers[0] as X509TrustManager\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":111,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"open fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? {\n return try {\n // Attempt to get the trust manager from an OpenJDK socket factory. We attempt this on all\n // platforms in order to support Robolectric, which mixes classes from both Android and the\n // Oracle JDK. Note that we don't support HTTP/2 or other nice features on Robolectric.\n val sslContextClass = Class.forName(\"sun.security.ssl.SSLContextImpl\")\n val context = readFieldOrNull(sslSocketFactory, sslContextClass, \"context\") ?: return null\n readFieldOrNull(context, X509TrustManager::class.java, \"trustManager\")\n } catch (e: ClassNotFoundException) {\n null\n } catch (e: RuntimeException) {\n // Throws InaccessibleObjectException (added in JDK9) on JDK 17 due to\n // JEP 403 Strongly Encapsulate JDK Internals.\n if (e.javaClass.name != \"java.lang.reflect.InaccessibleObjectException\") {\n throw e\n }\n\n null\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":135,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","doc":"Configure TLS extensions on `sslSocket` for `route`.","code":"open fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":144,"symbol":"echRetryPlan","kind":"function","lang":"kotlin","doc":"Returns a plan to recover when a handshake that failed due to Encrypted Client Hello.","code":"open fun echRetryPlan(exception: SSLException): EchRetryPlan? = null"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":147,"symbol":"afterHandshake","kind":"function","lang":"kotlin","doc":"Called after the TLS handshake to release resources allocated by [configureTlsExtensions].","code":"open fun afterHandshake(sslSocket: SSLSocket) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":151,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","doc":"Returns the negotiated protocol, or null if no protocol was negotiated.","code":"open fun getSelectedProtocol(sslSocket: SSLSocket): String? = null"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":154,"symbol":"getHandshakeServerNames","kind":"function","lang":"kotlin","doc":"For MockWebServer. This returns the inbound SNI names.","code":"@Suppress(\"NewApi\")\n @IgnoreJRERequirement // This function is overridden to require API >= 24.\n open fun getHandshakeServerNames(sslSocket: SSLSocket): List {\n val session = sslSocket.session as? ExtendedSSLSession ?: return listOf()\n return try {\n session.requestedServerNames.mapNotNull { (it as? SNIHostName)?.asciiName }\n } catch (_: UnsupportedOperationException) {\n // UnsupportedOperationException – if the underlying provider does not implement the operation\n // https://github.com/bcgit/bc-java/issues/1773\n listOf()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":167,"symbol":"connectSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n open fun connectSocket(\n socket: Socket,\n address: InetSocketAddress,\n connectTimeout: Int,\n ) {\n socket.connect(address, connectTimeout)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":176,"symbol":"log","kind":"function","lang":"kotlin","code":"open fun log(\n message: String,\n level: Int = INFO,\n t: Throwable? = null,\n ) {\n val logLevel = if (level == WARN) Level.WARNING else Level.INFO\n logger.log(logLevel, message, t)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":185,"symbol":"isCleartextTrafficPermitted","kind":"function","lang":"kotlin","code":"open fun isCleartextTrafficPermitted(hostname: String): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":192,"symbol":"getStackTraceForCloseable","kind":"function","lang":"kotlin","doc":"Returns an object that holds a stack trace created at the moment this method is executed. This should be used specifically for [java.io.Closeable] objects and in conjunction with [logCloseableLeak].","code":"open fun getStackTraceForCloseable(closer: String): Any? =\n when {\n logger.isLoggable(Level.FINE) -> Throwable(closer)\n\n // These are expensive to allocate.\n else -> null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":200,"symbol":"logCloseableLeak","kind":"function","lang":"kotlin","code":"open fun logCloseableLeak(\n message: String,\n stackTrace: Any?,\n ) {\n var logMessage = message\n if (stackTrace == null) {\n logMessage += \" To see where this was allocated, set the OkHttpClient logger level to \" +\n \"FINE: Logger.getLogger(OkHttpClient.class.getName()).setLevel(Level.FINE);\"\n }\n log(logMessage, WARN, stackTrace as Throwable?)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":212,"symbol":"buildCertificateChainCleaner","kind":"function","lang":"kotlin","code":"open fun buildCertificateChainCleaner(trustManager: X509TrustManager): CertificateChainCleaner =\n BasicCertificateChainCleaner(buildTrustRootIndex(trustManager))"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":215,"symbol":"buildTrustRootIndex","kind":"function","lang":"kotlin","code":"open fun buildTrustRootIndex(trustManager: X509TrustManager): TrustRootIndex = BasicTrustRootIndex(*trustManager.acceptedIssuers)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":217,"symbol":"newSslSocketFactory","kind":"function","lang":"kotlin","code":"open fun newSslSocketFactory(trustManager: X509TrustManager): SSLSocketFactory {\n try {\n return newSSLContext()\n .apply {\n init(null, arrayOf(trustManager), null)\n }.socketFactory\n } catch (e: GeneralSecurityException) {\n throw AssertionError(\"No System TLS: $e\", e) // The system has no TLS. Just give up.\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":228,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = javaClass.simpleName"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":238,"symbol":"get","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun get(): Platform = platform"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":241,"symbol":"resetForTests","kind":"function","lang":"kotlin","code":"fun resetForTests(platform: Platform = findPlatform()) {\n this.platform = platform\n PublicSuffixDatabase.resetForTests()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":246,"symbol":"alpnProtocolNames","kind":"function","lang":"kotlin","code":"fun alpnProtocolNames(protocols: List) = protocols.filter { it != Protocol.HTTP_1_0 }.map { it.toString() }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":252,"symbol":"findPlatform","kind":"function","lang":"kotlin","doc":"Attempt to match the host runtime to a capable Platform implementation.","code":"private fun findPlatform(): Platform = PlatformRegistry.findPlatform()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/Platform.kt","line":258,"symbol":"concatLengthPrefixed","kind":"function","lang":"kotlin","doc":"Returns the concatenation of 8-bit, length prefixed protocol names. http://tools.ietf.org/html/draft-agl-tls-nextprotoneg-04#page-4","code":"fun concatLengthPrefixed(protocols: List): ByteArray {\n val result = Buffer()\n for (protocol in alpnProtocolNames(protocols)) {\n result.writeByte(protocol.length)\n result.writeUtf8(protocol)\n }\n return result.readByteArray()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/PlatformRegistry.kt","line":18,"symbol":"PlatformRegistry","kind":"object","lang":"kotlin","code":"expect object PlatformRegistry {\n fun findPlatform(): Platform\n\n val isAndroid: Boolean\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/platform/PlatformRegistry.kt","line":19,"symbol":"findPlatform","kind":"function","lang":"kotlin","code":"fun findPlatform(): Platform"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/proxy/NullProxySelector.kt","line":27,"symbol":"NullProxySelector","kind":"object","lang":"kotlin","doc":"A proxy selector that always returns the [Proxy.NO_PROXY].","code":"object NullProxySelector : ProxySelector() {\n override fun select(uri: URI?): List {\n requireNotNull(uri) { \"uri must not be null\" }\n return listOf(Proxy.NO_PROXY)\n }\n\n override fun connectFailed(\n uri: URI?,\n sa: SocketAddress?,\n ioe: IOException?,\n ) {\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/proxy/NullProxySelector.kt","line":28,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI?): List {\n requireNotNull(uri) { \"uri must not be null\" }\n return listOf(Proxy.NO_PROXY)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/proxy/NullProxySelector.kt","line":33,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI?,\n sa: SocketAddress?,\n ioe: IOException?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/BasePublicSuffixList.kt","line":26,"symbol":"BasePublicSuffixList","kind":"class","lang":"kotlin","code":"internal abstract class BasePublicSuffixList : PublicSuffixList {\n /** True after we've attempted to read the list for the first time. */\n private val listRead = AtomicBoolean(false)\n\n /** Used for concurrent threads reading the list for the first time. */\n private val readCompleteLatch = CountDownLatch(1)\n\n // The lists are held as a large array of UTF-8 bytes. This is to avoid allocating lots of strings\n // that will likely never be used. Each rule is separated by '\\n'. Please see the\n // PublicSuffixListGenerator class for how these lists are generated.\n // Guarded by this.\n override lateinit var bytes: ByteString\n override lateinit var exceptionBytes: ByteString\n\n private var readFailure: IOException? = null\n\n @Throws(IOException::class)\n private fun readTheList() {\n var publicSuffixListBytes: ByteString?\n var publicSuffixExceptionListBytes: ByteString?\n\n try {\n listSource().buffer().use { bufferedSource ->\n val totalBytes = bufferedSource.readInt()\n publicSuffixListBytes = bufferedSource.readByteString(totalBytes.toLong())\n\n val totalExceptionBytes = bufferedSource.readInt()\n publicSuffixExceptionListBytes = bufferedSource"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/BasePublicSuffixList.kt","line":42,"symbol":"readTheList","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readTheList() {\n var publicSuffixListBytes: ByteString?\n var publicSuffixExceptionListBytes: ByteString?\n\n try {\n listSource().buffer().use { bufferedSource ->\n val totalBytes = bufferedSource.readInt()\n publicSuffixListBytes = bufferedSource.readByteString(totalBytes.toLong())\n\n val totalExceptionBytes = bufferedSource.readInt()\n publicSuffixExceptionListBytes = bufferedSource.readByteString(totalExceptionBytes.toLong())\n }\n\n synchronized(this) {\n this.bytes = publicSuffixListBytes!!\n this.exceptionBytes = publicSuffixExceptionListBytes!!\n }\n } finally {\n readCompleteLatch.countDown()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/BasePublicSuffixList.kt","line":65,"symbol":"listSource","kind":"function","lang":"kotlin","code":"abstract fun listSource(): Source"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/BasePublicSuffixList.kt","line":67,"symbol":"ensureLoaded","kind":"function","lang":"kotlin","code":"override fun ensureLoaded() {\n if (!listRead.get() && listRead.compareAndSet(false, true)) {\n readTheListUninterruptibly()\n } else {\n try {\n readCompleteLatch.await()\n } catch (_: InterruptedException) {\n Thread.currentThread().interrupt() // Retain interrupted status.\n }\n }\n\n if (!::bytes.isInitialized) {\n // May have failed with an IOException\n throw IllegalStateException(\"Unable to load $path resource.\").apply {\n initCause(readFailure)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/BasePublicSuffixList.kt","line":93,"symbol":"readTheListUninterruptibly","kind":"function","lang":"kotlin","doc":"Reads the public suffix list treating the operation as uninterruptible. We always want to read the list otherwise we'll be left in a bad state. If the thread was interrupted prior to this operation, it will be re-interrupted after the list is read.","code":"private fun readTheListUninterruptibly() {\n var interrupted = false\n try {\n while (true) {\n try {\n readTheList()\n return\n } catch (_: InterruptedIOException) {\n Thread.interrupted() // Temporarily clear the interrupted state.\n interrupted = true\n } catch (e: IOException) {\n readFailure = e\n return\n }\n }\n } finally {\n if (interrupted) {\n Thread.currentThread().interrupt() // Retain interrupted status.\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt","line":28,"symbol":"PublicSuffixDatabase","kind":"class","lang":"kotlin","doc":"A database of public suffixes provided by [publicsuffix.org][publicsuffix_org]. [publicsuffix_org]: https://publicsuffix.org/","code":"class PublicSuffixDatabase internal constructor(\n private val publicSuffixList: PublicSuffixList,\n) {\n /**\n * Returns the effective top-level domain plus one (eTLD+1) by referencing the public suffix list.\n * Returns null if the domain is a public suffix or a private address.\n *\n * Here are some examples:\n *\n * ```java\n * assertEquals(\"google.com\", getEffectiveTldPlusOne(\"google.com\"));\n * assertEquals(\"google.com\", getEffectiveTldPlusOne(\"www.google.com\"));\n * assertNull(getEffectiveTldPlusOne(\"com\"));\n * assertNull(getEffectiveTldPlusOne(\"localhost\"));\n * assertNull(getEffectiveTldPlusOne(\"mymacbook\"));\n * ```\n *\n * @param domain A canonicalized domain. An International Domain Name (IDN) should be punycode\n * encoded.\n */\n fun getEffectiveTldPlusOne(domain: String): String? {\n // We use UTF-8 in the list so we need to convert to Unicode.\n val unicodeDomain = IDN.toUnicode(domain)\n val domainLabels = splitDomain(unicodeDomain)\n\n val rule = findMatchingRule(domainLabels)\n if (domainLabels.size == rule.size && rule[0][0] != EXCEPTION_MARKER) {\n return null // The domain is a public suffix.\n }\n\n val firstLabelOffset =\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt","line":48,"symbol":"getEffectiveTldPlusOne","kind":"function","lang":"kotlin","doc":"assertNull(getEffectiveTldPlusOne(\"mymacbook\")); ``` @param domain A canonicalized domain. An International Domain Name (IDN) should be punycode encoded.","code":"fun getEffectiveTldPlusOne(domain: String): String? {\n // We use UTF-8 in the list so we need to convert to Unicode.\n val unicodeDomain = IDN.toUnicode(domain)\n val domainLabels = splitDomain(unicodeDomain)\n\n val rule = findMatchingRule(domainLabels)\n if (domainLabels.size == rule.size && rule[0][0] != EXCEPTION_MARKER) {\n return null // The domain is a public suffix.\n }\n\n val firstLabelOffset =\n if (rule[0][0] == EXCEPTION_MARKER) {\n // Exception rules hold the effective TLD plus one.\n domainLabels.size - rule.size\n } else {\n // Otherwise the rule is for a public suffix, so we must take one more label.\n domainLabels.size - (rule.size + 1)\n }\n\n return splitDomain(domain).asSequence().drop(firstLabelOffset).joinToString(\".\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt","line":70,"symbol":"splitDomain","kind":"function","lang":"kotlin","code":"private fun splitDomain(domain: String): List {\n val domainLabels = domain.split('.')\n\n if (domainLabels.last() == \"\") {\n // allow for domain name trailing dot\n return domainLabels.dropLast(1)\n }\n\n return domainLabels\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt","line":81,"symbol":"findMatchingRule","kind":"function","lang":"kotlin","code":"private fun findMatchingRule(domainLabels: List): List {\n publicSuffixList.ensureLoaded()\n\n // Break apart the domain into UTF-8 labels, i.e. foo.bar.com turns into [foo, bar, com].\n val domainLabelsUtf8Bytes = Array(domainLabels.size) { i -> domainLabels[i].encodeUtf8() }\n\n // Start by looking for exact matches. We start at the leftmost label. For example, foo.bar.com\n // will look like: [foo, bar, com], [bar, com], [com]. The longest matching rule wins.\n var exactMatch: String? = null\n for (i in domainLabelsUtf8Bytes.indices) {\n val rule = publicSuffixList.bytes.binarySearch(domainLabelsUtf8Bytes, i)\n if (rule != null) {\n exactMatch = rule\n break\n }\n }\n\n // In theory, wildcard rules are not restricted to having the wildcard in the leftmost position.\n // In practice, wildcards are always in the leftmost position. For now, this implementation\n // cheats and does not attempt every possible permutation. Instead, it only considers wildcards\n // in the leftmost position. We assert this fact when we generate the public suffix file. If\n // this assertion ever fails we'll need to refactor this implementati"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt","line":158,"symbol":"get","kind":"function","lang":"kotlin","code":"fun get(): PublicSuffixDatabase = instance"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt","line":160,"symbol":"binarySearch","kind":"function","lang":"kotlin","code":"private fun ByteString.binarySearch(\n labels: Array,\n labelIndex: Int,\n ): String? {\n var low = 0\n var high = size\n var match: String? = null\n while (low < high) {\n var mid = (low + high) / 2\n // Search for a '\\n' that marks the start of a value. Don't go back past the start of the\n // array.\n while (mid > -1 && this[mid] != '\\n'.code.toByte()) {\n mid--\n }\n mid++\n\n // Now look for the ending '\\n'.\n var end = 1\n while (this[mid + end] != '\\n'.code.toByte()) {\n end++\n }\n val publicSuffixLength = mid + end - mid\n\n // Compare the bytes. Note that the file stores UTF-8 encoded bytes, so we must compare the\n // unsigned bytes.\n var compareResult: Int\n var currentLabelIndex = labelIndex\n var currentLabelByteIndex = 0\n var publicSuffixByteIndex = 0\n\n var expectDot = false\n while (true) {\n val byte0: Int\n if (expectDot) {\n byte0 = '.'.code\n expectDot = false\n } else {\n byte0 = labels[currentLabelIndex][currentLabelByteIndex] and 0xff\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt","line":248,"symbol":"resetForTests","kind":"function","lang":"kotlin","code":"internal fun resetForTests() {\n instance = PublicSuffixDatabase(PublicSuffixList.Default)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixList.kt","line":23,"symbol":"PublicSuffixList","kind":"interface","lang":"kotlin","doc":"Basic I/O for `PublicSuffixDatabase.list`","code":"internal interface PublicSuffixList {\n fun ensureLoaded()\n\n val bytes: ByteString\n val exceptionBytes: ByteString\n\n companion object\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/PublicSuffixList.kt","line":24,"symbol":"ensureLoaded","kind":"function","lang":"kotlin","code":"fun ensureLoaded()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/ResourcePublicSuffixList.kt","line":23,"symbol":"ResourcePublicSuffixList","kind":"class","lang":"kotlin","code":"internal class ResourcePublicSuffixList(\n override val path: Path = PUBLIC_SUFFIX_RESOURCE,\n val fileSystem: FileSystem = FileSystem.Companion.RESOURCES,\n) : BasePublicSuffixList() {\n override fun listSource(): Source = fileSystem.source(path)\n\n companion object {\n @JvmField\n val PUBLIC_SUFFIX_RESOURCE =\n \"okhttp3/internal/publicsuffix/${PublicSuffixDatabase::class.java.simpleName}.list\".toPath()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/publicsuffix/ResourcePublicSuffixList.kt","line":27,"symbol":"listSource","kind":"function","lang":"kotlin","code":"override fun listSource(): Source = fileSystem.source(path)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicCertificateChainCleaner.kt","line":36,"symbol":"BasicCertificateChainCleaner","kind":"class","lang":"kotlin","doc":"This class includes code from [Conscrypt's][Conscrypt] [TrustManagerImpl] and [TrustedCertificateIndex]. [Conscrypt]: https://conscrypt.org/","code":"class BasicCertificateChainCleaner(\n private val trustRootIndex: TrustRootIndex,\n) : CertificateChainCleaner() {\n /**\n * Returns a cleaned chain for [chain].\n *\n * This method throws if the complete chain to a trusted CA certificate cannot be constructed.\n * This is unexpected unless the trust root index in this class has a different trust manager than\n * what was used to establish [chain].\n */\n @Throws(SSLPeerUnverifiedException::class)\n override fun clean(\n chain: List,\n hostname: String,\n ): List {\n val queue: Deque = ArrayDeque(chain)\n val result = mutableListOf()\n result.add(queue.removeFirst())\n var foundTrustedCertificate = false\n\n followIssuerChain@\n for (c in 0 until MAX_SIGNERS) {\n val toVerify = result[result.size - 1] as X509Certificate\n\n // If this cert has been signed by a trusted cert, use that. Add the trusted certificate to\n // the end of the chain unless it's already present. (That would happen if the first\n // certificate in the chain is itself a self-signed and trusted CA certificate.)\n val trustedCert = trustRootIndex.findByIssuerAndSignature(to"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicCertificateChainCleaner.kt","line":46,"symbol":"clean","kind":"function","lang":"kotlin","doc":"Returns a cleaned chain for [chain]. This method throws if the complete chain to a trusted CA certificate cannot be constructed. This is unexpected unless the trust root index in this class has a different trust manager than what was used to establish [chain].","code":"@Throws(SSLPeerUnverifiedException::class)\n override fun clean(\n chain: List,\n hostname: String,\n ): List {\n val queue: Deque = ArrayDeque(chain)\n val result = mutableListOf()\n result.add(queue.removeFirst())\n var foundTrustedCertificate = false\n\n followIssuerChain@\n for (c in 0 until MAX_SIGNERS) {\n val toVerify = result[result.size - 1] as X509Certificate\n\n // If this cert has been signed by a trusted cert, use that. Add the trusted certificate to\n // the end of the chain unless it's already present. (That would happen if the first\n // certificate in the chain is itself a self-signed and trusted CA certificate.)\n val trustedCert = trustRootIndex.findByIssuerAndSignature(toVerify)\n if (trustedCert != null) {\n if (result.size > 1 || toVerify != trustedCert) {\n result.add(trustedCert)\n }\n if (verifySignature(trustedCert, trustedCert, result.size - 2)) {\n return result // The self-signed cert is a root CA. We're done.\n }\n foundTrustedCertificate = true\n continue\n }\n\n // Search for the certificate in the chain"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicCertificateChainCleaner.kt","line":107,"symbol":"verifySignature","kind":"function","lang":"kotlin","doc":"Returns true if [toVerify] was signed by [signingCert]'s public key. @param minIntermediates the minimum number of intermediate certificates in [signingCert]. This is -1 if signing cert is a lone self-signed certificate.","code":"private fun verifySignature(\n toVerify: X509Certificate,\n signingCert: X509Certificate,\n minIntermediates: Int,\n ): Boolean {\n if (toVerify.issuerDN != signingCert.subjectDN) {\n return false\n }\n if (signingCert.basicConstraints < minIntermediates) {\n return false // The signer can't have this many intermediates beneath it.\n }\n return try {\n toVerify.verify(signingCert.publicKey)\n true\n } catch (verifyFailed: GeneralSecurityException) {\n false\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicCertificateChainCleaner.kt","line":126,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int = trustRootIndex.hashCode()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicCertificateChainCleaner.kt","line":128,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n if (other === this) {\n true\n } else {\n other is BasicCertificateChainCleaner && other.trustRootIndex == trustRootIndex\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicTrustRootIndex.kt","line":22,"symbol":"BasicTrustRootIndex","kind":"class","lang":"kotlin","doc":"A simple index that of trusted root certificates that have been loaded into memory.","code":"class BasicTrustRootIndex(\n vararg caCerts: X509Certificate,\n) : TrustRootIndex {\n private val subjectToCaCerts: Map>\n\n init {\n val map = mutableMapOf>()\n for (caCert in caCerts) {\n map.getOrPut(caCert.subjectX500Principal) { mutableSetOf() }.add(caCert)\n }\n this.subjectToCaCerts = map\n }\n\n override fun findByIssuerAndSignature(cert: X509Certificate): X509Certificate? {\n val issuer = cert.issuerX500Principal\n val subjectCaCerts = subjectToCaCerts[issuer] ?: return null\n\n return subjectCaCerts.firstOrNull {\n try {\n cert.verify(it.publicKey)\n return@firstOrNull true\n } catch (_: Exception) {\n return@firstOrNull false\n }\n }\n }\n\n override fun equals(other: Any?): Boolean =\n other === this ||\n (other is BasicTrustRootIndex && other.subjectToCaCerts == subjectToCaCerts)\n\n override fun hashCode(): Int = subjectToCaCerts.hashCode()\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicTrustRootIndex.kt","line":35,"symbol":"findByIssuerAndSignature","kind":"function","lang":"kotlin","code":"override fun findByIssuerAndSignature(cert: X509Certificate): X509Certificate? {\n val issuer = cert.issuerX500Principal\n val subjectCaCerts = subjectToCaCerts[issuer] ?: return null\n\n return subjectCaCerts.firstOrNull {\n try {\n cert.verify(it.publicKey)\n return@firstOrNull true\n } catch (_: Exception) {\n return@firstOrNull false\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicTrustRootIndex.kt","line":49,"symbol":"equals","kind":"function","lang":"kotlin","code":"override fun equals(other: Any?): Boolean =\n other === this ||\n (other is BasicTrustRootIndex && other.subjectToCaCerts == subjectToCaCerts)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/BasicTrustRootIndex.kt","line":53,"symbol":"hashCode","kind":"function","lang":"kotlin","code":"override fun hashCode(): Int = subjectToCaCerts.hashCode()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/CertificateChainCleaner.kt","line":35,"symbol":"CertificateChainCleaner","kind":"class","lang":"kotlin","doc":"certificate. Use of the chain cleaner is necessary to omit unexpected certificates that aren't relevant to the TLS handshake and to extract the trusted CA certificate for the benefit of certificate pinning.","code":"abstract class CertificateChainCleaner {\n @Throws(SSLPeerUnverifiedException::class)\n abstract fun clean(\n chain: List,\n hostname: String,\n ): List\n\n companion object {\n fun get(trustManager: X509TrustManager): CertificateChainCleaner = Platform.get().buildCertificateChainCleaner(trustManager)\n\n fun get(vararg caCerts: X509Certificate): CertificateChainCleaner = BasicCertificateChainCleaner(BasicTrustRootIndex(*caCerts))\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/CertificateChainCleaner.kt","line":36,"symbol":"clean","kind":"function","lang":"kotlin","code":"@Throws(SSLPeerUnverifiedException::class)\n abstract fun clean(\n chain: List,\n hostname: String,\n ): List"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/CertificateChainCleaner.kt","line":43,"symbol":"get","kind":"function","lang":"kotlin","code":"fun get(trustManager: X509TrustManager): CertificateChainCleaner = Platform.get().buildCertificateChainCleaner(trustManager)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/CertificateChainCleaner.kt","line":45,"symbol":"get","kind":"function","lang":"kotlin","code":"fun get(vararg caCerts: X509Certificate): CertificateChainCleaner = BasicCertificateChainCleaner(BasicTrustRootIndex(*caCerts))"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":34,"symbol":"OkHostnameVerifier","kind":"object","lang":"kotlin","doc":"A HostnameVerifier consistent with [RFC 2818][rfc_2818]. [rfc_2818]: http://www.ietf.org/rfc/rfc2818.txt","code":"@Suppress(\"NAME_SHADOWING\")\nobject OkHostnameVerifier : HostnameVerifier {\n private const val ALT_DNS_NAME = 2\n private const val ALT_IPA_NAME = 7\n\n override fun verify(\n host: String,\n session: SSLSession,\n ): Boolean =\n if (!host.isAscii()) {\n false\n } else {\n try {\n verify(host, session.peerCertificates[0] as X509Certificate)\n } catch (_: SSLException) {\n false\n }\n }\n\n fun verify(\n host: String,\n certificate: X509Certificate,\n ): Boolean =\n when {\n host.canParseAsIpAddress() -> verifyIpAddress(host, certificate)\n else -> verifyHostname(host, certificate)\n }\n\n /** Returns true if [certificate] matches [ipAddress]. */\n private fun verifyIpAddress(\n ipAddress: String,\n certificate: X509Certificate,\n ): Boolean {\n val canonicalIpAddress = ipAddress.toCanonicalHost() ?: return false\n\n return getSubjectAltNames(certificate, ALT_IPA_NAME).any {\n canonicalIpAddress == it.toCanonicalHost()\n }\n }\n\n /** Returns true if [certificate] matches [hostname]. */\n private fun verifyHostname(\n hostname: String,\n certificate: X509Certificate,\n ): Boolean {\n val hostname = hostname.asciiTo"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":39,"symbol":"verify","kind":"function","lang":"kotlin","code":"override fun verify(\n host: String,\n session: SSLSession,\n ): Boolean =\n if (!host.isAscii()) {\n false\n } else {\n try {\n verify(host, session.peerCertificates[0] as X509Certificate)\n } catch (_: SSLException) {\n false\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":53,"symbol":"verify","kind":"function","lang":"kotlin","code":"fun verify(\n host: String,\n certificate: X509Certificate,\n ): Boolean =\n when {\n host.canParseAsIpAddress() -> verifyIpAddress(host, certificate)\n else -> verifyHostname(host, certificate)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":63,"symbol":"verifyIpAddress","kind":"function","lang":"kotlin","doc":"Returns true if [certificate] matches [ipAddress].","code":"private fun verifyIpAddress(\n ipAddress: String,\n certificate: X509Certificate,\n ): Boolean {\n val canonicalIpAddress = ipAddress.toCanonicalHost() ?: return false\n\n return getSubjectAltNames(certificate, ALT_IPA_NAME).any {\n canonicalIpAddress == it.toCanonicalHost()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":75,"symbol":"verifyHostname","kind":"function","lang":"kotlin","doc":"Returns true if [certificate] matches [hostname].","code":"private fun verifyHostname(\n hostname: String,\n certificate: X509Certificate,\n ): Boolean {\n val hostname = hostname.asciiToLowercase()\n return getSubjectAltNames(certificate, ALT_DNS_NAME).any {\n verifyHostname(hostname, it)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":90,"symbol":"asciiToLowercase","kind":"function","lang":"kotlin","doc":"This is like [toLowerCase] except that it does nothing if this contains any non-ASCII characters. We want to avoid lower casing special chars like U+212A (Kelvin symbol) because they can return ASCII characters that match real hostnames.","code":"private fun String.asciiToLowercase(): String =\n when {\n isAscii() -> lowercase(Locale.US)\n\n // This is an ASCII string.\n else -> this\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":99,"symbol":"isAscii","kind":"function","lang":"kotlin","doc":"Returns true if the [String] is ASCII encoded (0-127).","code":"private fun String.isAscii() = length == utf8Size().toInt()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":108,"symbol":"verifyHostname","kind":"function","lang":"kotlin","doc":"Returns true if [hostname] matches the domain name [pattern]. @param hostname lower-case host name. @param pattern domain name pattern from certificate. May be a wildcard pattern such as `*.android.com`.","code":"private fun verifyHostname(\n hostname: String?,\n pattern: String?,\n ): Boolean {\n var hostname = hostname\n var pattern = pattern\n if (hostname.isNullOrEmpty() ||\n hostname.startsWith(\".\") ||\n hostname.endsWith(\"..\")\n ) {\n // Invalid domain name.\n return false\n }\n if (pattern.isNullOrEmpty() ||\n pattern.startsWith(\".\") ||\n pattern.endsWith(\"..\")\n ) {\n // Invalid pattern.\n return false\n }\n\n // Normalize hostname and pattern by turning them into absolute domain names if they are not\n // yet absolute. This is needed because server certificates do not normally contain absolute\n // names or patterns, but they should be treated as absolute. At the same time, any hostname\n // presented to this method should also be treated as absolute for the purposes of matching\n // to the server certificate.\n // www.android.com matches www.android.com\n // www.android.com matches www.android.com.\n // www.android.com. matches www.android.com.\n // www.android.com. matches www.android.com\n if (!hostname.endsWith(\".\")) {\n hostname += \".\"\n }\n if (!pattern.endsWith(\".\")) {\n pattern += \""} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":201,"symbol":"allSubjectAltNames","kind":"function","lang":"kotlin","code":"fun allSubjectAltNames(certificate: X509Certificate): List {\n val altIpaNames = getSubjectAltNames(certificate, ALT_IPA_NAME)\n val altDnsNames = getSubjectAltNames(certificate, ALT_DNS_NAME)\n return altIpaNames + altDnsNames\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/OkHostnameVerifier.kt","line":207,"symbol":"getSubjectAltNames","kind":"function","lang":"kotlin","code":"private fun getSubjectAltNames(\n certificate: X509Certificate,\n type: Int,\n ): List {\n try {\n val subjectAltNames = certificate.subjectAlternativeNames ?: return emptyList()\n val result = mutableListOf()\n for (subjectAltName in subjectAltNames) {\n if (subjectAltName == null || subjectAltName.size < 2) continue\n if (subjectAltName[0] != type) continue\n val altName = subjectAltName[1] ?: continue\n result.add(altName as String)\n }\n return result\n } catch (_: CertificateParsingException) {\n return emptyList()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/TrustRootIndex.kt","line":20,"symbol":"TrustRootIndex","kind":"interface","lang":"kotlin","code":"fun interface TrustRootIndex {\n /** Returns the trusted CA certificate that signed [cert]. */\n fun findByIssuerAndSignature(cert: X509Certificate): X509Certificate?\n}"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/tls/TrustRootIndex.kt","line":22,"symbol":"findByIssuerAndSignature","kind":"function","lang":"kotlin","doc":"Returns the trusted CA certificate that signed [cert].","code":"fun findByIssuerAndSignature(cert: X509Certificate): X509Certificate?"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/MessageDeflater.kt","line":29,"symbol":"MessageDeflater","kind":"class","lang":"kotlin","code":"class MessageDeflater(\n private val noContextTakeover: Boolean,\n) : Closeable {\n private val deflatedBytes = Buffer()\n\n private val deflater =\n Deflater(\n Deflater.DEFAULT_COMPRESSION,\n // nowrap (omits zlib header):\n true,\n )\n\n private val deflaterSink = DeflaterSink(deflatedBytes, deflater)\n\n /** Deflates [buffer] in place as described in RFC 7692 section 7.2.1. */\n @Throws(IOException::class)\n fun deflate(buffer: Buffer) {\n require(deflatedBytes.size == 0L)\n\n if (noContextTakeover) {\n deflater.reset()\n }\n\n deflaterSink.write(buffer, buffer.size)\n deflaterSink.flush()\n\n if (deflatedBytes.endsWith(EMPTY_DEFLATE_BLOCK)) {\n val newSize = deflatedBytes.size - LAST_OCTETS_COUNT_TO_REMOVE_AFTER_DEFLATION\n deflatedBytes.readAndWriteUnsafe().use { cursor ->\n cursor.resizeBuffer(newSize)\n }\n } else {\n // Same as adding EMPTY_DEFLATE_BLOCK and then removing 4 bytes.\n deflatedBytes.writeByte(0x00)\n }\n\n buffer.write(deflatedBytes, deflatedBytes.size)\n }\n\n @Throws(IOException::class)\n override fun close() = deflaterSink.close()\n\n private fun Buffer.endsWith(suffix: ByteString): Boolean = rangeEqual"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/MessageDeflater.kt","line":44,"symbol":"deflate","kind":"function","lang":"kotlin","doc":"Deflates [buffer] in place as described in RFC 7692 section 7.2.1.","code":"@Throws(IOException::class)\n fun deflate(buffer: Buffer) {\n require(deflatedBytes.size == 0L)\n\n if (noContextTakeover) {\n deflater.reset()\n }\n\n deflaterSink.write(buffer, buffer.size)\n deflaterSink.flush()\n\n if (deflatedBytes.endsWith(EMPTY_DEFLATE_BLOCK)) {\n val newSize = deflatedBytes.size - LAST_OCTETS_COUNT_TO_REMOVE_AFTER_DEFLATION\n deflatedBytes.readAndWriteUnsafe().use { cursor ->\n cursor.resizeBuffer(newSize)\n }\n } else {\n // Same as adding EMPTY_DEFLATE_BLOCK and then removing 4 bytes.\n deflatedBytes.writeByte(0x00)\n }\n\n buffer.write(deflatedBytes, deflatedBytes.size)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/MessageDeflater.kt","line":68,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() = deflaterSink.close()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/MessageDeflater.kt","line":71,"symbol":"endsWith","kind":"function","lang":"kotlin","code":"private fun Buffer.endsWith(suffix: ByteString): Boolean = rangeEquals(size - suffix.size, suffix)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/MessageInflater.kt","line":26,"symbol":"MessageInflater","kind":"class","lang":"kotlin","code":"class MessageInflater(\n private val noContextTakeover: Boolean,\n) : Closeable {\n private val deflatedBytes = Buffer()\n\n // Lazily-created.\n private var inflater: Inflater? = null\n private var inflaterSource: InflaterSource? = null\n\n /** Inflates [buffer] in place as described in RFC 7692 section 7.2.2. */\n @Throws(IOException::class)\n fun inflate(buffer: Buffer) {\n require(deflatedBytes.size == 0L)\n\n val inflater =\n this.inflater\n ?: Inflater(true).also { this.inflater = it }\n val inflaterSource =\n this.inflaterSource\n ?: InflaterSource(deflatedBytes, inflater).also { this.inflaterSource = it }\n\n if (noContextTakeover) {\n inflater.reset()\n }\n\n deflatedBytes.writeAll(buffer)\n deflatedBytes.writeInt(OCTETS_TO_ADD_BEFORE_INFLATION)\n\n val totalBytesToRead = inflater.bytesRead + deflatedBytes.size\n\n // We cannot read all, as the source does not close.\n // Instead, we ensure that all bytes from source have been processed by inflater.\n do {\n inflaterSource.readOrInflate(buffer, Long.MAX_VALUE)\n } while (inflater.bytesRead < totalBytesToRead && !inflater.finished())\n\n // The inflater data was self-terminated a"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/MessageInflater.kt","line":36,"symbol":"inflate","kind":"function","lang":"kotlin","doc":"Inflates [buffer] in place as described in RFC 7692 section 7.2.2.","code":"@Throws(IOException::class)\n fun inflate(buffer: Buffer) {\n require(deflatedBytes.size == 0L)\n\n val inflater =\n this.inflater\n ?: Inflater(true).also { this.inflater = it }\n val inflaterSource =\n this.inflaterSource\n ?: InflaterSource(deflatedBytes, inflater).also { this.inflaterSource = it }\n\n if (noContextTakeover) {\n inflater.reset()\n }\n\n deflatedBytes.writeAll(buffer)\n deflatedBytes.writeInt(OCTETS_TO_ADD_BEFORE_INFLATION)\n\n val totalBytesToRead = inflater.bytesRead + deflatedBytes.size\n\n // We cannot read all, as the source does not close.\n // Instead, we ensure that all bytes from source have been processed by inflater.\n do {\n inflaterSource.readOrInflate(buffer, Long.MAX_VALUE)\n } while (inflater.bytesRead < totalBytesToRead && !inflater.finished())\n\n // The inflater data was self-terminated and there's unexpected trailing data. Tear it all down\n // so we don't leak that data into the input of the next message.\n if (inflater.bytesRead < totalBytesToRead) {\n deflatedBytes.clear()\n inflaterSource.close()\n this.inflaterSource = null\n this.inflater = null\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/MessageInflater.kt","line":72,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n inflaterSource?.close()\n inflaterSource = null\n inflater = null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":55,"symbol":"RealWebSocket","kind":"class","lang":"kotlin","code":"class RealWebSocket(\n taskRunner: TaskRunner,\n /** The application's original request unadulterated by web socket headers. */\n private val originalRequest: Request,\n internal val listener: WebSocketListener,\n private val random: Random,\n private val pingIntervalMillis: Long,\n /**\n * For clients this is initially null, and will be assigned to the agreed-upon extensions. For\n * servers, it should be the agreed-upon extensions immediately.\n */\n private var extensions: WebSocketExtensions?,\n /** If compression is negotiated, outbound messages of this size and larger will be compressed. */\n private var minimumDeflateSize: Long,\n private val webSocketCloseTimeout: Long,\n) : WebSocket,\n WebSocketReader.FrameCallback,\n Lockable {\n private val key: String\n\n /** Non-null for client web sockets. These can be canceled. */\n internal var call: Call? = null\n\n /** This task processes the outgoing queues. Call [runWriter] to after enqueueing. */\n private var writerTask: Task? = null\n\n /** Null until this web socket is connected. Only accessed by the reader thread. */\n private var reader: WebSocketReader? = null\n\n // All mutable web socket state is guarded by this.\n\n /** "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":139,"symbol":"request","kind":"function","lang":"kotlin","code":"override fun request(): Request = originalRequest"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":141,"symbol":"queueSize","kind":"function","lang":"kotlin","code":"@Synchronized override fun queueSize(): Long = queueSize"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":143,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n call!!.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":147,"symbol":"connect","kind":"function","lang":"kotlin","code":"fun connect(client: OkHttpClient) {\n if (originalRequest.header(\"Sec-WebSocket-Extensions\") != null) {\n failWebSocket(ProtocolException(\"Request header not permitted: 'Sec-WebSocket-Extensions'\"))\n return\n }\n\n val webSocketClient =\n client\n .newBuilder()\n .eventListener(EventListener.NONE)\n .protocols(ONLY_HTTP1)\n .build()\n val request =\n originalRequest\n .newBuilder()\n .header(\"Upgrade\", \"websocket\")\n .header(\"Connection\", \"Upgrade\")\n .header(\"Sec-WebSocket-Key\", key)\n .header(\"Sec-WebSocket-Version\", \"13\")\n .header(\"Sec-WebSocket-Extensions\", \"permessage-deflate\")\n .build()\n call = RealCall(webSocketClient, request, forWebSocket = true)\n call!!.enqueue(\n object : Callback {\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val socket =\n try {\n checkUpgradeSuccess(response)\n } catch (e: IOException) {\n failWebSocket(e, response)\n response.closeQuietly()\n response.socket?.sink?.closeQuietly()\n response.socket?.source?.clos"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":171,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val socket =\n try {\n checkUpgradeSuccess(response)\n } catch (e: IOException) {\n failWebSocket(e, response)\n response.closeQuietly()\n response.socket?.sink?.closeQuietly()\n response.socket?.source?.closeQuietly()\n return\n }\n\n // Apply the extensions. If they're unacceptable initiate a graceful shut down.\n // TODO(jwilson): Listeners should get onFailure() instead of onClosing() + onClosed(1010).\n val extensions = WebSocketExtensions.parse(response.headers)\n this@RealWebSocket.extensions = extensions\n if (!extensions.isValid()) {\n synchronized(this@RealWebSocket) {\n messageAndCloseQueue.clear() // Don't transmit any messages.\n close(1010, \"unexpected Sec-WebSocket-Extensions in response header\")\n }\n }\n\n // Process all web socket messages.\n val name = \"$okHttpName WebSocket ${request.url.redact()}\"\n initReaderAndWriter(\n name = name,\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":207,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n failWebSocket(e)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":217,"symbol":"isValid","kind":"function","lang":"kotlin","code":"private fun WebSocketExtensions.isValid(): Boolean {\n // If the server returned parameters we don't understand, fail the web socket.\n if (unknownValues) return false\n\n // If the server returned a value for client_max_window_bits, fail the web socket.\n if (clientMaxWindowBits != null) return false\n\n // If the server returned an illegal server_max_window_bits, fail the web socket.\n if (serverMaxWindowBits != null && serverMaxWindowBits !in 8..15) return false\n\n // Success.\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":231,"symbol":"checkUpgradeSuccess","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n internal fun checkUpgradeSuccess(response: Response): Socket {\n if (response.code != 101) {\n throw ProtocolException(\n \"Expected HTTP 101 response but was '${response.code} ${response.message}'\",\n )\n }\n\n val headerConnection = response.header(\"Connection\")\n if (!\"Upgrade\".equals(headerConnection, ignoreCase = true)) {\n throw ProtocolException(\n \"Expected 'Connection' header value 'Upgrade' but was '$headerConnection'\",\n )\n }\n\n val headerUpgrade = response.header(\"Upgrade\")\n if (!\"websocket\".equals(headerUpgrade, ignoreCase = true)) {\n throw ProtocolException(\n \"Expected 'Upgrade' header value 'websocket' but was '$headerUpgrade'\",\n )\n }\n\n val headerAccept = response.header(\"Sec-WebSocket-Accept\")\n val acceptExpected = (key + WebSocketProtocol.ACCEPT_MAGIC).encodeUtf8().sha1().base64()\n if (acceptExpected != headerAccept) {\n throw ProtocolException(\n \"Expected 'Sec-WebSocket-Accept' header value '$acceptExpected' but was '$headerAccept'\",\n )\n }\n\n return response.socket\n ?: throw ProtocolException(\"Web Socket socket missing: bad interceptor?\")\n"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":269,"symbol":"initReaderAndWriter","kind":"function","lang":"kotlin","doc":"This accepts a [BufferedSource] instead of using [Socket.source], just in case we've already received data from the peer. This accepts a [BufferedSink] for symmetry with the source.","code":"fun initReaderAndWriter(\n name: String,\n socket: BufferedSocket,\n client: Boolean,\n ) {\n val extensions = this.extensions!!\n synchronized(this) {\n this.name = name\n this.socket = socket\n this.writer =\n WebSocketWriter(\n isClient = client,\n sink = socket.sink,\n random = random,\n perMessageDeflate = extensions.perMessageDeflate,\n noContextTakeover = extensions.noContextTakeover(client),\n minimumDeflateSize = minimumDeflateSize,\n )\n this.writerTask = WriterTask()\n if (pingIntervalMillis != 0L) {\n val pingIntervalNanos = MILLISECONDS.toNanos(pingIntervalMillis)\n taskQueue.schedule(\"$name ping\", pingIntervalNanos) {\n writePingFrame()\n return@schedule pingIntervalNanos\n }\n }\n if (messageAndCloseQueue.isNotEmpty()) {\n runWriter() // Send messages that were enqueued before we were connected.\n }\n }\n\n reader =\n WebSocketReader(\n isClient = client,\n source = socket.source,\n frameCallback = this,\n perMessageDeflate = extensions.perMessageDeflate,\n noContextTakeover = extensions.noC"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":311,"symbol":"loopReader","kind":"function","lang":"kotlin","doc":"Receive frames until there are no more. Invoked only by the reader thread.","code":"@Throws(IOException::class)\n fun loopReader(response: Response) {\n try {\n listener.onOpen(this@RealWebSocket, response)\n while (receivedCloseCode == -1) {\n // This method call results in one or more onRead* methods being called on this thread.\n reader!!.processNextFrame()\n }\n } catch (e: Exception) {\n failWebSocket(e = e)\n } finally {\n finishReader()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":330,"symbol":"processNextFrame","kind":"function","lang":"kotlin","doc":"For testing: receive a single frame and return true if there are more frames to read. Invoked only by the reader thread.","code":"@Throws(IOException::class)\n fun processNextFrame(): Boolean =\n try {\n reader!!.processNextFrame()\n receivedCloseCode == -1\n } catch (e: Exception) {\n failWebSocket(e = e)\n false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":344,"symbol":"finishReader","kind":"function","lang":"kotlin","doc":"Clean up and publish necessary close events when the reader is done. Invoked only by the reader thread.","code":"fun finishReader() {\n val code: Int\n val reason: String?\n val sendOnClosed: Boolean\n var readerToClose: WebSocketReader?\n synchronized(this) {\n code = receivedCloseCode\n reason = receivedCloseReason\n\n readerToClose = reader\n reader = null\n\n if (enqueuedClose && messageAndCloseQueue.isEmpty()) {\n // Close the writer on the writer's thread.\n val writerToClose = this.writer\n if (writerToClose != null) {\n this.writer = null\n taskQueue.execute(\"$name writer close\", cancelable = false) {\n writerToClose.closeQuietly()\n }\n }\n\n this.taskQueue.shutdown()\n }\n\n sendOnClosed = !failed && writer == null && receivedCloseCode != -1\n }\n\n if (sendOnClosed) {\n listener.onClosed(this, code, reason!!)\n }\n\n readerToClose?.closeQuietly()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":380,"symbol":"tearDown","kind":"function","lang":"kotlin","doc":"For testing: force this web socket to release its threads.","code":"@Throws(InterruptedException::class)\n fun tearDown() {\n taskQueue.shutdown()\n taskQueue.idleLatch().await(10, TimeUnit.SECONDS)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":386,"symbol":"sentPingCount","kind":"function","lang":"kotlin","code":"@Synchronized fun sentPingCount(): Int = sentPingCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":388,"symbol":"receivedPingCount","kind":"function","lang":"kotlin","code":"@Synchronized fun receivedPingCount(): Int = receivedPingCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":390,"symbol":"receivedPongCount","kind":"function","lang":"kotlin","code":"@Synchronized fun receivedPongCount(): Int = receivedPongCount"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":392,"symbol":"onReadMessage","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onReadMessage(text: String) {\n listener.onMessage(this, text)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":397,"symbol":"onReadMessage","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onReadMessage(bytes: ByteString) {\n listener.onMessage(this, bytes)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":402,"symbol":"onReadPing","kind":"function","lang":"kotlin","code":"@Synchronized override fun onReadPing(payload: ByteString) {\n // Don't respond to pings after we've failed or sent the close frame.\n if (failed || enqueuedClose && messageAndCloseQueue.isEmpty()) return\n\n pongQueue.add(payload)\n runWriter()\n receivedPingCount++\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":411,"symbol":"onReadPong","kind":"function","lang":"kotlin","code":"@Synchronized override fun onReadPong(payload: ByteString) {\n // This API doesn't expose pings.\n receivedPongCount++\n awaitingPong = false\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":417,"symbol":"onReadClose","kind":"function","lang":"kotlin","code":"override fun onReadClose(\n code: Int,\n reason: String,\n ) {\n require(code != -1)\n\n synchronized(this) {\n check(receivedCloseCode == -1) { \"already closed\" }\n receivedCloseCode = code\n receivedCloseReason = reason\n }\n\n listener.onClosing(this, code, reason)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":434,"symbol":"send","kind":"function","lang":"kotlin","code":"override fun send(text: String): Boolean = send(text.encodeUtf8(), OPCODE_TEXT)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":436,"symbol":"send","kind":"function","lang":"kotlin","code":"override fun send(bytes: ByteString): Boolean = send(bytes, OPCODE_BINARY)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":438,"symbol":"send","kind":"function","lang":"kotlin","code":"@Synchronized private fun send(\n data: ByteString,\n formatOpcode: Int,\n ): Boolean {\n // Don't send new frames after we've failed or enqueued a close frame.\n if (failed || enqueuedClose) return false\n\n // If this frame overflows the buffer, reject it and close the web socket.\n if (queueSize + data.size > MAX_QUEUE_SIZE) {\n close(CLOSE_CLIENT_GOING_AWAY, null)\n return false\n }\n\n // Enqueue the message frame.\n queueSize += data.size.toLong()\n messageAndCloseQueue.add(Message(formatOpcode, data))\n runWriter()\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":458,"symbol":"pong","kind":"function","lang":"kotlin","code":"@Synchronized fun pong(payload: ByteString): Boolean {\n // Don't send pongs after we've failed or sent the close frame.\n if (failed || enqueuedClose && messageAndCloseQueue.isEmpty()) return false\n\n pongQueue.add(payload)\n runWriter()\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":467,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close(\n code: Int,\n reason: String?,\n ): Boolean = close(code, reason, webSocketCloseTimeout)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":472,"symbol":"close","kind":"function","lang":"kotlin","code":"@Synchronized fun close(\n code: Int,\n reason: String?,\n cancelAfterCloseMillis: Long,\n ): Boolean {\n validateCloseCode(code)\n\n var reasonBytes: ByteString? = null\n if (reason != null) {\n reasonBytes = reason.encodeUtf8()\n require(reasonBytes.size <= CLOSE_MESSAGE_MAX) {\n \"reason.size() > $CLOSE_MESSAGE_MAX: $reason\"\n }\n }\n\n if (failed || enqueuedClose) return false\n\n // Immediately prevent further frames from being enqueued.\n enqueuedClose = true\n\n // Enqueue the close frame.\n messageAndCloseQueue.add(Close(code, reasonBytes, cancelAfterCloseMillis))\n runWriter()\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":498,"symbol":"runWriter","kind":"function","lang":"kotlin","code":"private fun runWriter() {\n assertLockHeld()\n\n val writerTask = writerTask\n if (writerTask != null) {\n taskQueue.schedule(writerTask)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":520,"symbol":"writeOneFrame","kind":"function","lang":"kotlin","doc":"connected - this does nothing and returns false. Otherwise, this returns true and the caller should immediately invoke this method again until it returns false. This method may only be invoked by the writer thread. There may be only thread invoking this method at a time.","code":"@Throws(IOException::class)\n internal fun writeOneFrame(): Boolean {\n val writer: WebSocketWriter?\n val pong: ByteString?\n var messageOrClose: Any? = null\n var receivedCloseCode = -1\n var receivedCloseReason: String? = null\n var sendOnClosed = false\n var writerToClose: WebSocketWriter? = null\n\n synchronized(this@RealWebSocket) {\n if (failed) {\n return false // Failed web socket.\n }\n\n writer = this.writer\n pong = pongQueue.poll()\n if (pong == null) {\n messageOrClose = messageAndCloseQueue.poll()\n if (messageOrClose is Close) {\n receivedCloseCode = this.receivedCloseCode\n receivedCloseReason = this.receivedCloseReason\n if (receivedCloseCode != -1) {\n writerToClose = this.writer\n this.writer = null\n sendOnClosed = writerToClose != null && reader == null\n this.taskQueue.shutdown()\n } else {\n // When we request a graceful close also schedule a cancel of the web socket.\n val cancelAfterCloseMillis = messageOrClose.cancelAfterCloseMillis\n taskQueue.execute(\"$name cancel\", MILLISECONDS.toNanos(cancelAfterClos"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":587,"symbol":"writePingFrame","kind":"function","lang":"kotlin","code":"internal fun writePingFrame() {\n val writer: WebSocketWriter\n val failedPing: Int\n synchronized(this) {\n if (failed) return\n writer = this.writer ?: return\n failedPing = if (awaitingPong) sentPingCount else -1\n sentPingCount++\n awaitingPong = true\n }\n\n if (failedPing != -1) {\n failWebSocket(\n e =\n SocketTimeoutException(\n \"sent ping but didn't receive pong within \" +\n \"${pingIntervalMillis}ms (after ${failedPing - 1} successful ping/pongs)\",\n ),\n isWriter = true,\n )\n return\n }\n\n try {\n writer.writePing(ByteString.EMPTY)\n } catch (e: IOException) {\n failWebSocket(e = e, isWriter = true)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":617,"symbol":"failWebSocket","kind":"function","lang":"kotlin","code":"fun failWebSocket(\n e: Exception,\n response: Response? = null,\n isWriter: Boolean = false,\n ) {\n val socketToCancel: Socket?\n val writerToClose: WebSocketWriter?\n synchronized(this) {\n if (failed) return // Already failed.\n failed = true\n\n socketToCancel = this.socket\n\n writerToClose = this.writer\n this.writer = null\n\n if (!isWriter && writerToClose != null) {\n // If the caller isn't the writer thread, get that thread to close the writer.\n taskQueue.execute(\"$name writer close\", cancelable = false) {\n writerToClose.closeQuietly()\n }\n }\n\n taskQueue.shutdown()\n }\n\n try {\n listener.onFailure(this, e, response)\n } finally {\n socketToCancel?.cancel()\n\n // If the caller is the writer thread, close it on this thread.\n if (isWriter) {\n writerToClose?.closeQuietly()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":666,"symbol":"WriterTask","kind":"class","lang":"kotlin","code":"private inner class WriterTask : Task(\"$name writer\") {\n override fun runOnce(): Long {\n try {\n if (writeOneFrame()) return 0L\n } catch (e: IOException) {\n failWebSocket(e = e, isWriter = true)\n }\n return -1L\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt","line":667,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n try {\n if (writeOneFrame()) return 0L\n } catch (e: IOException) {\n failWebSocket(e = e, isWriter = true)\n }\n return -1L\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketExtensions.kt","line":60,"symbol":"WebSocketExtensions","kind":"class","lang":"kotlin","doc":"* If `server_max_window_bits` is less than 15, OkHttp will waste memory on an oversized buffer. See [RFC 7692, 7.1][rfc_7692] for details on negotiation process. [rfc_7692]: https://tools.ietf.org/html/rfc7692#section-7.1","code":"@IgnoreJRERequirement // As of AGP 3.4.1, D8 desugars API 24 hashCode methods.\ndata class WebSocketExtensions(\n /** True if the agreed upon extensions includes the permessage-deflate extension. */\n @JvmField val perMessageDeflate: Boolean = false,\n /** Should be a value in [8..15]. Only 15 is acceptable by OkHttp as Java APIs are limited. */\n @JvmField val clientMaxWindowBits: Int? = null,\n /** True if the agreed upon extension parameters includes \"client_no_context_takeover\". */\n @JvmField val clientNoContextTakeover: Boolean = false,\n /** Should be a value in [8..15]. Any value in that range is acceptable by OkHttp. */\n @JvmField val serverMaxWindowBits: Int? = null,\n /** True if the agreed upon extension parameters includes \"server_no_context_takeover\". */\n @JvmField val serverNoContextTakeover: Boolean = false,\n /**\n * True if the agreed upon extensions or parameters contained values unrecognized by OkHttp.\n * Typically this indicates that the client will need to close the web socket with code 1010.\n */\n @JvmField val unknownValues: Boolean = false,\n) {\n fun noContextTakeover(clientOriginated: Boolean): Boolean =\n if (clientOriginated) {\n clientNoCont"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketExtensions.kt","line":78,"symbol":"noContextTakeover","kind":"function","lang":"kotlin","code":"fun noContextTakeover(clientOriginated: Boolean): Boolean =\n if (clientOriginated) {\n clientNoContextTakeover // Client is deflating.\n } else {\n serverNoContextTakeover // Server is deflating.\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketExtensions.kt","line":88,"symbol":"parse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun parse(responseHeaders: Headers): WebSocketExtensions {\n // Note that this code does case-insensitive comparisons, even though the spec doesn't specify\n // whether extension tokens and parameters are case-insensitive or not.\n\n var compressionEnabled = false\n var clientMaxWindowBits: Int? = null\n var clientNoContextTakeover = false\n var serverMaxWindowBits: Int? = null\n var serverNoContextTakeover = false\n var unexpectedValues = false\n\n // Parse each header.\n for (i in 0 until responseHeaders.size) {\n if (!responseHeaders.name(i).equals(HEADER_WEB_SOCKET_EXTENSION, ignoreCase = true)) {\n continue // Not a header we're interested in.\n }\n val header = responseHeaders.value(i)\n\n // Parse each extension.\n var pos = 0\n while (pos < header.length) {\n val extensionEnd = header.delimiterOffset(',', pos)\n val extensionTokenEnd = header.delimiterOffset(';', pos, extensionEnd)\n val extensionToken = header.trimSubstring(pos, extensionTokenEnd)\n pos = extensionTokenEnd + 1\n\n when {\n extensionToken.equals(\"p"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketProtocol.kt","line":21,"symbol":"WebSocketProtocol","kind":"object","lang":"kotlin","code":"object WebSocketProtocol {\n /** Magic value which must be appended to the key in a response header. */\n internal const val ACCEPT_MAGIC = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\"\n\n /*\n Each frame starts with two bytes of data.\n\n 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7\n +-+-+-+-+-------+ +-+-------------+\n |F|R|R|R| OP | |M| LENGTH |\n |I|S|S|S| CODE | |A| |\n |N|V|V|V| | |S| |\n | |1|2|3| | |K| |\n +-+-+-+-+-------+ +-+-------------+\n */\n\n /** Byte 0 flag for whether this is the final fragment in a message. */\n internal const val B0_FLAG_FIN = 128\n\n /** Byte 0 reserved flag 1. Must be 0 unless negotiated otherwise. */\n internal const val B0_FLAG_RSV1 = 64\n\n /** Byte 0 reserved flag 2. Must be 0 unless negotiated otherwise. */\n internal const val B0_FLAG_RSV2 = 32\n\n /** Byte 0 reserved flag 3. Must be 0 unless negotiated otherwise. */\n internal const val B0_FLAG_RSV3 = 16\n\n /** Byte 0 mask for the frame opcode. */\n internal const val B0_MASK_OPCODE = 15\n\n /** Flag in the opcode which indicates a control frame. */\n internal const val OPCODE_FLAG_CONTROL = 8\n\n /**\n * Byte 1 flag for whether the payload da"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketProtocol.kt","line":109,"symbol":"toggleMask","kind":"function","lang":"kotlin","code":"fun toggleMask(\n cursor: Buffer.UnsafeCursor,\n key: ByteArray,\n ) {\n var keyIndex = 0\n val keyLength = key.size\n do {\n val buffer = cursor.data\n var i = cursor.start\n val end = cursor.end\n if (buffer != null) {\n while (i < end) {\n keyIndex %= keyLength // Reassign to prevent overflow breaking counter.\n\n // Byte xor is experimental in Kotlin so we coerce bytes to int, xor them\n // and convert back to byte.\n val bufferInt: Int = buffer[i].toInt()\n val keyInt: Int = key[keyIndex].toInt()\n buffer[i] = (bufferInt xor keyInt).toByte()\n\n i++\n keyIndex++\n }\n }\n } while (cursor.next() != -1)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketProtocol.kt","line":136,"symbol":"closeCodeExceptionMessage","kind":"function","lang":"kotlin","code":"fun closeCodeExceptionMessage(code: Int): String? =\n if (code < 1000 || code >= 5000) {\n \"Code must be in range [1000,5000): $code\"\n } else if (code in 1004..1006 || code in 1015..2999) {\n \"Code $code is reserved and may not be used.\"\n } else {\n null\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketProtocol.kt","line":145,"symbol":"validateCloseCode","kind":"function","lang":"kotlin","code":"fun validateCloseCode(code: Int) {\n val message = closeCodeExceptionMessage(code)\n require(message == null) { message!! }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketProtocol.kt","line":150,"symbol":"acceptHeader","kind":"function","lang":"kotlin","code":"fun acceptHeader(key: String): String = (key + ACCEPT_MAGIC).encodeUtf8().sha1().base64()"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":55,"symbol":"WebSocketReader","kind":"class","lang":"kotlin","doc":"An [RFC 6455][rfc_6455]-compatible WebSocket frame reader. This class is not thread safe. [rfc_6455]: http://tools.ietf.org/html/rfc6455","code":"class WebSocketReader(\n private val isClient: Boolean,\n val source: BufferedSource,\n private val frameCallback: FrameCallback,\n private val perMessageDeflate: Boolean,\n private val noContextTakeover: Boolean,\n) : Closeable {\n private var closed = false\n private var receivedCloseFrame = false\n\n // Stateful data about the current frame.\n private var opcode = 0\n private var frameLength = 0L\n private var isFinalFrame = false\n private var isControlFrame = false\n private var readingCompressedMessage = false\n\n private val controlFrameBuffer = Buffer()\n private val messageFrameBuffer = Buffer()\n\n /** Lazily initialized on first use. */\n private var messageInflater: MessageInflater? = null\n\n // Masks are only a concern for server writers.\n private val maskKey: ByteArray? = if (isClient) null else ByteArray(4)\n private val maskCursor: Buffer.UnsafeCursor? = if (isClient) null else Buffer.UnsafeCursor()\n\n interface FrameCallback {\n @Throws(IOException::class)\n fun onReadMessage(text: String)\n\n @Throws(IOException::class)\n fun onReadMessage(bytes: ByteString)\n\n fun onReadPing(payload: ByteString)\n\n fun onReadPong(payload: ByteString)\n\n fun onReadClose("} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":82,"symbol":"FrameCallback","kind":"interface","lang":"kotlin","code":"interface FrameCallback {\n @Throws(IOException::class)\n fun onReadMessage(text: String)\n\n @Throws(IOException::class)\n fun onReadMessage(bytes: ByteString)\n\n fun onReadPing(payload: ByteString)\n\n fun onReadPong(payload: ByteString)\n\n fun onReadClose(\n code: Int,\n reason: String,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":83,"symbol":"onReadMessage","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun onReadMessage(text: String)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":86,"symbol":"onReadMessage","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun onReadMessage(bytes: ByteString)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":89,"symbol":"onReadPing","kind":"function","lang":"kotlin","code":"fun onReadPing(payload: ByteString)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":91,"symbol":"onReadPong","kind":"function","lang":"kotlin","code":"fun onReadPong(payload: ByteString)"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":93,"symbol":"onReadClose","kind":"function","lang":"kotlin","code":"fun onReadClose(\n code: Int,\n reason: String,\n )"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":107,"symbol":"processNextFrame","kind":"function","lang":"kotlin","doc":"* If it is a control frame this will result in a single call to [FrameCallback]. * If it is a message frame this will result in a single call to [FrameCallback.onReadMessage]. If the message spans multiple frames, each interleaved control frame will result in a corresponding call to [FrameCallback].","code":"@Throws(IOException::class)\n fun processNextFrame() {\n check(!closed) { \"closed\" }\n\n readHeader()\n if (isControlFrame) {\n readControlFrame()\n } else {\n readMessageFrame()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":119,"symbol":"readHeader","kind":"function","lang":"kotlin","code":"@Throws(IOException::class, ProtocolException::class)\n private fun readHeader() {\n if (receivedCloseFrame) throw IOException(\"closed\")\n\n // Disable the timeout to read the first byte of a new frame.\n val b0: Int\n val timeoutBefore = source.timeout().timeoutNanos()\n source.timeout().clearTimeout()\n try {\n b0 = source.readByte() and 0xff\n } finally {\n source.timeout().timeout(timeoutBefore, TimeUnit.NANOSECONDS)\n }\n\n opcode = b0 and B0_MASK_OPCODE\n isFinalFrame = b0 and B0_FLAG_FIN != 0\n isControlFrame = b0 and OPCODE_FLAG_CONTROL != 0\n\n // Control frames must be final frames (cannot contain continuations).\n if (isControlFrame && !isFinalFrame) {\n throw ProtocolException(\"Control frames must be final.\")\n }\n\n val reservedFlag1 = b0 and B0_FLAG_RSV1 != 0\n when (opcode) {\n OPCODE_TEXT, OPCODE_BINARY -> {\n readingCompressedMessage =\n if (reservedFlag1) {\n if (!perMessageDeflate) throw ProtocolException(\"Unexpected rsv1 flag\")\n true\n } else {\n false\n }\n }\n\n else -> {\n if (reservedFlag1) throw ProtocolException(\"Unexpected rsv1 flag\")\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":202,"symbol":"readControlFrame","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readControlFrame() {\n if (frameLength > 0L) {\n source.readFully(controlFrameBuffer, frameLength)\n\n if (!isClient) {\n controlFrameBuffer.readAndWriteUnsafe(maskCursor!!)\n maskCursor.seek(0)\n toggleMask(maskCursor, maskKey!!)\n maskCursor.close()\n }\n }\n\n when (opcode) {\n OPCODE_CONTROL_PING -> {\n frameCallback.onReadPing(controlFrameBuffer.readByteString())\n }\n\n OPCODE_CONTROL_PONG -> {\n frameCallback.onReadPong(controlFrameBuffer.readByteString())\n }\n\n OPCODE_CONTROL_CLOSE -> {\n var code = CLOSE_NO_STATUS_CODE\n var reason = \"\"\n val bufferSize = controlFrameBuffer.size\n if (bufferSize == 1L) {\n throw ProtocolException(\"Malformed close payload length of 1.\")\n } else if (bufferSize != 0L) {\n code = controlFrameBuffer.readShort().toInt()\n reason = controlFrameBuffer.readUtf8()\n val codeExceptionMessage = WebSocketProtocol.closeCodeExceptionMessage(code)\n if (codeExceptionMessage != null) throw ProtocolException(codeExceptionMessage)\n }\n frameCallback.onReadClose(co"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":246,"symbol":"readMessageFrame","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun readMessageFrame() {\n val opcode = this.opcode\n if (opcode != OPCODE_TEXT && opcode != OPCODE_BINARY) {\n throw ProtocolException(\"Unknown opcode: ${opcode.toHexString()}\")\n }\n\n readMessage()\n\n if (readingCompressedMessage) {\n val messageInflater =\n this.messageInflater\n ?: MessageInflater(noContextTakeover).also { this.messageInflater = it }\n messageInflater.inflate(messageFrameBuffer)\n }\n\n if (opcode == OPCODE_TEXT) {\n frameCallback.onReadMessage(messageFrameBuffer.readUtf8())\n } else {\n frameCallback.onReadMessage(messageFrameBuffer.readByteString())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":270,"symbol":"readUntilNonControlFrame","kind":"function","lang":"kotlin","doc":"Read headers and process any control frames until we reach a non-control frame.","code":"@Throws(IOException::class)\n private fun readUntilNonControlFrame() {\n while (!receivedCloseFrame) {\n readHeader()\n if (!isControlFrame) {\n break\n }\n readControlFrame()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":286,"symbol":"readMessage","kind":"function","lang":"kotlin","doc":"Reads a message body into across one or more frames. Control frames that occur between fragments will be processed. If the message payload is masked this will unmask as it's being processed.","code":"@Throws(IOException::class)\n private fun readMessage() {\n while (true) {\n if (receivedCloseFrame) throw IOException(\"closed\")\n\n if (frameLength > 0L) {\n source.readFully(messageFrameBuffer, frameLength)\n\n if (!isClient) {\n messageFrameBuffer.readAndWriteUnsafe(maskCursor!!)\n maskCursor.seek(messageFrameBuffer.size - frameLength)\n toggleMask(maskCursor, maskKey!!)\n maskCursor.close()\n }\n }\n\n if (isFinalFrame) break // We are exhausted and have no continuations.\n\n readUntilNonControlFrame()\n if (opcode != OPCODE_CONTINUATION) {\n throw ProtocolException(\"Expected continuation opcode. Got: ${opcode.toHexString()}\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketReader.kt","line":311,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n if (closed) return\n closed = true\n messageInflater?.closeQuietly()\n source.closeQuietly()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketWriter.kt","line":45,"symbol":"WebSocketWriter","kind":"class","lang":"kotlin","doc":"An [RFC 6455][rfc_6455]-compatible WebSocket frame writer. This class is not thread safe. [rfc_6455]: http://tools.ietf.org/html/rfc6455","code":"class WebSocketWriter(\n private val isClient: Boolean,\n val sink: BufferedSink,\n val random: Random,\n private val perMessageDeflate: Boolean,\n private val noContextTakeover: Boolean,\n private val minimumDeflateSize: Long,\n) : Closeable {\n /** This holds outbound data for compression and masking. */\n private val messageBuffer = Buffer()\n\n /** The [Buffer] of [sink]. Write to this and then flush/emit [sink]. */\n private val sinkBuffer: Buffer = sink.buffer\n private var writerClosed = false\n\n /** Lazily initialized on first use. */\n private var messageDeflater: MessageDeflater? = null\n\n // Masks are only a concern for client writers.\n private val maskKey: ByteArray? = if (isClient) ByteArray(4) else null\n private val maskCursor: Buffer.UnsafeCursor? = if (isClient) Buffer.UnsafeCursor() else null\n\n /** Send a ping with the supplied [payload]. */\n @Throws(IOException::class)\n fun writePing(payload: ByteString) {\n writeControlFrame(OPCODE_CONTROL_PING, payload)\n }\n\n /** Send a pong with the supplied [payload]. */\n @Throws(IOException::class)\n fun writePong(payload: ByteString) {\n writeControlFrame(OPCODE_CONTROL_PONG, payload)\n }\n\n /**\n * Send a close fr"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketWriter.kt","line":68,"symbol":"writePing","kind":"function","lang":"kotlin","doc":"Send a ping with the supplied [payload].","code":"@Throws(IOException::class)\n fun writePing(payload: ByteString) {\n writeControlFrame(OPCODE_CONTROL_PING, payload)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketWriter.kt","line":74,"symbol":"writePong","kind":"function","lang":"kotlin","doc":"Send a pong with the supplied [payload].","code":"@Throws(IOException::class)\n fun writePong(payload: ByteString) {\n writeControlFrame(OPCODE_CONTROL_PONG, payload)\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketWriter.kt","line":86,"symbol":"writeClose","kind":"function","lang":"kotlin","doc":"Send a close frame with optional code and reason. @param code Status code as defined by [Section 7.4 of RFC 6455](http://tools.ietf.org/html/rfc6455#section-7.4) or `0`. @param reason Reason for shutting down or `null`.","code":"@Throws(IOException::class)\n fun writeClose(\n code: Int,\n reason: ByteString?,\n ) {\n var payload = ByteString.EMPTY\n if (code != 0 || reason != null) {\n if (code != 0) {\n validateCloseCode(code)\n }\n payload =\n Buffer().run {\n writeShort(code)\n if (reason != null) {\n write(reason)\n }\n readByteString()\n }\n }\n\n try {\n writeControlFrame(OPCODE_CONTROL_CLOSE, payload)\n } finally {\n writerClosed = true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketWriter.kt","line":113,"symbol":"writeControlFrame","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun writeControlFrame(\n opcode: Int,\n payload: ByteString,\n ) {\n if (writerClosed) throw IOException(\"closed\")\n\n val length = payload.size\n require(length <= PAYLOAD_BYTE_MAX) {\n \"Payload size must be less than or equal to $PAYLOAD_BYTE_MAX\"\n }\n\n val b0 = B0_FLAG_FIN or opcode\n sinkBuffer.writeByte(b0)\n\n var b1 = length\n if (isClient) {\n b1 = b1 or B1_FLAG_MASK\n sinkBuffer.writeByte(b1)\n\n random.nextBytes(maskKey!!)\n sinkBuffer.write(maskKey)\n\n if (length > 0) {\n val payloadStart = sinkBuffer.size\n sinkBuffer.write(payload)\n\n sinkBuffer.readAndWriteUnsafe(maskCursor!!)\n maskCursor.seek(payloadStart)\n toggleMask(maskCursor, maskKey)\n maskCursor.close()\n }\n } else {\n sinkBuffer.writeByte(b1)\n sinkBuffer.write(payload)\n }\n\n sink.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketWriter.kt","line":153,"symbol":"writeMessageFrame","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n fun writeMessageFrame(\n formatOpcode: Int,\n data: ByteString,\n ) {\n if (writerClosed) throw IOException(\"closed\")\n\n messageBuffer.write(data)\n\n var b0 = formatOpcode or B0_FLAG_FIN\n if (perMessageDeflate && data.size >= minimumDeflateSize) {\n val messageDeflater =\n this.messageDeflater\n ?: MessageDeflater(noContextTakeover).also { this.messageDeflater = it }\n messageDeflater.deflate(messageBuffer)\n b0 = b0 or B0_FLAG_RSV1\n }\n val dataSize = messageBuffer.size\n sinkBuffer.writeByte(b0)\n\n var b1 = 0\n if (isClient) {\n b1 = b1 or B1_FLAG_MASK\n }\n when {\n dataSize <= PAYLOAD_BYTE_MAX -> {\n b1 = b1 or dataSize.toInt()\n sinkBuffer.writeByte(b1)\n }\n\n dataSize <= PAYLOAD_SHORT_MAX -> {\n b1 = b1 or PAYLOAD_SHORT\n sinkBuffer.writeByte(b1)\n sinkBuffer.writeShort(dataSize.toInt())\n }\n\n else -> {\n b1 = b1 or PAYLOAD_LONG\n sinkBuffer.writeByte(b1)\n sinkBuffer.writeLong(dataSize)\n }\n }\n\n if (isClient) {\n random.nextBytes(maskKey!!)\n sinkBuffer.write(maskKey)\n\n if (dataSize > 0L) {\n "} {"repo":"okhttp","file":"okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/WebSocketWriter.kt","line":212,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n messageDeflater?.closeQuietly()\n sink.closeQuietly()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/CompressionInterceptorTest.kt","line":32,"symbol":"CompressionInterceptorTest","kind":"class","lang":"kotlin","code":"class CompressionInterceptorTest {\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n val source =\n Buffer().apply {\n write(\"Hello World\".encodeUtf8())\n } as Source\n\n @Test\n fun emptyDoesntChangeRequestOrResponse() {\n val empty = CompressionInterceptor()\n val client =\n clientTestRule\n .newClientBuilder()\n .addInterceptor(empty)\n .addInterceptor { chain ->\n assertThat(chain.request().header(\"Accept-Encoding\")).isNull()\n Response\n .Builder()\n .request(chain.request())\n .protocol(Protocol.HTTP_1_1)\n .code(200)\n .message(\"OK\")\n .body(\"Hello\".toResponseBody())\n .header(\"Content-Encoding\", \"piedpiper\")\n .build()\n }.build()\n\n val response = client.newCall(Request(\"https://google.com/robots.txt\".toHttpUrl())).execute()\n\n assertThat(response.header(\"Content-Encoding\")).isEqualTo(\"piedpiper\")\n assertThat(response.body.string()).isEqualTo(\"Hello\")\n }\n\n @Test\n fun gzipThroughCall() {\n val gzip = CompressionInterceptor(Gzip)\n val client =\n clientTestRule\n .newClientBuilder()\n .addInte"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/CompressionInterceptorTest.kt","line":41,"symbol":"emptyDoesntChangeRequestOrResponse","kind":"function","lang":"kotlin","code":"@Test\n fun emptyDoesntChangeRequestOrResponse() {\n val empty = CompressionInterceptor()\n val client =\n clientTestRule\n .newClientBuilder()\n .addInterceptor(empty)\n .addInterceptor { chain ->\n assertThat(chain.request().header(\"Accept-Encoding\")).isNull()\n Response\n .Builder()\n .request(chain.request())\n .protocol(Protocol.HTTP_1_1)\n .code(200)\n .message(\"OK\")\n .body(\"Hello\".toResponseBody())\n .header(\"Content-Encoding\", \"piedpiper\")\n .build()\n }.build()\n\n val response = client.newCall(Request(\"https://google.com/robots.txt\".toHttpUrl())).execute()\n\n assertThat(response.header(\"Content-Encoding\")).isEqualTo(\"piedpiper\")\n assertThat(response.body.string()).isEqualTo(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/CompressionInterceptorTest.kt","line":67,"symbol":"gzipThroughCall","kind":"function","lang":"kotlin","code":"@Test\n fun gzipThroughCall() {\n val gzip = CompressionInterceptor(Gzip)\n val client =\n clientTestRule\n .newClientBuilder()\n .addInterceptor(gzip)\n .addInterceptor { chain ->\n assertThat(chain.request().header(\"Accept-Encoding\")).isEqualTo(\"gzip\")\n\n Response\n .Builder()\n .request(chain.request())\n .protocol(Protocol.HTTP_1_1)\n .code(200)\n .message(\"OK\")\n .body(gzip(\"Hello\").asResponseBody())\n .header(\"Content-Encoding\", \"gzip\")\n .build()\n }.build()\n\n val response = client.newCall(Request(\"https://google.com/robots.txt\".toHttpUrl())).execute()\n\n assertThat(response.header(\"Content-Encoding\")).isNull()\n assertThat(response.body.string()).isEqualTo(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/CompressionInterceptorTest.kt","line":94,"symbol":"gzip","kind":"function","lang":"kotlin","code":"private fun gzip(data: String): Buffer {\n val result = Buffer()\n val sink = GzipSink(result).buffer()\n sink.writeUtf8(data)\n sink.close()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":27,"symbol":"DnsValuesTest","kind":"class","lang":"kotlin","code":"class DnsValuesTest {\n @Test\n fun `request canonical hostname`() {\n assertThat(Dns.Request(hostname = \"EXAMPLE.COM\").hostname)\n .isEqualTo(\"example.com\")\n }\n\n @Test\n fun `request invalid hostname`() {\n assertFailsWith {\n Dns.Request(hostname = \"\")\n }\n assertFailsWith {\n Dns.Request(hostname = \"a\".repeat(64))\n }\n assertFailsWith {\n Dns.Request(hostname = (\"${\"a\".repeat(55)}.\".repeat(5)))\n }\n assertFailsWith {\n Dns.Request(hostname = \"a?b\")\n }\n }\n\n @Test\n fun `request invalid port`() {\n assertFailsWith {\n Dns.Request(hostname = \"example.com\", port = -2)\n }\n assertFailsWith {\n Dns.Request(hostname = \"example.com\", port = 0)\n }\n assertFailsWith {\n Dns.Request(hostname = \"example.com\", port = 65536)\n }\n }\n\n @Test\n fun `default port`() {\n assertThat(Dns.Request(hostname = \"example.com\", port = -1).port)\n .isEqualTo(443)\n }\n\n @Test\n fun `request equals and hashCode`() {\n assertThat(Dns.Request(hostname"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":28,"symbol":"`request canonical hostname`","kind":"function","lang":"kotlin","code":"@Test\n fun `request canonical hostname`() {\n assertThat(Dns.Request(hostname = \"EXAMPLE.COM\").hostname)\n .isEqualTo(\"example.com\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":34,"symbol":"`request invalid hostname`","kind":"function","lang":"kotlin","code":"@Test\n fun `request invalid hostname`() {\n assertFailsWith {\n Dns.Request(hostname = \"\")\n }\n assertFailsWith {\n Dns.Request(hostname = \"a\".repeat(64))\n }\n assertFailsWith {\n Dns.Request(hostname = (\"${\"a\".repeat(55)}.\".repeat(5)))\n }\n assertFailsWith {\n Dns.Request(hostname = \"a?b\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":50,"symbol":"`request invalid port`","kind":"function","lang":"kotlin","code":"@Test\n fun `request invalid port`() {\n assertFailsWith {\n Dns.Request(hostname = \"example.com\", port = -2)\n }\n assertFailsWith {\n Dns.Request(hostname = \"example.com\", port = 0)\n }\n assertFailsWith {\n Dns.Request(hostname = \"example.com\", port = 65536)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":63,"symbol":"`default port`","kind":"function","lang":"kotlin","code":"@Test\n fun `default port`() {\n assertThat(Dns.Request(hostname = \"example.com\", port = -1).port)\n .isEqualTo(443)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":69,"symbol":"`request equals and hashCode`","kind":"function","lang":"kotlin","code":"@Test\n fun `request equals and hashCode`() {\n assertThat(Dns.Request(hostname = \"example.com\", port = 443))\n .isEqualTo(Dns.Request(hostname = \"example.com\", port = 443))\n assertThat(Dns.Request(hostname = \"example.com\", port = 443).hashCode())\n .isEqualTo(Dns.Request(hostname = \"example.com\", port = 443).hashCode())\n assertThat(Dns.Request(hostname = \"example.com\", port = 443))\n .isNotEqualTo(Dns.Request(hostname = \"example.com\", port = 8443))\n assertThat(Dns.Request(hostname = \"example.com\", port = 443))\n .isNotEqualTo(Dns.Request(hostname = \"example.net\", port = 443))\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":81,"symbol":"`request to string`","kind":"function","lang":"kotlin","code":"@Test\n fun `request to string`() {\n assertThat(Dns.Request(hostname = \"example.com\", port = 443).toString())\n .isEqualTo(\"example.com\")\n assertThat(Dns.Request(hostname = \"example.com\", port = 8443).toString())\n .isEqualTo(\"example.com:8443\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":89,"symbol":"`ip address record invalid hostname`","kind":"function","lang":"kotlin","code":"@Test\n fun `ip address record invalid hostname`() {\n val address = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))\n assertFailsWith {\n Dns.Record.IpAddress(hostname = \"\", address = address)\n }\n assertFailsWith {\n Dns.Record.IpAddress(hostname = \"a\".repeat(64), address = address)\n }\n assertFailsWith {\n Dns.Record.IpAddress(hostname = (\"${\"a\".repeat(55)}.\".repeat(5)), address = address)\n }\n assertFailsWith {\n Dns.Record.IpAddress(hostname = \"a?b\", address = address)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":106,"symbol":"`ip address equals and hashCode`","kind":"function","lang":"kotlin","code":"@Test\n fun `ip address equals and hashCode`() {\n val address1 = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))\n val address2 = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 2))\n assertThat(Dns.Record.IpAddress(hostname = \"example.com\", address = address1))\n .isEqualTo(Dns.Record.IpAddress(hostname = \"example.com\", address = address1))\n assertThat(Dns.Record.IpAddress(hostname = \"example.com\", address = address1).hashCode())\n .isEqualTo(Dns.Record.IpAddress(hostname = \"example.com\", address = address1).hashCode())\n assertThat(Dns.Record.IpAddress(hostname = \"example.com\", address = address1))\n .isNotEqualTo(Dns.Record.IpAddress(hostname = \"example.com\", address = address2))\n assertThat(Dns.Record.IpAddress(hostname = \"example.com\", address = address1).hashCode())\n .isNotEqualTo(Dns.Record.IpAddress(hostname = \"example.com\", address = address2).hashCode())\n assertThat(Dns.Record.IpAddress(hostname = \"example.com\", address = address1))\n .isNotEqualTo(Dns.Record.IpAddress(hostname = \"example.net\", address = address1))\n assertThat(Dns.Record.IpAddress(hostname = \"example.com\", address = address1).hashCode())\n .isNotEqualTo(Dn"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":124,"symbol":"`ip address toString`","kind":"function","lang":"kotlin","code":"@Test\n fun `ip address toString`() {\n val address = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))\n assertThat(Dns.Record.IpAddress(hostname = \"example.com\", address = address).toString())\n .isEqualTo(\"example.com/127.0.0.1\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":131,"symbol":"`service metadata invalid hostname`","kind":"function","lang":"kotlin","code":"@Test\n fun `service metadata invalid hostname`() {\n assertFailsWith {\n Dns.Record.ServiceMetadata(hostname = \"\")\n }\n assertFailsWith {\n Dns.Record.ServiceMetadata(hostname = \"a\".repeat(64))\n }\n assertFailsWith {\n Dns.Record.ServiceMetadata(hostname = (\"${\"a\".repeat(55)}.\".repeat(5)))\n }\n assertFailsWith {\n Dns.Record.ServiceMetadata(hostname = \"a?b\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":147,"symbol":"`service metadata invalid port`","kind":"function","lang":"kotlin","code":"@Test\n fun `service metadata invalid port`() {\n assertFailsWith {\n Dns.Record.ServiceMetadata(hostname = \"example.com\", port = -2)\n }\n assertFailsWith {\n Dns.Record.ServiceMetadata(hostname = \"example.com\", port = 0)\n }\n assertFailsWith {\n Dns.Record.ServiceMetadata(hostname = \"example.com\", port = 65536)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":160,"symbol":"`service metadata equals and hashCode`","kind":"function","lang":"kotlin","code":"@Test\n fun `service metadata equals and hashCode`() {\n val original =\n Dns.Record.ServiceMetadata(\n hostname = \"example.com\",\n port = 443,\n alpnIds = listOf(Protocol.HTTP_1_1, Protocol.HTTP_2),\n ipAddressHints = listOf(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))),\n echConfigList = \"hello I am ECH config\".encodeUtf8(),\n )\n assertThat(original).isEqualTo(\n Dns.Record.ServiceMetadata(\n hostname = \"example.com\",\n port = 443,\n alpnIds = listOf(Protocol.HTTP_1_1, Protocol.HTTP_2),\n ipAddressHints = listOf(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))),\n echConfigList = \"hello I am ECH config\".encodeUtf8(),\n ),\n )\n assertThat(original.hashCode()).isEqualTo(\n Dns.Record\n .ServiceMetadata(\n hostname = \"example.com\",\n port = 443,\n alpnIds = listOf(Protocol.HTTP_1_1, Protocol.HTTP_2),\n ipAddressHints = listOf(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))),\n echConfigList = \"hello I am ECH config\".encodeUtf8(),\n ).hashCode(),\n )\n assertThat(original).isNotIn(\n Dns.Record.ServiceMetadata(\n hos"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/DnsValuesTest.kt","line":228,"symbol":"`service metadata toString`","kind":"function","lang":"kotlin","code":"@Test\n fun `service metadata toString`() {\n val empty =\n Dns.Record.ServiceMetadata(\n hostname = \"example.com\",\n )\n assertThat(empty.toString()).isEqualTo(\n \"ServiceMetadata{example.com}\",\n )\n val full =\n Dns.Record.ServiceMetadata(\n hostname = \"example.com\",\n port = 443,\n alpnIds = listOf(Protocol.HTTP_1_1, Protocol.HTTP_2),\n ipAddressHints = listOf(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))),\n echConfigList = \"hello I am ECH config\".encodeUtf8(),\n )\n assertThat(full.toString()).isEqualTo(\n \"ServiceMetadata{example.com, alpnIds=[http/1.1, h2], ipAddressHints=[127.0.0.1], \" +\n \"echConfigList=68656c6c6f204920616d2045434820636f6e666967}\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/OkHttpTest.kt","line":7,"symbol":"OkHttpTest","kind":"class","lang":"kotlin","code":"class OkHttpTest {\n @Test\n fun testVersion() {\n assertThat(OkHttp.VERSION).matches(Regex(\"[0-9]+\\\\.[0-9]+\\\\.[0-9]+(-.+)?\"))\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/OkHttpTest.kt","line":8,"symbol":"testVersion","kind":"function","lang":"kotlin","code":"@Test\n fun testVersion() {\n assertThat(OkHttp.VERSION).matches(Regex(\"[0-9]+\\\\.[0-9]+\\\\.[0-9]+(-.+)?\"))\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/IsProbablyUtf8Test.kt","line":28,"symbol":"IsProbablyUtf8Test","kind":"class","lang":"kotlin","code":"class IsProbablyUtf8Test {\n @Test fun isProbablyUtf8() {\n assertThat(Buffer().isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeUtf8(\"abc\").isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeUtf8(\"new\\r\\nlines\").isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeUtf8(\"white\\t space\").isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeUtf8(\"Слава Україні!\").isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeByte(0x80).isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeByte(0x00).isProbablyUtf8(16L)).isFalse()\n assertThat(Buffer().writeByte(0xc0).isProbablyUtf8(16L)).isFalse()\n }\n\n @Test fun doesNotConsumeBuffer() {\n val buffer = Buffer()\n buffer.writeUtf8(\"hello \".repeat(1024))\n assertThat(buffer.isProbablyUtf8(100L)).isTrue()\n assertThat(buffer.readUtf8()).isEqualTo(\"hello \".repeat(1024))\n }\n\n /** Confirm [isProbablyUtf8] doesn't attempt to read the entire stream. */\n @Test fun doesNotReadEntireSource() {\n val unlimitedSource =\n object : Source {\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n sink.writeUtf8(\"a\".repeat(byteCount.toInt()))\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/IsProbablyUtf8Test.kt","line":29,"symbol":"isProbablyUtf8","kind":"function","lang":"kotlin","code":"@Test fun isProbablyUtf8() {\n assertThat(Buffer().isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeUtf8(\"abc\").isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeUtf8(\"new\\r\\nlines\").isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeUtf8(\"white\\t space\").isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeUtf8(\"Слава Україні!\").isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeByte(0x80).isProbablyUtf8(16L)).isTrue()\n assertThat(Buffer().writeByte(0x00).isProbablyUtf8(16L)).isFalse()\n assertThat(Buffer().writeByte(0xc0).isProbablyUtf8(16L)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/IsProbablyUtf8Test.kt","line":40,"symbol":"doesNotConsumeBuffer","kind":"function","lang":"kotlin","code":"@Test fun doesNotConsumeBuffer() {\n val buffer = Buffer()\n buffer.writeUtf8(\"hello \".repeat(1024))\n assertThat(buffer.isProbablyUtf8(100L)).isTrue()\n assertThat(buffer.readUtf8()).isEqualTo(\"hello \".repeat(1024))\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/IsProbablyUtf8Test.kt","line":48,"symbol":"doesNotReadEntireSource","kind":"function","lang":"kotlin","doc":"Confirm [isProbablyUtf8] doesn't attempt to read the entire stream.","code":"@Test fun doesNotReadEntireSource() {\n val unlimitedSource =\n object : Source {\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n sink.writeUtf8(\"a\".repeat(byteCount.toInt()))\n return byteCount\n }\n\n override fun close() {\n }\n\n override fun timeout() = Timeout.NONE\n }\n\n assertThat(unlimitedSource.buffer().isProbablyUtf8(1L)).isTrue()\n assertThat(unlimitedSource.buffer().isProbablyUtf8(1024L)).isTrue()\n assertThat(unlimitedSource.buffer().isProbablyUtf8(1024L * 1024L)).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/IsProbablyUtf8Test.kt","line":51,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n sink.writeUtf8(\"a\".repeat(byteCount.toInt()))\n return byteCount\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/IsProbablyUtf8Test.kt","line":59,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/IsProbablyUtf8Test.kt","line":62,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout() = Timeout.NONE"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":38,"symbol":"DnsMessageReaderRecordedValuesTest","kind":"class","lang":"kotlin","doc":"Those are the subjects of this test. We used the Tranco list generated on 13 July 2026. Available at https://tranco-list.eu/list/74JZX.","code":"class DnsMessageReaderRecordedValuesTest {\n @Test\n fun `resource record with compressed suffix`() {\n val reader =\n DnsMessageReader(\n \"00008180000100040000000006676f6f676c6503636f6d00001c0001c00c001c00010000003c00102607f8b0\" +\n \"402318070000000000000071c00c001c00010000003c00102607f8b0402318070000000000000065c00c00\" +\n \"1c00010000003c00102607f8b040231807000000000000008ac00c001c00010000003c00102607f8b04023\" +\n \"1807000000000000008b\",\n )\n assertThat(reader.read()).isEqualTo(\n DnsMessage(\n id = 0,\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"google.com\",\n type = TYPE_AAAA,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"google.com\",\n timeToLive = 60,\n address = InetAddress.getByName(\"2607:f8b0:4023:1807:0:0:0:71\"),\n ),\n ResourceRecord.IpAddress(\n name = \"google.com\",\n timeToLive = 60,\n address = InetAddress.getByName(\"2607:f8b0:4023:1807:0:0:0:65\"),\n ),\n ResourceRecord"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":39,"symbol":"`resource record with compressed suffix`","kind":"function","lang":"kotlin","code":"@Test\n fun `resource record with compressed suffix`() {\n val reader =\n DnsMessageReader(\n \"00008180000100040000000006676f6f676c6503636f6d00001c0001c00c001c00010000003c00102607f8b0\" +\n \"402318070000000000000071c00c001c00010000003c00102607f8b0402318070000000000000065c00c00\" +\n \"1c00010000003c00102607f8b040231807000000000000008ac00c001c00010000003c00102607f8b04023\" +\n \"1807000000000000008b\",\n )\n assertThat(reader.read()).isEqualTo(\n DnsMessage(\n id = 0,\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"google.com\",\n type = TYPE_AAAA,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"google.com\",\n timeToLive = 60,\n address = InetAddress.getByName(\"2607:f8b0:4023:1807:0:0:0:71\"),\n ),\n ResourceRecord.IpAddress(\n name = \"google.com\",\n timeToLive = 60,\n address = InetAddress.getByName(\"2607:f8b0:4023:1807:0:0:0:65\"),\n ),\n ResourceRecord.IpAddress(\n name = \"google.com\""} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":86,"symbol":"`resource record with not compressed suffix`","kind":"function","lang":"kotlin","code":"@Test\n fun `resource record with not compressed suffix`() {\n val reader =\n DnsMessageReader(\n \"00008180000100010000000106676f6f676c6503636f6d0000010001c00c000100010000028e0004acd917ee\" +\n \"00002904d000000000000d000c0009585858585858585858\",\n )\n assertThat(reader.read()).isEqualTo(\n DnsMessage(\n id = 0,\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"google.com\",\n type = TYPE_A,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"google.com\",\n timeToLive = 654,\n address = InetAddress.getByName(\"172.217.23.238\"),\n ),\n ),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":116,"symbol":"`ignore cname`","kind":"function","lang":"kotlin","code":"@Test\n fun `ignore cname`() {\n val reader =\n DnsMessageReader(\n \"0000818000010002000000000567726170680866616365626f6f6b03636f6d0000010001c00c000500010000\" +\n \"0a0f000c04737461720463313072c012c030000100010000002e00041f0d5008\",\n )\n assertThat(reader.read()).isEqualTo(\n DnsMessage(\n id = 0,\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"graph.facebook.com\",\n type = TYPE_A,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"star.c10r.facebook.com\",\n timeToLive = 46,\n address = InetAddress.getByName(\"31.13.80.8\"),\n ),\n ),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":146,"symbol":"`ignore soa`","kind":"function","lang":"kotlin","code":"@Test\n fun `ignore soa`() {\n val reader =\n DnsMessageReader(\n \"0000818300010000000100000e7364666c6b686673646c6b6a646602656500001c0001c01b00060001000004\" +\n \"ff0038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e6574c01b6a554d2d\" +\n \"00000e10000003840012750000000e10\",\n )\n assertThat(reader.read()).isEqualTo(\n DnsMessage(\n id = 0,\n flags = -32381,\n questions =\n listOf(\n Question(\n name = \"sdflkhfsdlkjdf.ee\",\n type = TYPE_AAAA,\n ),\n ),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":170,"symbol":"`ignore DNS extensions`","kind":"function","lang":"kotlin","doc":"https://www.rfc-editor.org/info/rfc6891/","code":"@Test\n fun `ignore DNS extensions`() {\n val reader =\n DnsMessageReader(\n \"00008180000100010000000106676f6f676c6503636f6d0000010001c00c000100010000028e0004acd917ee\" +\n \"00002904d000000000000d000c0009585858585858585858\",\n )\n assertThat(reader.read()).isEqualTo(\n DnsMessage(\n id = 0,\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"google.com\",\n type = TYPE_A,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"google.com\",\n timeToLive = 654,\n address = InetAddress.getByName(\"172.217.23.238\"),\n ),\n ),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":201,"symbol":"`https no-default-alpn`","kind":"function","lang":"kotlin","doc":"This site's HTTPS record claims it to be h2-only.","code":"@Test\n fun `https no-default-alpn`() {\n val reader =\n DnsMessageReader(\n \"00008180000100010000000008796c696c61757461036f72670000410001c00c004100010000012c000e0001\" +\n \"000001000302683200020000\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"ylilauta.org\",\n timeToLive = 300,\n alpnIds = listOf(\"h2\"),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":219,"symbol":"`https explicit port`","kind":"function","lang":"kotlin","doc":"The only domain that specifies [ResourceRecord.Https.port] sets it to the default. Sigh.","code":"@Test\n fun `https explicit port`() {\n val reader =\n DnsMessageReader(\n \"0000818000010001000000000d6169726e65777a65616c616e6402636f026e7a0000410001c00c0041000100\" +\n \"0002580010000100000100030268320003000201bb\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"airnewzealand.co.nz\",\n timeToLive = 600,\n alpnIds = listOf(\"h2\", \"http/1.1\"),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":236,"symbol":"`https multiple records`","kind":"function","lang":"kotlin","code":"@Test\n fun `https multiple records`() {\n val reader =\n DnsMessageReader(\n \"00008180000100020000000005666263646e036e65740000410001c00c004100010000039c000d0001000001\" +\n \"0006026832026833c00c004100010000039c0032000209737461722d6d696e690866616c6c6261636b0463\" +\n \"3130720866616365626f6f6b03636f6d0000010006026832026833\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"fbcdn.net\",\n timeToLive = 924,\n alpnIds = listOf(\"h2\", \"h3\", \"http/1.1\"),\n ),\n ResourceRecord.Https(\n name = \"fbcdn.net\",\n timeToLive = 924,\n priority = 2,\n targetName = \"star-mini.fallback.c10r.facebook.com\",\n alpnIds = listOf(\"h2\", \"h3\", \"http/1.1\"),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":262,"symbol":"`https alias mode`","kind":"function","lang":"kotlin","doc":"If [ResourceRecord.Https.priority] is 0, all parameters should be ignored.","code":"@Test\n fun `https alias mode`() {\n val reader =\n DnsMessageReader(\n \"000081800001000100000000076869737461747303636f6d0000410001c00c004100010000003c0022000007\" +\n \"6869737461747303636f6d0363646e0a636c6f7564666c617265036e657400\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"histats.com\",\n timeToLive = 60,\n priority = 0,\n targetName = \"histats.com.cdn.cloudflare.net\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":280,"symbol":"`https target cycle`","kind":"function","lang":"kotlin","code":"@Test\n fun `https target cycle`() {\n val reader =\n DnsMessageReader(\n \"00008180000100010000000006626565626f6d03636f6d0000410001c00c0041000100093a80000e00000662\" +\n \"6565626f6d03636f6d00\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"beebom.com\",\n timeToLive = 604800,\n priority = 0,\n targetName = \"beebom.com\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":298,"symbol":"`https target is not a hostname`","kind":"function","lang":"kotlin","code":"@Test\n fun `https target is not a hostname`() {\n val reader =\n DnsMessageReader(\n \"00008180000100010000000007617572616b6c65036465760000410001c00c00410001000002580009000005\" +\n \"3c6e696c3e00\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"aurakle.dev\",\n timeToLive = 600,\n priority = 0,\n targetName = \"\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":316,"symbol":"`https target is an IP address`","kind":"function","lang":"kotlin","code":"@Test\n fun `https target is an IP address`() {\n val reader =\n DnsMessageReader(\n \"00008180000100010000000004756e7a6503636f6d02706b0000410001c00c004100010000012c0010000002\" +\n \"32330332323702333802363500\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"unze.com.pk\",\n timeToLive = 300,\n priority = 0,\n targetName = \"23.227.38.65\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":335,"symbol":"`https default alpn is already in the alpn list`","kind":"function","lang":"kotlin","doc":"The spec says you shouldn't include 'http/1.1' in your alpn parameter, but this one does.","code":"@Test\n fun `https default alpn is already in the alpn list`() {\n val reader =\n DnsMessageReader(\n \"0000818000010002000000000770726f736f647902696d0000410001c00c004100010000012c001e00010000\" +\n \"010003026832000600102a00109803a000000000000000000001c00c004100010000012c00180002000001\" +\n \"000908687474702f312e3100040004b07ef24a\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"prosody.im\",\n timeToLive = 300,\n priority = 1,\n alpnIds = listOf(\"h2\", \"http/1.1\"),\n ipAddressHints = listOf(InetAddress.getByName(\"2a00:1098:3a0:0:0:0:0:1\")),\n ),\n ResourceRecord.Https(\n name = \"prosody.im\",\n timeToLive = 300,\n priority = 2,\n alpnIds = listOf(\"http/1.1\"),\n ipAddressHints = listOf(InetAddress.getByName(\"176.126.242.74\")),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":363,"symbol":"`https mandatory parameter`","kind":"function","lang":"kotlin","doc":"This record uses the `mandatory` service parameter.","code":"@Test\n fun `https mandatory parameter`() {\n val reader =\n DnsMessageReader(\n \"000081800001000100000000056d7467616c03636f6d0000410001c00c0041000100093a8000530001000000\" +\n \"00020001000100030268330005003f003dfe0d0039aa00200020a4a7bb34b77c43336c3a2931dd28c87d00\" +\n \"8218a99b44f1f0aa8a82537d487d43000400010001000a676f6f676c652e636f6d0000\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"mtgal.com\",\n timeToLive = 604800,\n alpnIds = listOf(\"h3\", \"http/1.1\"),\n echConfigList =\n \"\"\"\n 003dfe0d0039aa00200020a4a7bb34b77c43336c3a2931dd28c87d008218a99b44f1f0aa8a82537d487d4300\n 0400010001000a676f6f676c652e636f6d0000\n \"\"\".decodeHex(ignoreWhitespace = true),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":387,"symbol":"`https unknown service parameter`","kind":"function","lang":"kotlin","doc":"This record includes an unrecognized parameter (7), presumably a misconfiguration.","code":"@Test\n fun `https unknown service parameter`() {\n val reader =\n DnsMessageReader(\n \"0000818000010001000000000b706c616e616c746f6e6574036e65740262720000410001c00c004100010000\" +\n \"012c005c000105646e7372310b706c616e616c746f6e6574036e6574026272000001000602683202683300\" +\n \"03000201bb00040004be6d50fb0006001028041088000000000000000000000012000700102f646e732d71\" +\n \"756572797b3f646e737d\",\n )\n assertThat(reader.read().answers.filterIsInstance())\n .containsExactly(\n ResourceRecord.Https(\n name = \"planaltonet.net.br\",\n timeToLive = 300,\n targetName = \"dnsr1.planaltonet.net.br\",\n alpnIds = listOf(\"h2\", \"h3\", \"http/1.1\"),\n ipAddressHints =\n listOf(\n InetAddress.getByName(\"190.109.80.251\"),\n InetAddress.getByName(\"2804:1088:0:0:0:0:0:12\"),\n ),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderRecordedValuesTest.kt","line":412,"symbol":"DnsMessageReader","kind":"function","lang":"kotlin","code":"private fun DnsMessageReader(hex: String) = DnsMessageReader(Buffer().write(hex.decodeHex()))"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":31,"symbol":"DnsMessageReaderWriterTest","kind":"class","lang":"kotlin","code":"class DnsMessageReaderWriterTest {\n @Test\n fun `ipv4 round trip`() {\n assertRoundTrip(\n DnsMessage(\n id = 65432.toShort(),\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"lysine.dev\",\n type = TYPE_A,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 0,\n address = InetAddress.getByName(\"172.217.23.238\"),\n ),\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 86_400,\n address = InetAddress.getByName(\"31.13.80.8\"),\n ),\n ),\n ),\n )\n }\n\n @Test\n fun `ipv6 round trip`() {\n assertRoundTrip(\n DnsMessage(\n id = 65432.toShort(),\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"lysine.dev\",\n type = TYPE_AAAA,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 60,\n address = "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":32,"symbol":"`ipv4 round trip`","kind":"function","lang":"kotlin","code":"@Test\n fun `ipv4 round trip`() {\n assertRoundTrip(\n DnsMessage(\n id = 65432.toShort(),\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"lysine.dev\",\n type = TYPE_A,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 0,\n address = InetAddress.getByName(\"172.217.23.238\"),\n ),\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 86_400,\n address = InetAddress.getByName(\"31.13.80.8\"),\n ),\n ),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":62,"symbol":"`ipv6 round trip`","kind":"function","lang":"kotlin","code":"@Test\n fun `ipv6 round trip`() {\n assertRoundTrip(\n DnsMessage(\n id = 65432.toShort(),\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"lysine.dev\",\n type = TYPE_AAAA,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 60,\n address = InetAddress.getByName(\"2607:f8b0:4023:1807:0:0:0:71\"),\n ),\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 300,\n address = InetAddress.getByName(\"2607:f8b0:4023:1807:0:0:0:8b\"),\n ),\n ),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":96,"symbol":"`https round trip`","kind":"function","lang":"kotlin","doc":"This also confirms that name compression accepts elements from [ResourceRecord.Https] records and uses those records.","code":"@Test\n fun `https round trip`() {\n assertRoundTrip(\n DnsMessage(\n id = 65432.toShort(),\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"lysine.dev\",\n type = TYPE_HTTPS,\n ),\n ),\n answers =\n listOf(\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 60,\n priority = 2,\n targetName = \"ca-west.cdn.lysine.dev\",\n alpnIds = listOf(\"h2\", \"http/1.1\"),\n port = 8443,\n ipAddressHints =\n listOf(\n InetAddress.getByName(\"172.217.23.238\"),\n InetAddress.getByName(\"31.13.80.8\"),\n InetAddress.getByName(\"2607:f8b0:4023:1807:0:0:0:71\"),\n InetAddress.getByName(\"2607:f8b0:4023:1807:0:0:0:8b\"),\n ),\n echConfigList =\n \"\"\"\n 003dfe0d0039aa00200020a4a7bb34b77c43336c3a2931dd28c87d008218a99b44f1f0aa8a82537d487d\n 43000400010001000a676f6f676c652e636f6d0000\n \"\"\".decodeHex(ignoreWhitespace = true),\n ),\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":143,"symbol":"`unbounded name compression`","kind":"function","lang":"kotlin","code":"@Test\n fun `unbounded name compression`() {\n val buffer = Buffer()\n buffer.write(\n \"\"\"\n 000081800001000100000000066c7973696e65c00c000100010363646ec00c000100010000000000040a141e28\n \"\"\".decodeHex(ignoreWhitespace = true),\n )\n\n val reader = DnsMessageReader(buffer)\n val e =\n assertFailsWith {\n reader.read()\n }\n assertThat(e).hasMessage(\"malformed DNS message\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":165,"symbol":"`unsupported record with high-bit record length is skipped`","kind":"function","lang":"kotlin","doc":"An RDLENGTH is a 16-bit unsigned field, so a record may legitimately declare up to 65535 bytes of data. A value with the high bit set must still be skipped for record types we don't decode, otherwise the reader loses sync with the stream.","code":"@Test\n fun `unsupported record with high-bit record length is skipped`() {\n val buffer =\n Buffer().apply {\n writeShort(0x0000) // id\n writeShort(0x8180) // flags\n writeShort(1) // question count\n writeShort(1) // answer count\n writeShort(0) // authority record count\n writeShort(0) // additional record count\n\n // Question: \"a\", type A, class IN.\n writeByte(1)\n writeByte('a'.code)\n writeByte(0)\n writeShort(TYPE_A)\n writeShort(CLASS_IN)\n\n // Answer with an unsupported type and 0x8000 bytes of record data.\n writeShort(0xc00c) // Name compressed to the question's name.\n writeShort(16) // TYPE_TXT, which this reader doesn't decode.\n writeShort(CLASS_IN)\n writeInt(0) // time to live\n writeShort(0x8000) // record data length, 32768\n write(ByteArray(0x8000))\n }\n\n assertThat(DnsMessageReader(buffer).read()).isEqualTo(\n DnsMessage(\n id = 0,\n flags = -32384,\n questions =\n listOf(\n Question(\n name = \"a\",\n type = TYPE_A,\n ),\n ),\n answers = listOf(),\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":208,"symbol":"`rejects mandatory service parameter with unsupported key`","kind":"function","lang":"kotlin","code":"@Test\n fun `rejects mandatory service parameter with unsupported key`() {\n // An HTTPS record whose mandatory value is the single 2-octet SvcParamKey 0x0101 (257), which\n // OkHttp does not support. RFC 9460 requires such a record be treated as malformed.\n val buffer = Buffer()\n buffer.write(\n \"0000818000000001000000000000410001000000000009000100000000020101\".decodeHex(),\n )\n assertFailsWith {\n DnsMessageReader(buffer).read()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":221,"symbol":"`rejects odd length mandatory service parameter`","kind":"function","lang":"kotlin","code":"@Test\n fun `rejects odd length mandatory service parameter`() {\n // The mandatory value has an odd length, so it can't be a list of 2-octet SvcParamKeys.\n val buffer = Buffer()\n buffer.write(\n \"00008180000000010000000000004100010000000000080001000000000103\".decodeHex(),\n )\n assertFailsWith {\n DnsMessageReader(buffer).read()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/DnsMessageReaderWriterTest.kt","line":233,"symbol":"assertRoundTrip","kind":"function","lang":"kotlin","code":"private fun assertRoundTrip(message: DnsMessage) {\n val buffer = Buffer()\n DnsMessageWriter(buffer).write(message)\n assertThat(DnsMessageReader(buffer).read()).isEqualTo(message)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/EchRetryPlanTest.kt","line":33,"symbol":"EchRetryPlanTest","kind":"class","lang":"kotlin","doc":"Confirm we correctly validate the requirements of RFC 9849 public names. We're stricter with these than on regular DNS names, because we expect the DNS servers will reject those for us. https://www.rfc-editor.org/rfc/rfc9849.html#section-6.1.7","code":"class EchRetryPlanTest {\n @Test\n fun `valid public name`() {\n assertValid(\"ech.example.com\")\n assertValid(\"ECH.EXAMPLE.COM\")\n assertValid(\"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.example.com\")\n assertValid(\"0xG\")\n assertValid(\"0xG.example.com\")\n assertValid(\"0XG\")\n assertValid(\"0XG.example.com\")\n }\n\n @Test\n fun `invalid public name`() {\n assertInvalid(\"1:2::3:4\")\n assertInvalid(\"10.20.30.40\")\n assertInvalid(\"ech.example.com.\")\n assertInvalid(\".ech.example.com\")\n assertInvalid(\"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl.example.com\")\n assertInvalid(\"ech.example.123\")\n assertInvalid(\"ech.example.0x123\")\n assertInvalid(\"123\")\n assertInvalid(\"0xab\")\n assertInvalid(\"0XAB\")\n assertInvalid(\"0X\")\n }\n\n private fun assertValid(publicName: String) {\n assertThat(\n EchRetryPlan.getOrNull(\n publicName = publicName,\n configList = null,\n ),\n ).isNotNull()\n }\n\n private fun assertInvalid(publicName: String) {\n assertThat(\n EchRetryPlan.getOrNull(\n publicName = publicName,\n configList = null,\n ),\n ).isNull()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/EchRetryPlanTest.kt","line":34,"symbol":"`valid public name`","kind":"function","lang":"kotlin","code":"@Test\n fun `valid public name`() {\n assertValid(\"ech.example.com\")\n assertValid(\"ECH.EXAMPLE.COM\")\n assertValid(\"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijk.example.com\")\n assertValid(\"0xG\")\n assertValid(\"0xG.example.com\")\n assertValid(\"0XG\")\n assertValid(\"0XG.example.com\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/EchRetryPlanTest.kt","line":45,"symbol":"`invalid public name`","kind":"function","lang":"kotlin","code":"@Test\n fun `invalid public name`() {\n assertInvalid(\"1:2::3:4\")\n assertInvalid(\"10.20.30.40\")\n assertInvalid(\"ech.example.com.\")\n assertInvalid(\".ech.example.com\")\n assertInvalid(\"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl.example.com\")\n assertInvalid(\"ech.example.123\")\n assertInvalid(\"ech.example.0x123\")\n assertInvalid(\"123\")\n assertInvalid(\"0xab\")\n assertInvalid(\"0XAB\")\n assertInvalid(\"0X\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/EchRetryPlanTest.kt","line":60,"symbol":"assertValid","kind":"function","lang":"kotlin","code":"private fun assertValid(publicName: String) {\n assertThat(\n EchRetryPlan.getOrNull(\n publicName = publicName,\n configList = null,\n ),\n ).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/EchRetryPlanTest.kt","line":69,"symbol":"assertInvalid","kind":"function","lang":"kotlin","code":"private fun assertInvalid(publicName: String) {\n assertThat(\n EchRetryPlan.getOrNull(\n publicName = publicName,\n configList = null,\n ),\n ).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":29,"symbol":"MemoryCacheTest","kind":"class","lang":"kotlin","code":"class MemoryCacheTest {\n private var time = 0.seconds\n private val timeSource =\n object : AbstractLongTimeSource(DurationUnit.SECONDS) {\n override fun read() = time.inWholeSeconds\n }\n\n private val cache =\n object : MemoryCache(\n timeSource = timeSource,\n maxSize = 4,\n ) {\n override fun lastRequestedAt(\n now: Time,\n value: Record,\n ): Time? {\n val evictAt = value.evictAt ?: return null\n if (now >= evictAt) return null\n return value.lastRequestedAt\n }\n }\n\n @Test\n fun `computeIfAbsent remembers values`() {\n val a0 = cache.access(\"a\")\n val b0 = cache.access(\"b\")\n val c0 = cache.access(\"c\")\n\n cache.assertPresent(\"a\", a0)\n cache.assertPresent(\"b\", b0)\n cache.assertPresent(\"c\", c0)\n }\n\n /** Use a re-entrant call to simulate a concurrent call.*/\n @Test\n fun `computeIfAbsent race`() {\n val now = timeSource.markNow()\n val r0 = Record(\"r0\", now, now)\n val r1 = Record(\"r1\", now, now)\n val a0 =\n cache.computeIfAbsent(\"a\") {\n val a1 = cache.computeIfAbsent(\"a\") { r1 }\n assertThat(a1).isSameInstanceAs(r1)\n r0\n }\n assertThat(a0).is"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":33,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read() = time.inWholeSeconds"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":41,"symbol":"lastRequestedAt","kind":"function","lang":"kotlin","code":"override fun lastRequestedAt(\n now: Time,\n value: Record,\n ): Time? {\n val evictAt = value.evictAt ?: return null\n if (now >= evictAt) return null\n return value.lastRequestedAt\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":51,"symbol":"`computeIfAbsent remembers values`","kind":"function","lang":"kotlin","code":"@Test\n fun `computeIfAbsent remembers values`() {\n val a0 = cache.access(\"a\")\n val b0 = cache.access(\"b\")\n val c0 = cache.access(\"c\")\n\n cache.assertPresent(\"a\", a0)\n cache.assertPresent(\"b\", b0)\n cache.assertPresent(\"c\", c0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":63,"symbol":"`computeIfAbsent race`","kind":"function","lang":"kotlin","doc":"Use a re-entrant call to simulate a concurrent call.","code":"@Test\n fun `computeIfAbsent race`() {\n val now = timeSource.markNow()\n val r0 = Record(\"r0\", now, now)\n val r1 = Record(\"r1\", now, now)\n val a0 =\n cache.computeIfAbsent(\"a\") {\n val a1 = cache.computeIfAbsent(\"a\") { r1 }\n assertThat(a1).isSameInstanceAs(r1)\n r0\n }\n assertThat(a0).isSameInstanceAs(r1)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":77,"symbol":"`evictAll evicts all`","kind":"function","lang":"kotlin","code":"@Test\n fun `evictAll evicts all`() {\n cache.access(\"a\")\n cache.access(\"b\")\n\n cache.evictAll()\n cache.assertAbsent(\"a\")\n cache.assertAbsent(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":87,"symbol":"`evict removes expired records`","kind":"function","lang":"kotlin","code":"@Test\n fun `evict removes expired records`() {\n cache.access(\"b\")\n sleep(7.seconds)\n val a0 = cache.access(\"a\")\n val c0 = cache.access(\"c\")\n\n // All elements are in the cache and have up-to-date lastRequestedAt times.\n sleep(1.seconds)\n cache.access(\"a\")\n sleep(1.seconds)\n cache.access(\"b\")\n sleep(1.seconds)\n cache.access(\"c\")\n\n // Evict removes b, which has reached its evictAt time.\n cache.evict(1)\n cache.assertPresent(\"a\", a0)\n cache.assertAbsent(\"b\")\n cache.assertPresent(\"c\", c0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":109,"symbol":"`evict removes all expired records`","kind":"function","lang":"kotlin","code":"@Test\n fun `evict removes all expired records`() {\n cache.access(\"a\")\n cache.access(\"b\")\n cache.access(\"c\")\n sleep(10.seconds)\n\n cache.evict(1)\n cache.assertAbsent(\"a\")\n cache.assertAbsent(\"b\")\n cache.assertAbsent(\"c\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":122,"symbol":"`evict removes least recently used element`","kind":"function","lang":"kotlin","code":"@Test\n fun `evict removes least recently used element`() {\n val a0 = cache.access(\"a\")\n cache.access(\"b\")\n val c0 = cache.access(\"c\")\n\n sleep(1.seconds)\n cache.access(\"b\")\n sleep(1.seconds)\n cache.access(\"a\")\n sleep(1.seconds)\n cache.access(\"c\")\n\n cache.evict(1)\n cache.assertPresent(\"a\", a0)\n cache.assertAbsent(\"b\")\n cache.assertPresent(\"c\", c0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":141,"symbol":"`evict removes expired element and least recently used element`","kind":"function","lang":"kotlin","code":"@Test\n fun `evict removes expired element and least recently used element`() {\n // Make 'd' expired.\n cache.access(\"d\")\n sleep(10.seconds)\n val a0 = cache.access(\"a\")\n cache.access(\"b\")\n val c0 = cache.access(\"c\")\n val e0 = cache.access(\"e\")\n\n // Make 'b' the least recently used.\n sleep(1.seconds)\n cache.access(\"b\")\n sleep(1.seconds)\n cache.access(\"a\")\n sleep(1.seconds)\n cache.access(\"c\")\n sleep(1.seconds)\n cache.access(\"d\")\n sleep(1.seconds)\n cache.access(\"e\")\n\n cache.evict(2)\n cache.assertPresent(\"a\", a0)\n cache.assertAbsent(\"b\") // Least recently used.\n cache.assertPresent(\"c\", c0)\n cache.assertAbsent(\"d\") // Expired.\n cache.assertPresent(\"e\", e0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":175,"symbol":"`automatic eviction when size is double max`","kind":"function","lang":"kotlin","doc":"The test's configured with a max size of 4, so adding the 8th element should automatically resize it to 4 elements.","code":"@Test\n fun `automatic eviction when size is double max`() {\n sleep(1.seconds)\n val a0 = cache.access(\"a\")\n sleep(1.seconds)\n val b0 = cache.access(\"b\")\n sleep(1.seconds)\n val c0 = cache.access(\"c\")\n sleep(1.seconds)\n val d0 = cache.access(\"d\")\n sleep(1.seconds)\n val e0 = cache.access(\"e\")\n sleep(1.seconds)\n val f0 = cache.access(\"f\")\n sleep(1.seconds)\n val g0 = cache.access(\"g\")\n\n // Nothing evicted after 7 inserts.\n cache.assertPresent(\"a\", a0)\n cache.assertPresent(\"b\", b0)\n cache.assertPresent(\"c\", c0)\n cache.assertPresent(\"d\", d0)\n cache.assertPresent(\"e\", e0)\n cache.assertPresent(\"f\", f0)\n cache.assertPresent(\"g\", g0)\n\n // After the 8th insert, it evicts down to size 4.\n sleep(1.seconds)\n val h0 = cache.access(\"h\")\n cache.assertAbsent(\"a\")\n cache.assertAbsent(\"b\")\n cache.assertAbsent(\"c\")\n cache.assertAbsent(\"d\")\n cache.assertPresent(\"e\", e0)\n cache.assertPresent(\"f\", f0)\n cache.assertPresent(\"g\", g0)\n cache.assertPresent(\"h\", h0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":214,"symbol":"Record","kind":"class","lang":"kotlin","code":"class Record(\n val name: String,\n var lastRequestedAt: Time?,\n var evictAt: Time?,\n ) {\n override fun toString() = name\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":219,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = name"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":222,"symbol":"sleep","kind":"function","lang":"kotlin","code":"private fun sleep(duration: Duration) {\n time += duration\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":226,"symbol":"access","kind":"function","lang":"kotlin","code":"fun MemoryCache.access(key: String): Record {\n val now = timeSource.markNow()\n val result = computeIfAbsent(key) { Record(key, now, now + 10.seconds) }\n result.lastRequestedAt = now\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":233,"symbol":"assertAbsent","kind":"function","lang":"kotlin","code":"fun MemoryCache.assertAbsent(key: String) {\n val actual =\n try {\n computeIfAbsent(key) { throw Exception(\"absent!\") }\n } catch (_: Exception) {\n null\n }\n assertThat(actual).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/MemoryCacheTest.kt","line":243,"symbol":"assertPresent","kind":"function","lang":"kotlin","code":"fun MemoryCache.assertPresent(\n key: String,\n expected: Record,\n ) {\n val actual = computeIfAbsent(key) { throw Exception(\"absent!\") }\n assertThat(actual).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":34,"symbol":"StateMachineDnsCallTest","kind":"class","lang":"kotlin","code":"@Burst\nclass StateMachineDnsCallTest {\n /** Arbitrary sample values. */\n private val blueIpv6s = listOf(InetAddress.getByName(\"1:2::3:4\"))\n private val blueIpv4s = listOf(InetAddress.getByName(\"10.20.30.40\"))\n private val greenIpv6s = listOf(InetAddress.getByName(\"5:6::7:8\"))\n private val greenIpv4s = listOf(InetAddress.getByName(\"50.60.70.80\"))\n\n @Test\n fun `happy path`(caching: Boolean = true) {\n testStateMachineDnsCall {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = caching,\n )\n call.enqueue()\n\n val query0 = queryFactory.takeQuery(\"lysine.dev\", TYPE_HTTPS)\n val query1 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val query2 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n query1.respondIpAddresses(\n addresses = blueIpv6s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv6s,\n )\n\n query2.respondIpAddresses(\n addresses = blueIpv4s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv4s,\n )\n\n query0.respondServiceMetadata(\n alpnIds = listOf(\"h2\"),\n )\n call.takeOnRecordsServiceMet"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":42,"symbol":"`happy path`","kind":"function","lang":"kotlin","code":"@Test\n fun `happy path`(caching: Boolean = true) {\n testStateMachineDnsCall {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = caching,\n )\n call.enqueue()\n\n val query0 = queryFactory.takeQuery(\"lysine.dev\", TYPE_HTTPS)\n val query1 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val query2 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n query1.respondIpAddresses(\n addresses = blueIpv6s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv6s,\n )\n\n query2.respondIpAddresses(\n addresses = blueIpv4s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv4s,\n )\n\n query0.respondServiceMetadata(\n alpnIds = listOf(\"h2\"),\n )\n call.takeOnRecordsServiceMetadata(\n last = true,\n alpnIds = listOf(Protocol.HTTP_2),\n )\n\n if (caching) {\n assertThat(cache.size).isEqualTo(3)\n assertThat(cache.requestCount).isEqualTo(3)\n assertThat(cache.networkCount).isEqualTo(3)\n assertThat(cache.hitCount).isEqualTo(0)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":87,"symbol":"`attrleaf is used for nondefault ports`","kind":"function","lang":"kotlin","code":"@Test\n fun `attrleaf is used for nondefault ports`(caching: Boolean = true) {\n testStateMachineDnsCall {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\", port = 8443),\n caching = caching,\n )\n call.enqueue()\n\n val query0 = queryFactory.takeQuery(\"_8443._https.lysine.dev\", TYPE_HTTPS)\n val query1 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val query2 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n query0.respondServiceMetadata(\n alpnIds = listOf(\"h2\"),\n )\n call.takeOnRecordsServiceMetadata(\n alpnIds = listOf(Protocol.HTTP_2),\n )\n\n query1.respondIpAddresses(\n addresses = blueIpv6s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv6s,\n )\n\n query2.respondIpAddresses(\n addresses = blueIpv4s,\n )\n call.takeOnRecordsIpAddresses(\n last = true,\n addresses = blueIpv4s,\n )\n\n if (caching) {\n assertThat(cache.size).isEqualTo(3)\n assertThat(cache.requestCount).isEqualTo(3)\n assertThat(cache.networkCount).isEqualTo(3)\n assertThat(cache.hitCount).isEqualTo(0)\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":132,"symbol":"`caches are independent per hostname`","kind":"function","lang":"kotlin","code":"@Test\n fun `caches are independent per hostname`() {\n testStateMachineDnsCall {\n val lysineCall0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n lysineCall0.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = blueIpv4s,\n )\n assertThat(lysineCall0.takeAllRecords().addresses())\n .isEqualTo(blueIpv4s)\n\n val commonhausCall0 =\n newCall(\n request = Dns.Request(hostname = \"commonhaus.org\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n commonhausCall0.enqueue()\n queryFactory.respondToQuery(\n hostname = \"commonhaus.org\",\n type = TYPE_A,\n addresses = greenIpv4s,\n )\n assertThat(commonhausCall0.takeAllRecords().addresses())\n .isEqualTo(greenIpv4s)\n\n val lysineCall1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":196,"symbol":"`cache already completed values`","kind":"function","lang":"kotlin","code":"@Test\n fun `cache already completed values`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n\n val call0QueryIpv6 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val call0QueryIpv4 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n call0QueryIpv6.respondIpAddresses(\n addresses = blueIpv6s,\n )\n call0QueryIpv4.respondIpAddresses(\n addresses = blueIpv4s,\n )\n assertThat(call0.takeAllRecords().addresses())\n .isEqualTo(blueIpv6s + blueIpv4s)\n\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n assertThat(call1.takeAllRecords().addresses())\n .isEqualTo(blueIpv6s + blueIpv4s)\n\n assertThat(cache.size).isEqualTo(2)\n assertThat(cache.requestCount).isEqualTo(4)\n assertThat(cache.networkCount).isEqualTo(2)\n assertThat(cache.hitCount).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":235,"symbol":"`cache evictAll causes misses`","kind":"function","lang":"kotlin","code":"@Test\n fun `cache evictAll causes misses`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = blueIpv4s,\n )\n assertThat(call0.takeAllRecords().addresses())\n .isEqualTo(blueIpv4s)\n\n cache.evictAll()\n\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = greenIpv4s,\n )\n assertThat(call1.takeAllRecords().addresses())\n .isEqualTo(greenIpv4s)\n\n assertThat(cache.size).isEqualTo(1)\n assertThat(cache.requestCount).isEqualTo(2)\n assertThat(cache.networkCount).isEqualTo(2)\n assertThat(cache.hitCount).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":279,"symbol":"`server time to live is honored`","kind":"function","lang":"kotlin","code":"@Test\n fun `server time to live is honored`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n timeToLive = 30.seconds,\n addresses = blueIpv4s,\n )\n assertThat(call0.takeAllRecords().addresses())\n .isEqualTo(blueIpv4s)\n\n sleep(27.seconds)\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n assertThat(call1.takeAllRecords().addresses())\n .isEqualTo(blueIpv4s)\n\n // The blueIp4s response is expired after 30 seconds.\n sleep(3.seconds)\n val call2 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call2.enqueue()\n query"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":339,"symbol":"`time to live is measured from call send time`","kind":"function","lang":"kotlin","doc":"We compute expiration time from when the request is made, not from when it is received. This is the most conservative policy, but moderated by the minimum time to live configuration.","code":"@Test\n fun `time to live is measured from call send time`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n sleep(30.seconds)\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n timeToLive = 30.seconds,\n addresses = blueIpv4s,\n )\n assertThat(call0.takeAllRecords().addresses())\n .isEqualTo(blueIpv4s)\n\n // The first call's cache is already expired because it took 30 seconds to be returned.\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n timeToLive = 30.seconds,\n addresses = greenIpv4s,\n )\n assertThat(call1.takeAllRecords().addresses())\n .isEqualTo(greenIpv4s)\n\n assertThat(cache.size).isEqualTo(1)\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":384,"symbol":"`server time to live is clamped to at least configured minimum`","kind":"function","lang":"kotlin","code":"@Test\n fun `server time to live is clamped to at least configured minimum`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n timeToLive = 1.seconds,\n addresses = blueIpv4s,\n )\n assertThat(call0.takeAllRecords().addresses())\n .isEqualTo(blueIpv4s)\n\n // The test cache's configured minimum TTL is 10 seconds, so the first response is served.\n sleep(2.seconds)\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n assertThat(call1.takeAllRecords().addresses())\n .isEqualTo(blueIpv4s)\n\n assertThat(cache.size).isEqualTo(1)\n assertThat(cache.requestCount).isEqualTo(2)\n assertThat(cache.networkCount).isEqualTo(1)\n assertThat(cache.hitCount).isEqualTo(1)\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":423,"symbol":"`server time to live is clamped to at most configured maximum`","kind":"function","lang":"kotlin","code":"@Test\n fun `server time to live is clamped to at most configured maximum`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n timeToLive = 100.seconds,\n addresses = blueIpv4s,\n )\n assertThat(call0.takeAllRecords().addresses())\n .isEqualTo(blueIpv4s)\n\n // The test cache's configured maximum TTL is 60 seconds, so the first response is not served.\n sleep(62.seconds)\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeIPv6 = false,\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n timeToLive = 1.seconds,\n addresses = greenIpv4s,\n )\n assertThat(call1.takeAllRecords().addresses())\n .isEqualTo(greenIpv4s)\n\n assertThat(cache"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":469,"symbol":"`cache in flight calls`","kind":"function","lang":"kotlin","doc":"Confirm that two queries to the cache yield a single query to the underlying transport.","code":"@Test\n fun `cache in flight calls`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n\n val call0QueryIpv6 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val call0QueryIpv4 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n\n call0QueryIpv6.respondIpAddresses(\n addresses = blueIpv6s,\n )\n call0.takeOnRecordsIpAddresses(\n addresses = blueIpv6s,\n )\n call1.takeOnRecordsIpAddresses(\n addresses = blueIpv6s,\n )\n\n call0QueryIpv4.respondIpAddresses(\n addresses = blueIpv4s,\n )\n call0.takeOnRecordsIpAddresses(\n last = true,\n addresses = blueIpv4s,\n )\n call1.takeOnRecordsIpAddresses(\n last = true,\n addresses = blueIpv4s,\n )\n\n assertThat(cache.size).isEqualTo(2)\n assertThat(cache.requestCount).isE"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":521,"symbol":"`cache revalidate returns cached result and also makes request`","kind":"function","lang":"kotlin","code":"@Test\n fun `cache revalidate returns cached result and also makes request`() =\n testStateMachineDnsCall {\n // Seed the cache.\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_AAAA,\n timeToLive = 10.seconds,\n addresses = blueIpv6s,\n )\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n timeToLive = 10.seconds,\n addresses = blueIpv4s,\n )\n assertThat(call0.takeAllRecords().addresses())\n .isEqualTo(blueIpv6s + blueIpv4s)\n\n // After 8 seconds, the cached response is returned immediately and a revalidating call is\n // also made. (10 seconds minus 2 seconds for revalidateBeforeExpire.)\n sleep(8.seconds)\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n assertThat(call1.takeAllRecords().addresses())\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":588,"symbol":"`new call joins incomplete revalidate call`","kind":"function","lang":"kotlin","code":"@Test\n fun `new call joins incomplete revalidate call`() =\n testStateMachineDnsCall {\n // Seed the cache.\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeServiceMetadata = false,\n caching = true,\n )\n call0.enqueue()\n\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_AAAA,\n timeToLive = 10.seconds,\n addresses = blueIpv6s,\n )\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n timeToLive = 10.seconds,\n addresses = blueIpv4s,\n )\n assertThat(call0.takeAllRecords().addresses())\n .isEqualTo(blueIpv6s + blueIpv4s)\n\n // After 8 seconds, the cached response is returned immediately and a revalidating call is\n // also made. (10 seconds minus 2 seconds for revalidateBeforeExpire.)\n sleep(8.seconds)\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n includeServiceMetadata = false,\n caching = true,\n )\n call1.enqueue()\n assertThat(call1.takeAllRecords().addresses())\n .isEqualTo(blue"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":667,"symbol":"`failure returned last`","kind":"function","lang":"kotlin","code":"@Test\n fun `failure returned last`(caching: Boolean = true) =\n testStateMachineDnsCall {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = caching,\n )\n call.enqueue()\n\n val query0 = queryFactory.takeQuery(\"lysine.dev\", TYPE_HTTPS)\n val query1 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val query2 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n query1.respondFailure(\"boom!\")\n\n query2.respondIpAddresses(\n addresses = blueIpv4s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv4s,\n )\n\n query0.respondServiceMetadata(\n alpnIds = listOf(\"h2\"),\n )\n call.takeOnRecordsServiceMetadata(\n alpnIds = listOf(Protocol.HTTP_2),\n )\n\n call.takeOnFailure(\"boom!\")\n\n if (caching) {\n assertThat(cache.size).isEqualTo(3)\n assertThat(cache.requestCount).isEqualTo(3)\n assertThat(cache.networkCount).isEqualTo(3)\n assertThat(cache.hitCount).isEqualTo(0)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":707,"symbol":"`partial failure is cached`","kind":"function","lang":"kotlin","code":"@Test\n fun `partial failure is cached`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeServiceMetadata = false,\n )\n call0.enqueue()\n\n val queryIpv6 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val queryIpv4 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n queryIpv6.respondFailure(\"boom!\")\n queryIpv4.respondIpAddresses(\n addresses = blueIpv4s,\n )\n\n call0.takeOnRecordsIpAddresses(\n addresses = blueIpv4s,\n )\n call0.takeOnFailure(\"boom!\")\n\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeServiceMetadata = false,\n )\n call1.enqueue()\n\n call1.takeOnRecordsIpAddresses(\n addresses = blueIpv4s,\n )\n call1.takeOnFailure(\"boom!\")\n\n assertThat(cache.size).isEqualTo(2)\n assertThat(cache.requestCount).isEqualTo(4)\n assertThat(cache.networkCount).isEqualTo(2)\n assertThat(cache.hitCount).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":750,"symbol":"`failure expires`","kind":"function","lang":"kotlin","code":"@Test\n fun `failure expires`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeIPv6 = false,\n includeServiceMetadata = false,\n )\n call0.enqueue()\n queryFactory\n .takeQuery(\"lysine.dev\", TYPE_A)\n .respondFailure(\"boom!\")\n call0.takeOnFailure(\"boom!\")\n\n // The test cache expires failures after 5 seconds.\n sleep(5.seconds)\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeIPv6 = false,\n includeServiceMetadata = false,\n )\n call1.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = greenIpv4s,\n )\n assertThat(call1.takeAllRecords().addresses())\n .isEqualTo(greenIpv4s)\n\n assertThat(cache.size).isEqualTo(1)\n assertThat(cache.requestCount).isEqualTo(2)\n assertThat(cache.networkCount).isEqualTo(2)\n assertThat(cache.hitCount).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":790,"symbol":"`empty result expires on the same schedule as failure`","kind":"function","lang":"kotlin","code":"@Test\n fun `empty result expires on the same schedule as failure`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeIPv6 = false,\n includeServiceMetadata = false,\n )\n call0.enqueue()\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = listOf(),\n )\n call0.takeOnRecordsIpAddresses(\n last = true,\n addresses = listOf(),\n )\n\n // The empty result is still cached.\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeIPv6 = false,\n includeServiceMetadata = false,\n )\n call1.enqueue()\n call1.takeOnRecordsIpAddresses(\n last = true,\n addresses = listOf(),\n )\n\n // The empty result expires after 5 seconds.\n sleep(5.seconds)\n val call2 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeIPv6 = false,\n includeServiceMetadata = false,\n )\n c"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":851,"symbol":"`failure is revalidated`","kind":"function","lang":"kotlin","code":"@Test\n fun `failure is revalidated`() =\n testStateMachineDnsCall {\n val call0 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeIPv6 = false,\n includeServiceMetadata = false,\n )\n call0.enqueue()\n queryFactory\n .takeQuery(\"lysine.dev\", TYPE_A)\n .respondFailure(\"boom!\")\n call0.takeOnFailure(\"boom!\")\n\n // The failure expires after 5 seconds, but we start revalidating it 2 seconds before that.\n sleep(3.seconds)\n val call1 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeIPv6 = false,\n includeServiceMetadata = false,\n )\n call1.enqueue()\n call1.takeOnFailure(\"boom!\")\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = blueIpv4s,\n )\n\n // After the revalidation returns, that result is used.\n val call2 =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n includeIPv6 = false,\n includeServiceMetadata = false,\n )\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":909,"symbol":"`calls to onRecords are serialized`","kind":"function","lang":"kotlin","doc":"Confirm that the state machine calls doesn't call any [Dns.Callback] methods until the previous call to a [Dns.Callback] method has returned. Usually this will be a concurrency problem, but we can exercise it just as well by making a re-entrant call on a single thread.","code":"@Test\n fun `calls to onRecords are serialized`(caching: Boolean = true) =\n testStateMachineDnsCall {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = caching,\n )\n call.enqueue()\n\n val query0 = queryFactory.takeQuery(\"lysine.dev\", TYPE_HTTPS)\n val query1 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val query2 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n onNextEvent = {\n query2.respondIpAddresses(\n addresses = blueIpv4s,\n )\n query1.respondIpAddresses(\n addresses = blueIpv6s,\n )\n }\n query0.respondServiceMetadata(\n alpnIds = listOf(\"h2\"),\n )\n call.takeOnRecordsServiceMetadata(\n alpnIds = listOf(Protocol.HTTP_2),\n )\n call.takeOnRecordsIpAddresses(\n last = true,\n addresses =\n listOf(\n InetAddress.getByName(\"10.20.30.40\"),\n InetAddress.getByName(\"1:2::3:4\"),\n ),\n )\n\n if (caching) {\n assertThat(cache.size).isEqualTo(3)\n assertThat(cache.requestCount).isEqualTo(3)\n assertThat(cache.networkCount).isEqualTo(3)\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":954,"symbol":"`cancel before enqueue`","kind":"function","lang":"kotlin","code":"@Test\n fun `cancel before enqueue`(caching: Boolean) =\n testStateMachineDnsCall {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = caching,\n )\n call.cancel()\n call.enqueue()\n\n call.takeOnFailure(\"canceled\")\n\n assertThat(cache.size).isEqualTo(0)\n assertThat(cache.requestCount).isEqualTo(0)\n assertThat(cache.networkCount).isEqualTo(0)\n assertThat(cache.hitCount).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":974,"symbol":"`cancel ignored if canceled query completes`","kind":"function","lang":"kotlin","doc":"Cancels are asynchronous and if the canceled query completes anyway, that's fine.","code":"@Test\n fun `cancel ignored if canceled query completes`() =\n testStateMachineDnsCall {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = false,\n )\n call.enqueue()\n\n val query0 = queryFactory.takeQuery(\"lysine.dev\", TYPE_HTTPS)\n val query1 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val query2 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n query1.respondIpAddresses(\n addresses = blueIpv6s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv6s,\n )\n\n call.cancel()\n\n queryFactory.takeCancel(\"lysine.dev\", TYPE_HTTPS)\n queryFactory.takeCancel(\"lysine.dev\", TYPE_A)\n\n query2.respondIpAddresses(\n addresses = blueIpv4s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv4s,\n )\n\n query0.respondServiceMetadata(\n alpnIds = listOf(\"h2\"),\n )\n call.takeOnRecordsServiceMetadata(\n last = true,\n alpnIds = listOf(Protocol.HTTP_2),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":1017,"symbol":"`cancel ignored if canceled query completes with caching`","kind":"function","lang":"kotlin","doc":"When caching, cancels aren't applied to the transport.","code":"@Test\n fun `cancel ignored if canceled query completes with caching`() =\n testStateMachineDnsCall {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = true,\n )\n call.enqueue()\n\n val query0 = queryFactory.takeQuery(\"lysine.dev\", TYPE_HTTPS)\n val query1 = queryFactory.takeQuery(\"lysine.dev\", TYPE_AAAA)\n val query2 = queryFactory.takeQuery(\"lysine.dev\", TYPE_A)\n\n query1.respondIpAddresses(\n addresses = blueIpv6s,\n )\n call.takeOnRecordsIpAddresses(\n addresses = blueIpv6s,\n )\n\n call.cancel()\n\n query2.respondIpAddresses(\n addresses = blueIpv4s,\n )\n\n query0.respondServiceMetadata(\n alpnIds = listOf(\"h2\"),\n )\n call.takeOnFailure(\"canceled\")\n\n assertThat(cache.size).isEqualTo(3)\n assertThat(cache.requestCount).isEqualTo(3)\n assertThat(cache.networkCount).isEqualTo(3)\n assertThat(cache.hitCount).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":1055,"symbol":"`alias mode records are ignored`","kind":"function","lang":"kotlin","code":"@Test\n fun `alias mode records are ignored`() =\n testStateMachineDnsCall {\n val call = newCall(request = Dns.Request(hostname = \"lysine.dev\"))\n call.enqueue()\n\n // Priority 0 means 'AliasMode'. We must ignore all SvcParams in AliasMode.\n val query0 = queryFactory.takeQuery(\"lysine.dev\", TYPE_HTTPS)\n query0.respond(\n ResourceRecord.Https(\n timeToLive = 300,\n name = \"lysine.dev\",\n priority = 0,\n alpnIds = listOf(\"h2\"),\n ),\n )\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_AAAA,\n addresses = blueIpv6s,\n )\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = blueIpv4s,\n )\n\n call.takeOnRecordsIpAddresses(\n last = false,\n addresses = blueIpv6s,\n )\n call.takeOnRecordsIpAddresses(\n last = true,\n addresses = blueIpv4s,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":1092,"symbol":"`service mode records are ignored if any alias mode record is present`","kind":"function","lang":"kotlin","code":"@Test\n fun `service mode records are ignored if any alias mode record is present`() =\n testStateMachineDnsCall {\n val call = newCall(request = Dns.Request(hostname = \"lysine.dev\"))\n call.enqueue()\n\n // Priority 0 means 'AliasMode'. We must ignore all SvcParams in AliasMode.\n val query0 = queryFactory.takeQuery(\"lysine.dev\", TYPE_HTTPS)\n query0.respond(\n ResourceRecord.Https(\n timeToLive = 300,\n name = \"lysine.dev\",\n priority = 0,\n ),\n ResourceRecord.Https(\n timeToLive = 300,\n name = \"lysine.dev\",\n priority = 1,\n alpnIds = listOf(\"h2\"),\n ),\n )\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_AAAA,\n addresses = blueIpv6s,\n )\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = blueIpv4s,\n )\n\n call.takeOnRecordsIpAddresses(\n last = false,\n addresses = blueIpv6s,\n )\n call.takeOnRecordsIpAddresses(\n last = true,\n addresses = blueIpv4s,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":1134,"symbol":"`service mode records are sorted by priority`","kind":"function","lang":"kotlin","code":"@Test\n fun `service mode records are sorted by priority`(caching: Boolean = true) =\n testStateMachineDnsCall {\n val processedRecords =\n serveAndProcessResourceRecords(\n caching = caching,\n attempt = 0,\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 300.seconds.inWholeSeconds.toInt(),\n priority = 3,\n echConfigList = \"priority three ECH config list\".encodeUtf8(),\n ),\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 300.seconds.inWholeSeconds.toInt(),\n priority = 1,\n echConfigList = \"priority one ECH config list\".encodeUtf8(),\n ),\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 300.seconds.inWholeSeconds.toInt(),\n priority = 2,\n echConfigList = \"priority two ECH config list\".encodeUtf8(),\n ),\n )\n\n val sortedEchConfigLists =\n processedRecords\n .map { it.echConfigList }\n assertThat(sortedEchConfigLists).containsExactly(\n \"priority one ECH config list\".encodeUtf8(),\n \"priority two ECH config l"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":1175,"symbol":"`service mode records are shuffled within each priority`","kind":"function","lang":"kotlin","doc":"We've got 8 lists, each containing 3 elements. If we shuffle each list we should expect all the lists to be the same once in every ~280,000 runs. (So this test is flaky, but acceptably so.)","code":"@Test\n fun `service mode records are shuffled within each priority`(caching: Boolean = true) =\n testStateMachineDnsCall {\n val attemptCount = 8\n val distinctOrderings = mutableSetOf>()\n for (i in 0 until attemptCount) {\n val processedRecords =\n serveAndProcessResourceRecords(\n caching,\n attempt = i,\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 300.seconds.inWholeSeconds.toInt(),\n echConfigList = \"element A ECH config list\".encodeUtf8(),\n ),\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 300.seconds.inWholeSeconds.toInt(),\n echConfigList = \"element B ECH config list\".encodeUtf8(),\n ),\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 300.seconds.inWholeSeconds.toInt(),\n echConfigList = \"element C ECH config list\".encodeUtf8(),\n ),\n )\n\n distinctOrderings += processedRecords\n }\n\n assertThat(distinctOrderings).size().isGreaterThan(1)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTest.kt","line":1212,"symbol":"serveAndProcessResourceRecords","kind":"function","lang":"kotlin","doc":"Use the state machine to transform server-provided [resourceRecords] to the user-facing [Dns.Record] instances.","code":"private fun StateMachineDnsCallTester.serveAndProcessResourceRecords(\n caching: Boolean,\n attempt: Int,\n vararg resourceRecords: ResourceRecord.Https,\n ): List {\n val call =\n newCall(\n request = Dns.Request(hostname = \"lysine.dev\"),\n caching = caching,\n includeIPv6 = false,\n )\n call.enqueue()\n\n if (attempt == 0 || !caching) {\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_HTTPS,\n *resourceRecords,\n )\n queryFactory.respondToQuery(\n hostname = \"lysine.dev\",\n type = TYPE_A,\n addresses = blueIpv4s,\n )\n }\n\n return call\n .takeAllRecords()\n .filterIsInstance()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":33,"symbol":"testStateMachineDnsCall","kind":"function","lang":"kotlin","doc":"This has helpers to operate on the state machine: This tracks all effects from the state machine as events: creating queries, canceling queries, calling callbacks.","code":"fun testStateMachineDnsCall(block: StateMachineDnsCallTester.() -> Unit) {\n val tester = StateMachineDnsCallTester()\n tester.block()\n assertThat(tester.queryFactory.events.poll(), \"unexpected transport event\").isNull()\n}"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":39,"symbol":"StateMachineDnsCallTester","kind":"class","lang":"kotlin","code":"class StateMachineDnsCallTester internal constructor() {\n var onNextEvent: (() -> Unit)? = null\n\n /** Defend against re-entrant calls. */\n private var acceptCallbacks: Boolean = true\n\n private val taskFaker = TaskFaker()\n\n val cache =\n RealDnsCache(\n taskRunner = taskFaker.taskRunner,\n timeSource = taskFaker.timeSource,\n minimumTimeToLive = 10.seconds,\n maximumTimeToLive = 60.seconds,\n failureTimeToLive = 5.seconds,\n revalidateBeforeExpire = 2.seconds,\n maxEntryCount = 4,\n )\n\n val queryFactory = QueryFactory()\n\n fun newCall(\n request: Dns.Request,\n includeIPv6: Boolean = true,\n includeServiceMetadata: Boolean = true,\n caching: Boolean = false,\n ) = CallTester(\n request = request,\n includeIPv6 = includeIPv6,\n includeServiceMetadata = includeServiceMetadata,\n caching = caching,\n )\n\n fun sleep(duration: Duration) {\n taskFaker.advanceUntil(taskFaker.nanoTime + duration.inWholeNanoseconds)\n }\n\n /** Scriptable query factory for testing. */\n inner class QueryFactory : DnsQuery.Factory {\n val events = LinkedBlockingDeque()\n\n override fun newQuery(question: Question): DnsQuery =\n obje"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":60,"symbol":"newCall","kind":"function","lang":"kotlin","code":"fun newCall(\n request: Dns.Request,\n includeIPv6: Boolean = true,\n includeServiceMetadata: Boolean = true,\n caching: Boolean = false,\n ) = CallTester(\n request = request,\n includeIPv6 = includeIPv6,\n includeServiceMetadata = includeServiceMetadata,\n caching = caching,\n )"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":72,"symbol":"sleep","kind":"function","lang":"kotlin","code":"fun sleep(duration: Duration) {\n taskFaker.advanceUntil(taskFaker.nanoTime + duration.inWholeNanoseconds)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":77,"symbol":"QueryFactory","kind":"class","lang":"kotlin","doc":"Scriptable query factory for testing.","code":"inner class QueryFactory : DnsQuery.Factory {\n val events = LinkedBlockingDeque()\n\n override fun newQuery(question: Question): DnsQuery =\n object : DnsQuery {\n override fun enqueue(callback: DnsQuery.Callback) {\n postEvent(QueryEnqueued(question, callback))\n }\n\n override fun cancel() {\n postEvent(QueryCanceled(question))\n }\n }\n\n private fun postEvent(e: TransportEvent) {\n events.put(e)\n\n onNextEvent?.invoke()\n onNextEvent = null\n }\n\n private fun takeEvent(): TransportEvent {\n taskFaker.runTasks() // Run any queued async work first.\n return events.take()\n }\n\n /** Asserts that the next-posted event is a query enqueue. */\n fun takeQuery(\n hostname: String,\n type: Int,\n ): QueryEnqueued {\n val event = queryFactory.takeEvent() as QueryEnqueued\n assertThat(event.hostname).isEqualTo(hostname)\n assertThat(event.type).isEqualTo(type)\n return event\n }\n\n /** Combines [takeQuery] and [QueryEnqueued.respondIpAddresses]. */\n fun respondToQuery(\n hostname: String,\n type: Int,\n timeToLive: Duration = 300.seconds,\n add"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":80,"symbol":"newQuery","kind":"function","lang":"kotlin","code":"override fun newQuery(question: Question): DnsQuery =\n object : DnsQuery {\n override fun enqueue(callback: DnsQuery.Callback) {\n postEvent(QueryEnqueued(question, callback))\n }\n\n override fun cancel() {\n postEvent(QueryCanceled(question))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":82,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(callback: DnsQuery.Callback) {\n postEvent(QueryEnqueued(question, callback))\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":86,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n postEvent(QueryCanceled(question))\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":91,"symbol":"postEvent","kind":"function","lang":"kotlin","code":"private fun postEvent(e: TransportEvent) {\n events.put(e)\n\n onNextEvent?.invoke()\n onNextEvent = null\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":98,"symbol":"takeEvent","kind":"function","lang":"kotlin","code":"private fun takeEvent(): TransportEvent {\n taskFaker.runTasks() // Run any queued async work first.\n return events.take()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":104,"symbol":"takeQuery","kind":"function","lang":"kotlin","doc":"Asserts that the next-posted event is a query enqueue.","code":"fun takeQuery(\n hostname: String,\n type: Int,\n ): QueryEnqueued {\n val event = queryFactory.takeEvent() as QueryEnqueued\n assertThat(event.hostname).isEqualTo(hostname)\n assertThat(event.type).isEqualTo(type)\n return event\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":115,"symbol":"respondToQuery","kind":"function","lang":"kotlin","doc":"Combines [takeQuery] and [QueryEnqueued.respondIpAddresses].","code":"fun respondToQuery(\n hostname: String,\n type: Int,\n timeToLive: Duration = 300.seconds,\n addresses: List = listOf(),\n ): QueryEnqueued {\n val event = takeQuery(hostname, type)\n event.respondIpAddresses(timeToLive, addresses)\n return event\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":127,"symbol":"respondToQuery","kind":"function","lang":"kotlin","doc":"Combines [takeQuery] and [QueryEnqueued.respond].","code":"fun respondToQuery(\n hostname: String,\n type: Int,\n vararg resourceRecords: ResourceRecord,\n ): QueryEnqueued {\n val event = takeQuery(hostname, type)\n event.respond(*resourceRecords)\n return event\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":138,"symbol":"takeCancel","kind":"function","lang":"kotlin","doc":"Asserts that the next-posted event is a query cancel.","code":"fun takeCancel(\n hostname: String,\n type: Int,\n ): QueryCanceled {\n val event = queryFactory.takeEvent() as QueryCanceled\n assertThat(event.hostname).isEqualTo(hostname)\n assertThat(event.type).isEqualTo(type)\n return event\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":150,"symbol":"CallTester","kind":"class","lang":"kotlin","doc":"A DNS call for the fake state machine.","code":"inner class CallTester(\n request: Dns.Request,\n includeIPv6: Boolean = true,\n includeServiceMetadata: Boolean = true,\n caching: Boolean = false,\n ) : Dns.Callback {\n private val events = LinkedBlockingDeque()\n\n val call =\n StateMachineDnsCall(\n taskRunner = taskFaker.taskRunner,\n request = request,\n queryFactory =\n when {\n caching -> cache.wrap(queryFactory)\n else -> queryFactory\n },\n includeIPv6 = includeIPv6,\n includeServiceMetadata = includeServiceMetadata,\n )\n\n fun enqueue() {\n check(acceptCallbacks) { \"unexpected enqueue\" }\n acceptCallbacks = false\n try {\n enqueue(this)\n } finally {\n acceptCallbacks = true\n }\n }\n\n fun enqueue(callback: Dns.Callback) {\n call.enqueue(callback)\n }\n\n fun cancel() {\n call.cancel()\n }\n\n private fun postEvent(e: CallEvent) {\n events.put(e)\n\n onNextEvent?.invoke()\n onNextEvent = null\n }\n\n private fun takeEvent(): CallEvent {\n taskFaker.runTasks() // Run any queued async work first.\n return events.take()\n }\n\n override fun onRecords(\n "} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":171,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"fun enqueue() {\n check(acceptCallbacks) { \"unexpected enqueue\" }\n acceptCallbacks = false\n try {\n enqueue(this)\n } finally {\n acceptCallbacks = true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":181,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"fun enqueue(callback: Dns.Callback) {\n call.enqueue(callback)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":185,"symbol":"cancel","kind":"function","lang":"kotlin","code":"fun cancel() {\n call.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":189,"symbol":"postEvent","kind":"function","lang":"kotlin","code":"private fun postEvent(e: CallEvent) {\n events.put(e)\n\n onNextEvent?.invoke()\n onNextEvent = null\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":196,"symbol":"takeEvent","kind":"function","lang":"kotlin","code":"private fun takeEvent(): CallEvent {\n taskFaker.runTasks() // Run any queued async work first.\n return events.take()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":201,"symbol":"onRecords","kind":"function","lang":"kotlin","code":"override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n check(call == this.call)\n check(acceptCallbacks) { \"unexpected callback\" }\n\n acceptCallbacks = false\n try {\n postEvent(OnRecords(last, records))\n } finally {\n acceptCallbacks = true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":217,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Dns.Call,\n e: IOException,\n ) {\n check(call == this.call)\n check(acceptCallbacks) { \"unexpected callback\" }\n\n acceptCallbacks = false\n try {\n postEvent(OnFailure(e))\n } finally {\n acceptCallbacks = true\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":236,"symbol":"takeOnRecordsIpAddresses","kind":"function","lang":"kotlin","doc":"Asserts that the next-posted event is a call to [Dns.Callback.onRecords] with a list of IP addresses.","code":"fun takeOnRecordsIpAddresses(\n last: Boolean = false,\n addresses: List,\n ): OnRecords {\n val event = takeEvent() as OnRecords\n assertThat(event.last).isEqualTo(last)\n assertThat(event.records.map { (it as Dns.Record.IpAddress).address })\n .isEqualTo(addresses)\n return event\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":250,"symbol":"takeOnRecordsServiceMetadata","kind":"function","lang":"kotlin","doc":"Asserts that the next-posted event is a call to [Dns.Callback.onRecords] with service metadata.","code":"fun takeOnRecordsServiceMetadata(\n last: Boolean = false,\n alpnIds: List? = null,\n echConfigList: ByteString? = null,\n ): OnRecords {\n val event = takeEvent() as OnRecords\n assertThat(event.last).isEqualTo(last)\n\n val serviceMetadata = event.records.single() as Dns.Record.ServiceMetadata\n assertThat(serviceMetadata.alpnIds).isEqualTo(alpnIds)\n assertThat(serviceMetadata.echConfigList).isEqualTo(echConfigList)\n return event\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":264,"symbol":"takeAllRecords","kind":"function","lang":"kotlin","code":"fun takeAllRecords(): List =\n buildList {\n do {\n val event = takeEvent() as OnRecords\n addAll(event.records)\n } while (!event.last)\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":273,"symbol":"takeOnFailure","kind":"function","lang":"kotlin","doc":"Asserts that the next-posted event is a call to [Dns.Callback.onFailure].","code":"fun takeOnFailure(message: String): OnFailure {\n val event = takeEvent() as OnFailure\n assertThat(event.e).hasMessage(message)\n return event\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":280,"symbol":"TransportEvent","kind":"interface","lang":"kotlin","code":"sealed interface TransportEvent {\n class QueryEnqueued(\n val question: Question,\n val callback: DnsQuery.Callback,\n ) : TransportEvent {\n val hostname: String\n get() = question.name\n val type: Int\n get() = question.type\n\n /** Respond to a [TYPE_HTTPS] query with service metadata. */\n fun respondServiceMetadata(\n timeToLive: Duration = 300.seconds,\n alpnIds: List? = null,\n echConfigList: ByteString? = null,\n ) {\n respond(\n ResourceRecord.Https(\n name = question.name,\n timeToLive = timeToLive.inWholeSeconds.toInt(),\n alpnIds = alpnIds,\n echConfigList = echConfigList,\n ),\n )\n }\n\n /** Respond to any query with a failure. */\n fun respondFailure(message: String) {\n callback.onFailure(IOException(message))\n }\n\n /** Respond to a [TYPE_A] or [TYPE_AAAA] query with a (possibly-empty) list of IP addresses. */\n fun respondIpAddresses(\n timeToLive: Duration = 300.seconds,\n addresses: List = listOf(),\n ) {\n val resourceRecords =\n addresses.map { address -"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":281,"symbol":"QueryEnqueued","kind":"class","lang":"kotlin","code":"class QueryEnqueued(\n val question: Question,\n val callback: DnsQuery.Callback,\n ) : TransportEvent {\n val hostname: String\n get() = question.name\n val type: Int\n get() = question.type\n\n /** Respond to a [TYPE_HTTPS] query with service metadata. */\n fun respondServiceMetadata(\n timeToLive: Duration = 300.seconds,\n alpnIds: List? = null,\n echConfigList: ByteString? = null,\n ) {\n respond(\n ResourceRecord.Https(\n name = question.name,\n timeToLive = timeToLive.inWholeSeconds.toInt(),\n alpnIds = alpnIds,\n echConfigList = echConfigList,\n ),\n )\n }\n\n /** Respond to any query with a failure. */\n fun respondFailure(message: String) {\n callback.onFailure(IOException(message))\n }\n\n /** Respond to a [TYPE_A] or [TYPE_AAAA] query with a (possibly-empty) list of IP addresses. */\n fun respondIpAddresses(\n timeToLive: Duration = 300.seconds,\n addresses: List = listOf(),\n ) {\n val resourceRecords =\n addresses.map { address ->\n ResourceRecord.IpAddress"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":291,"symbol":"respondServiceMetadata","kind":"function","lang":"kotlin","doc":"Respond to a [TYPE_HTTPS] query with service metadata.","code":"fun respondServiceMetadata(\n timeToLive: Duration = 300.seconds,\n alpnIds: List? = null,\n echConfigList: ByteString? = null,\n ) {\n respond(\n ResourceRecord.Https(\n name = question.name,\n timeToLive = timeToLive.inWholeSeconds.toInt(),\n alpnIds = alpnIds,\n echConfigList = echConfigList,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":307,"symbol":"respondFailure","kind":"function","lang":"kotlin","doc":"Respond to any query with a failure.","code":"fun respondFailure(message: String) {\n callback.onFailure(IOException(message))\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":312,"symbol":"respondIpAddresses","kind":"function","lang":"kotlin","doc":"Respond to a [TYPE_A] or [TYPE_AAAA] query with a (possibly-empty) list of IP addresses.","code":"fun respondIpAddresses(\n timeToLive: Duration = 300.seconds,\n addresses: List = listOf(),\n ) {\n val resourceRecords =\n addresses.map { address ->\n ResourceRecord.IpAddress(\n name = question.name,\n timeToLive = timeToLive.inWholeSeconds.toInt(),\n address = address,\n )\n }\n respond(*resourceRecords.toTypedArray())\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":327,"symbol":"respond","kind":"function","lang":"kotlin","code":"fun respond(vararg resourceRecords: ResourceRecord) {\n callback.onResponse(\n DnsMessage.response(\n questions = listOf(question),\n answers = resourceRecords.toList(),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":337,"symbol":"QueryCanceled","kind":"class","lang":"kotlin","code":"class QueryCanceled(\n val question: Question,\n ) : TransportEvent {\n val hostname: String\n get() = question.name\n val type: Int\n get() = question.type\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":347,"symbol":"CallEvent","kind":"interface","lang":"kotlin","code":"sealed interface CallEvent {\n class OnRecords(\n val last: Boolean,\n val records: List,\n ) : CallEvent\n\n class OnFailure(\n val e: IOException,\n ) : CallEvent\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/dns/StateMachineDnsCallTester.kt","line":359,"symbol":"addresses","kind":"function","lang":"kotlin","code":"fun List.addresses(): List = map { (it as Dns.Record.IpAddress).address }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/ConfiguredPublicSuffixDatabaseTest.kt","line":24,"symbol":"ConfiguredPublicSuffixDatabaseTest","kind":"class","lang":"kotlin","code":"class ConfiguredPublicSuffixDatabaseTest {\n private val list = ConfiguredPublicSuffixList()\n private val publicSuffixDatabase = PublicSuffixDatabase(list)\n\n @Test fun longestMatchWins() {\n list.bytes =\n Buffer()\n .writeUtf8(\"com\\n\")\n .writeUtf8(\"my.square.com\\n\")\n .writeUtf8(\"square.com\\n\")\n .readByteString()\n\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"example.com\"))\n .isEqualTo(\"example.com\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.example.com\"))\n .isEqualTo(\"example.com\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.bar.square.com\"))\n .isEqualTo(\"bar.square.com\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.my.square.com\"))\n .isEqualTo(\"foo.my.square.com\")\n }\n\n @Test fun wildcardMatch() {\n list.bytes =\n Buffer()\n .writeUtf8(\"*.square.com\\n\")\n .writeUtf8(\"com\\n\")\n .writeUtf8(\"example.com\\n\")\n .readByteString()\n\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"my.square.com\")).isNull()\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.my.square.com\"))\n .isEqualTo(\"foo.my.square.c"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/ConfiguredPublicSuffixDatabaseTest.kt","line":28,"symbol":"longestMatchWins","kind":"function","lang":"kotlin","code":"@Test fun longestMatchWins() {\n list.bytes =\n Buffer()\n .writeUtf8(\"com\\n\")\n .writeUtf8(\"my.square.com\\n\")\n .writeUtf8(\"square.com\\n\")\n .readByteString()\n\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"example.com\"))\n .isEqualTo(\"example.com\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.example.com\"))\n .isEqualTo(\"example.com\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.bar.square.com\"))\n .isEqualTo(\"bar.square.com\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.my.square.com\"))\n .isEqualTo(\"foo.my.square.com\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/ConfiguredPublicSuffixDatabaseTest.kt","line":46,"symbol":"wildcardMatch","kind":"function","lang":"kotlin","code":"@Test fun wildcardMatch() {\n list.bytes =\n Buffer()\n .writeUtf8(\"*.square.com\\n\")\n .writeUtf8(\"com\\n\")\n .writeUtf8(\"example.com\\n\")\n .readByteString()\n\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"my.square.com\")).isNull()\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.my.square.com\"))\n .isEqualTo(\"foo.my.square.com\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"bar.foo.my.square.com\"))\n .isEqualTo(\"foo.my.square.com\")\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/ConfiguredPublicSuffixDatabaseTest.kt","line":61,"symbol":"boundarySearches","kind":"function","lang":"kotlin","code":"@Test fun boundarySearches() {\n list.bytes =\n Buffer()\n .writeUtf8(\"bbb\\n\")\n .writeUtf8(\"ddd\\n\")\n .writeUtf8(\"fff\\n\")\n .readByteString()\n\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"aaa\")).isNull()\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"ggg\")).isNull()\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"ccc\")).isNull()\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"eee\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/ConfiguredPublicSuffixDatabaseTest.kt","line":75,"symbol":"exceptionRule","kind":"function","lang":"kotlin","code":"@Test fun exceptionRule() {\n list.bytes =\n Buffer()\n .writeUtf8(\"*.jp\\n\")\n .writeUtf8(\"*.square.jp\\n\")\n .writeUtf8(\"example.com\\n\")\n .writeUtf8(\"square.com\\n\")\n .readByteString()\n list.exceptionBytes =\n Buffer()\n .writeUtf8(\"my.square.jp\\n\")\n .readByteString()\n\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"my.square.jp\"))\n .isEqualTo(\"my.square.jp\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.my.square.jp\"))\n .isEqualTo(\"my.square.jp\")\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"my1.square.jp\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/ConfiguredPublicSuffixDatabaseTest.kt","line":95,"symbol":"noEffectiveTldPlusOne","kind":"function","lang":"kotlin","code":"@Test fun noEffectiveTldPlusOne() {\n list.bytes =\n Buffer()\n .writeUtf8(\"*.jp\\n\")\n .writeUtf8(\"*.square.jp\\n\")\n .writeUtf8(\"example.com\\n\")\n .writeUtf8(\"square.com\\n\")\n .readByteString()\n list.exceptionBytes =\n Buffer()\n .writeUtf8(\"my.square.jp\\n\")\n .readByteString()\n\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"example.com\")).isNull()\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(\"foo.square.jp\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/ConfiguredPublicSuffixList.kt","line":23,"symbol":"ConfiguredPublicSuffixList","kind":"class","lang":"kotlin","doc":"An implementation of I/O for `PublicSuffixDatabase` by directly passing in ByteStrings.","code":"internal class ConfiguredPublicSuffixList : PublicSuffixList {\n override fun ensureLoaded() {\n }\n\n override var bytes: ByteString = ByteString.EMPTY\n\n override var exceptionBytes: ByteString = ByteString.EMPTY\n}"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/ConfiguredPublicSuffixList.kt","line":24,"symbol":"ensureLoaded","kind":"function","lang":"kotlin","code":"override fun ensureLoaded() {\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt","line":34,"symbol":"PublicSuffixDatabaseTest","kind":"class","lang":"kotlin","code":"@RunWith(PublicSuffixTestRunner::class)\nclass PublicSuffixDatabaseTest {\n private val publicSuffixDatabase = PublicSuffixDatabase.get()\n\n val pathForTests = okHttpRoot / \"okhttp/src/jvmMain/resources\" / PUBLIC_SUFFIX_RESOURCE\n\n @Before\n fun setUp() {\n beforePublicSuffixTest()\n }\n\n @Test\n fun allPublicSuffixes() {\n val buffer = Buffer()\n FileSystem.SYSTEM.read(pathForTests) {\n val length = readInt()\n buffer.write(this, length.toLong())\n }\n while (!buffer.exhausted()) {\n var publicSuffix = buffer.readUtf8LineStrict()\n if (publicSuffix.contains(\"*\")) {\n // A wildcard rule, let's replace the wildcard with a value.\n publicSuffix = publicSuffix.replace(\"\\\\*\".toRegex(), \"square\")\n }\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(publicSuffix)).isNull()\n val test = \"foobar.$publicSuffix\"\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(test)).isEqualTo(test)\n }\n }\n\n @Test\n fun publicSuffixExceptions() {\n val buffer = Buffer()\n FileSystem.SYSTEM.read(pathForTests) {\n var length = readInt()\n skip(length.toLong())\n length = readInt()\n buffer.write(this, length.toLong())\n"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt","line":40,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@Before\n fun setUp() {\n beforePublicSuffixTest()\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt","line":45,"symbol":"allPublicSuffixes","kind":"function","lang":"kotlin","code":"@Test\n fun allPublicSuffixes() {\n val buffer = Buffer()\n FileSystem.SYSTEM.read(pathForTests) {\n val length = readInt()\n buffer.write(this, length.toLong())\n }\n while (!buffer.exhausted()) {\n var publicSuffix = buffer.readUtf8LineStrict()\n if (publicSuffix.contains(\"*\")) {\n // A wildcard rule, let's replace the wildcard with a value.\n publicSuffix = publicSuffix.replace(\"\\\\*\".toRegex(), \"square\")\n }\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(publicSuffix)).isNull()\n val test = \"foobar.$publicSuffix\"\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(test)).isEqualTo(test)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt","line":64,"symbol":"publicSuffixExceptions","kind":"function","lang":"kotlin","code":"@Test\n fun publicSuffixExceptions() {\n val buffer = Buffer()\n FileSystem.SYSTEM.read(pathForTests) {\n var length = readInt()\n skip(length.toLong())\n length = readInt()\n buffer.write(this, length.toLong())\n }\n while (!buffer.exhausted()) {\n val exception = buffer.readUtf8LineStrict()\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(exception)).isEqualTo(\n exception,\n )\n val test = \"foobar.$exception\"\n assertThat(publicSuffixDatabase.getEffectiveTldPlusOne(test)).isEqualTo(exception)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt","line":83,"symbol":"threadIsInterruptedOnFirstRead","kind":"function","lang":"kotlin","code":"@Test\n fun threadIsInterruptedOnFirstRead() {\n Thread.currentThread().interrupt()\n try {\n val result = publicSuffixDatabase.getEffectiveTldPlusOne(\"squareup.com\")\n assertThat(result).isEqualTo(\"squareup.com\")\n } finally {\n assertThat(Thread.interrupted()).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt","line":94,"symbol":"secondReadFailsSameAsFirst","kind":"function","lang":"kotlin","code":"@Test\n fun secondReadFailsSameAsFirst() {\n val badPublicSuffixDatabase =\n PublicSuffixDatabase(\n ResourcePublicSuffixList(\n path = \"/xxx.gz\".toPath(),\n ),\n )\n lateinit var firstFailure: Exception\n assertFailsWith {\n badPublicSuffixDatabase.getEffectiveTldPlusOne(\"squareup.com\")\n }.also { e ->\n firstFailure = e\n }\n assertFailsWith {\n badPublicSuffixDatabase.getEffectiveTldPlusOne(\"squareup.com\")\n }.also { e ->\n assertEquals(firstFailure.toString(), e.toString())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt","line":116,"symbol":"publicSuffixDotOrgTestCases","kind":"function","lang":"kotlin","doc":"These tests are provided by [publicsuffix.org](https://publicsuffix.org/list/).","code":"@Test\n fun publicSuffixDotOrgTestCases() {\n // Any copyright is dedicated to the Public Domain.\n // https://creativecommons.org/publicdomain/zero/1.0/\n\n // Mixed case.\n checkPublicSuffix(\"COM\", null)\n checkPublicSuffix(\"example.COM\", \"example.com\")\n checkPublicSuffix(\"WwW.example.COM\", \"example.com\")\n // Leading dot.\n checkPublicSuffix(\".com\", null)\n checkPublicSuffix(\".example\", null)\n checkPublicSuffix(\".example.com\", null)\n checkPublicSuffix(\".example.example\", null)\n // Unlisted TLD.\n checkPublicSuffix(\"example\", null)\n checkPublicSuffix(\"example.example\", \"example.example\")\n checkPublicSuffix(\"b.example.example\", \"example.example\")\n checkPublicSuffix(\"a.b.example.example\", \"example.example\")\n // Listed, but non-Internet, TLD.\n // checkPublicSuffix(\"local\", null);\n // checkPublicSuffix(\"example.local\", null);\n // checkPublicSuffix(\"b.example.local\", null);\n // checkPublicSuffix(\"a.b.example.local\", null);\n // TLD with only 1 rule.\n checkPublicSuffix(\"biz\", null)\n checkPublicSuffix(\"domain.biz\", \"domain.biz\")\n checkPublicSuffix(\"b.domain.biz\", \"domain.biz\")\n checkPublicSuffix(\"a.b.domain.biz\", \"domain"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabaseTest.kt","line":216,"symbol":"checkPublicSuffix","kind":"function","lang":"kotlin","code":"private fun checkPublicSuffix(\n domain: String,\n registrablePart: String?,\n ) {\n val canonicalDomain = domain.toCanonicalHost() ?: return\n val result = publicSuffixDatabase.getEffectiveTldPlusOne(canonicalDomain)\n if (registrablePart == null) {\n assertThat(result).isNull()\n } else {\n assertThat(result).isEqualTo(registrablePart.toCanonicalHost())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/commonTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixTesting.kt","line":22,"symbol":"beforePublicSuffixTest","kind":"function","lang":"kotlin","code":"expect fun beforePublicSuffixTest()"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/OkHttp.jvm.kt","line":20,"symbol":"OkHttp","kind":"object","lang":"kotlin","code":"actual object OkHttp {\n @JvmField\n actual val VERSION: String = CONST_VERSION\n}"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/graal/GraalSvm.kt","line":44,"symbol":"TargetPlatform","kind":"class","lang":"kotlin","code":"@TargetClass(Platform.Companion::class)\nclass TargetPlatform {\n @Substitute\n fun findPlatform(): Platform = Jdk9Platform.buildIfSupported()!!\n}"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/graal/GraalSvm.kt","line":46,"symbol":"findPlatform","kind":"function","lang":"kotlin","code":"@Substitute\n fun findPlatform(): Platform = Jdk9Platform.buildIfSupported()!!"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/graal/OkHttpFeature.kt","line":27,"symbol":"OkHttpFeature","kind":"class","lang":"kotlin","doc":"Automatic configuration of OkHttp for native images. Currently, includes all necessary resources.","code":"class OkHttpFeature : Feature {\n @IgnoreJRERequirement\n override fun beforeAnalysis(access: Feature.BeforeAnalysisAccess?) = Unit\n}"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/graal/OkHttpFeature.kt","line":28,"symbol":"beforeAnalysis","kind":"function","lang":"kotlin","code":"@IgnoreJRERequirement\n override fun beforeAnalysis(access: Feature.BeforeAnalysisAccess?) = Unit"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/BouncyCastlePlatform.kt","line":35,"symbol":"BouncyCastlePlatform","kind":"class","lang":"kotlin","doc":"Platform using BouncyCastle if installed as the first Security Provider. Requires org.bouncycastle:bctls-jdk15on on the classpath.","code":"class BouncyCastlePlatform private constructor() : Platform() {\n private val provider: Provider = BouncyCastleJsseProvider()\n\n override fun newSSLContext(): SSLContext = SSLContext.getInstance(\"TLS\", provider)\n\n override fun platformTrustManager(): X509TrustManager {\n val factory =\n TrustManagerFactory.getInstance(\n \"PKIX\",\n BouncyCastleJsseProvider.PROVIDER_NAME,\n )\n factory.init(null as KeyStore?)\n val trustManagers = factory.trustManagers!!\n check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {\n \"Unexpected default trust managers: ${trustManagers.contentToString()}\"\n }\n return trustManagers[0] as X509TrustManager\n }\n\n override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager =\n throw UnsupportedOperationException(\n \"clientBuilder.sslSocketFactory(SSLSocketFactory) not supported with BouncyCastle\",\n )\n\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n if (sslSocket is BCSSLSocket) {\n val sslParameters = sslSocket.parameters\n\n // Enable A"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/BouncyCastlePlatform.kt","line":38,"symbol":"newSSLContext","kind":"function","lang":"kotlin","code":"override fun newSSLContext(): SSLContext = SSLContext.getInstance(\"TLS\", provider)"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/BouncyCastlePlatform.kt","line":40,"symbol":"platformTrustManager","kind":"function","lang":"kotlin","code":"override fun platformTrustManager(): X509TrustManager {\n val factory =\n TrustManagerFactory.getInstance(\n \"PKIX\",\n BouncyCastleJsseProvider.PROVIDER_NAME,\n )\n factory.init(null as KeyStore?)\n val trustManagers = factory.trustManagers!!\n check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {\n \"Unexpected default trust managers: ${trustManagers.contentToString()}\"\n }\n return trustManagers[0] as X509TrustManager\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/BouncyCastlePlatform.kt","line":54,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager =\n throw UnsupportedOperationException(\n \"clientBuilder.sslSocketFactory(SSLSocketFactory) not supported with BouncyCastle\",\n )"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/BouncyCastlePlatform.kt","line":59,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n if (sslSocket is BCSSLSocket) {\n val sslParameters = sslSocket.parameters\n\n // Enable ALPN.\n val names = alpnProtocolNames(protocols)\n sslParameters.applicationProtocols = names.toTypedArray()\n\n sslSocket.parameters = sslParameters\n } else {\n super.configureTlsExtensions(sslSocket, hostname, protocols, echConfigList)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/BouncyCastlePlatform.kt","line":78,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n if (sslSocket is BCSSLSocket) {\n when (val protocol = (sslSocket as BCSSLSocket).applicationProtocol) {\n // Handles both un-configured and none selected.\n null, \"\" -> null\n\n else -> protocol\n }\n } else {\n super.getSelectedProtocol(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/BouncyCastlePlatform.kt","line":101,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): BouncyCastlePlatform? = if (isSupported) BouncyCastlePlatform() else null"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":38,"symbol":"ConscryptPlatform","kind":"class","lang":"kotlin","doc":"Platform using Conscrypt (conscrypt.org) if installed as the first Security Provider. Requires org.conscrypt:conscrypt-openjdk-uber >= 2.1.0 on the classpath.","code":"class ConscryptPlatform private constructor() : Platform() {\n private val provider: Provider = Conscrypt.newProvider()\n\n // See release notes https://groups.google.com/forum/#!forum/conscrypt\n // for version differences\n override fun newSSLContext(): SSLContext =\n // supports TLSv1.3 by default (version api is >= 1.4.0)\n SSLContext.getInstance(\"TLS\", provider)\n\n override fun platformTrustManager(): X509TrustManager {\n val trustManagers =\n TrustManagerFactory\n .getInstance(TrustManagerFactory.getDefaultAlgorithm())\n .apply {\n init(null as KeyStore?)\n }.trustManagers!!\n check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {\n \"Unexpected default trust managers: ${trustManagers.contentToString()}\"\n }\n val x509TrustManager = trustManagers[0] as X509TrustManager\n // Disabled because OkHttp will run anyway\n Conscrypt.setHostnameVerifier(x509TrustManager, DisabledHostnameVerifier)\n return x509TrustManager\n }\n\n internal object DisabledHostnameVerifier : ConscryptHostnameVerifier {\n fun verify(\n hostname: String?,\n session: SSLSession?,\n ): Boolean = true\n\n override fun verify(\n "} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":43,"symbol":"newSSLContext","kind":"function","lang":"kotlin","doc":"See release notes https://groups.google.com/forum/#!forum/conscrypt for version differences","code":"override fun newSSLContext(): SSLContext =\n // supports TLSv1.3 by default (version api is >= 1.4.0)\n SSLContext.getInstance(\"TLS\", provider)"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":47,"symbol":"platformTrustManager","kind":"function","lang":"kotlin","code":"override fun platformTrustManager(): X509TrustManager {\n val trustManagers =\n TrustManagerFactory\n .getInstance(TrustManagerFactory.getDefaultAlgorithm())\n .apply {\n init(null as KeyStore?)\n }.trustManagers!!\n check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {\n \"Unexpected default trust managers: ${trustManagers.contentToString()}\"\n }\n val x509TrustManager = trustManagers[0] as X509TrustManager\n // Disabled because OkHttp will run anyway\n Conscrypt.setHostnameVerifier(x509TrustManager, DisabledHostnameVerifier)\n return x509TrustManager\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":63,"symbol":"DisabledHostnameVerifier","kind":"object","lang":"kotlin","code":"internal object DisabledHostnameVerifier : ConscryptHostnameVerifier {\n fun verify(\n hostname: String?,\n session: SSLSession?,\n ): Boolean = true\n\n override fun verify(\n certs: Array?,\n hostname: String?,\n session: SSLSession?,\n ): Boolean = true\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":64,"symbol":"verify","kind":"function","lang":"kotlin","code":"fun verify(\n hostname: String?,\n session: SSLSession?,\n ): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":69,"symbol":"verify","kind":"function","lang":"kotlin","code":"override fun verify(\n certs: Array?,\n hostname: String?,\n session: SSLSession?,\n ): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":76,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager? = null"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":78,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n if (Conscrypt.isConscrypt(sslSocket)) {\n // Enable session tickets.\n Conscrypt.setUseSessionTickets(sslSocket, true)\n\n // Enable ALPN.\n val names = alpnProtocolNames(protocols)\n Conscrypt.setApplicationProtocols(sslSocket, names.toTypedArray())\n } else {\n super.configureTlsExtensions(sslSocket, hostname, protocols, echConfigList)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":96,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n if (Conscrypt.isConscrypt(sslSocket)) {\n Conscrypt.getApplicationProtocol(sslSocket)\n } else {\n super.getSelectedProtocol(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":103,"symbol":"newSslSocketFactory","kind":"function","lang":"kotlin","code":"override fun newSslSocketFactory(trustManager: X509TrustManager): SSLSocketFactory =\n newSSLContext()\n .apply {\n init(null, arrayOf(trustManager), null)\n }.socketFactory"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":127,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): ConscryptPlatform? = if (isSupported) ConscryptPlatform() else null"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/ConscryptPlatform.kt","line":129,"symbol":"atLeastVersion","kind":"function","lang":"kotlin","code":"fun atLeastVersion(\n major: Int,\n minor: Int = 0,\n patch: Int = 0,\n ): Boolean {\n val conscryptVersion = Conscrypt.version() ?: return false\n\n if (conscryptVersion.major() != major) {\n return conscryptVersion.major() > major\n }\n\n if (conscryptVersion.minor() != minor) {\n return conscryptVersion.minor() > minor\n }\n\n return conscryptVersion.patch() >= patch\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatform.kt","line":27,"symbol":"Jdk8WithJettyBootPlatform","kind":"class","lang":"kotlin","doc":"OpenJDK 8 with `org.mortbay.jetty.alpn:alpn-boot` in the boot class path.","code":"class Jdk8WithJettyBootPlatform(\n private val putMethod: Method,\n private val getMethod: Method,\n private val removeMethod: Method,\n private val clientProviderClass: Class<*>,\n private val serverProviderClass: Class<*>,\n) : Platform() {\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n val names = alpnProtocolNames(protocols)\n\n try {\n val alpnProvider =\n Proxy.newProxyInstance(\n Platform::class.java.classLoader,\n arrayOf(clientProviderClass, serverProviderClass),\n AlpnProvider(names),\n )\n putMethod.invoke(null, sslSocket, alpnProvider)\n } catch (e: InvocationTargetException) {\n throw AssertionError(\"failed to set ALPN\", e)\n } catch (e: IllegalAccessException) {\n throw AssertionError(\"failed to set ALPN\", e)\n }\n }\n\n override fun afterHandshake(sslSocket: SSLSocket) {\n try {\n removeMethod.invoke(null, sslSocket)\n } catch (e: IllegalAccessException) {\n throw AssertionError(\"failed to remove ALPN\", e)\n } catch (e: InvocationTargetException) {\n throw AssertionError(\"failed to"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatform.kt","line":34,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List,\n echConfigList: ByteString?,\n ) {\n val names = alpnProtocolNames(protocols)\n\n try {\n val alpnProvider =\n Proxy.newProxyInstance(\n Platform::class.java.classLoader,\n arrayOf(clientProviderClass, serverProviderClass),\n AlpnProvider(names),\n )\n putMethod.invoke(null, sslSocket, alpnProvider)\n } catch (e: InvocationTargetException) {\n throw AssertionError(\"failed to set ALPN\", e)\n } catch (e: IllegalAccessException) {\n throw AssertionError(\"failed to set ALPN\", e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatform.kt","line":57,"symbol":"afterHandshake","kind":"function","lang":"kotlin","code":"override fun afterHandshake(sslSocket: SSLSocket) {\n try {\n removeMethod.invoke(null, sslSocket)\n } catch (e: IllegalAccessException) {\n throw AssertionError(\"failed to remove ALPN\", e)\n } catch (e: InvocationTargetException) {\n throw AssertionError(\"failed to remove ALPN\", e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatform.kt","line":67,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? {\n try {\n val provider = Proxy.getInvocationHandler(getMethod.invoke(null, sslSocket)) as AlpnProvider\n if (!provider.unsupported && provider.selected == null) {\n log(\"ALPN callback dropped: HTTP/2 is disabled. \" + \"Is alpn-boot on the boot class path?\")\n return null\n }\n return if (provider.unsupported) null else provider.selected\n } catch (e: InvocationTargetException) {\n throw AssertionError(\"failed to get ALPN selected protocol\", e)\n } catch (e: IllegalAccessException) {\n throw AssertionError(\"failed to get ALPN selected protocol\", e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatform.kt","line":86,"symbol":"AlpnProvider","kind":"class","lang":"kotlin","doc":"Handle the methods of ALPN's ClientProvider and ServerProvider without a compile-time dependency on those interfaces.","code":"private class AlpnProvider(\n /** This peer's supported protocols. */\n private val protocols: List,\n ) : InvocationHandler {\n /** Set when remote peer notifies ALPN is unsupported. */\n var unsupported: Boolean = false\n\n /** The protocol the server selected. */\n var selected: String? = null\n\n @Throws(Throwable::class)\n override fun invoke(\n proxy: Any,\n method: Method,\n args: Array?,\n ): Any? {\n val callArgs = args ?: arrayOf()\n val methodName = method.name\n val returnType = method.returnType\n if (methodName == \"supports\" && Boolean::class.javaPrimitiveType == returnType) {\n return true // ALPN is supported.\n } else if (methodName == \"unsupported\" && Void.TYPE == returnType) {\n this.unsupported = true // Peer doesn't support ALPN.\n return null\n } else if (methodName == \"protocols\" && callArgs.isEmpty()) {\n return protocols // Client advertises these protocols.\n } else if ((methodName == \"selectProtocol\" || methodName == \"select\") &&\n String::class.java == returnType &&\n callArgs.size == 1 &&\n callArgs[0] is List<*>\n ) {\n val pee"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatform.kt","line":96,"symbol":"invoke","kind":"function","lang":"kotlin","code":"@Throws(Throwable::class)\n override fun invoke(\n proxy: Any,\n method: Method,\n args: Array?,\n ): Any? {\n val callArgs = args ?: arrayOf()\n val methodName = method.name\n val returnType = method.returnType\n if (methodName == \"supports\" && Boolean::class.javaPrimitiveType == returnType) {\n return true // ALPN is supported.\n } else if (methodName == \"unsupported\" && Void.TYPE == returnType) {\n this.unsupported = true // Peer doesn't support ALPN.\n return null\n } else if (methodName == \"protocols\" && callArgs.isEmpty()) {\n return protocols // Client advertises these protocols.\n } else if ((methodName == \"selectProtocol\" || methodName == \"select\") &&\n String::class.java == returnType &&\n callArgs.size == 1 &&\n callArgs[0] is List<*>\n ) {\n val peerProtocols = callArgs[0] as List<*>\n // Pick the first known protocol the peer advertises.\n for (i in 0..peerProtocols.size) {\n val protocol = peerProtocols[i] as String\n if (protocol in protocols) {\n selected = protocol\n return selected\n }\n }\n "} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatform.kt","line":138,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): Platform? {\n val jvmVersion = System.getProperty(\"java.specification.version\", \"unknown\")\n try {\n // 1.8, 9, 10, 11, 12 etc\n val version = jvmVersion.toInt()\n if (version >= 9) return null\n } catch (_: NumberFormatException) {\n // expected on >= JDK 9\n }\n\n // Find Jetty's ALPN extension for OpenJDK.\n try {\n val alpnClassName = \"org.eclipse.jetty.alpn.ALPN\"\n val alpnClass = Class.forName(alpnClassName, true, null)\n val providerClass = Class.forName(\"$alpnClassName\\$Provider\", true, null)\n val clientProviderClass = Class.forName(\"$alpnClassName\\$ClientProvider\", true, null)\n val serverProviderClass = Class.forName(\"$alpnClassName\\$ServerProvider\", true, null)\n val putMethod = alpnClass.getMethod(\"put\", SSLSocket::class.java, providerClass)\n val getMethod = alpnClass.getMethod(\"get\", SSLSocket::class.java)\n val removeMethod = alpnClass.getMethod(\"remove\", SSLSocket::class.java)\n return Jdk8WithJettyBootPlatform(\n putMethod,\n getMethod,\n removeMethod,\n clientProviderClass,\n serverProviderClass,\n "} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/OpenJSSEPlatform.kt","line":34,"symbol":"OpenJSSEPlatform","kind":"class","lang":"kotlin","doc":"Platform using OpenJSSE (https://github.com/openjsse/openjsse) if installed as the first Security Provider. Requires org.openjsse:openjsse >= 1.1.0 on the classpath.","code":"class OpenJSSEPlatform private constructor() : Platform() {\n private val provider: Provider =\n org.openjsse.net.ssl\n .OpenJSSE()\n\n // Selects TLSv1.3 so we are specific about our intended version ranges (not just 1.3)\n // and because it's a common pattern for VMs to have differences between supported and\n // defaulted versions for TLS based on what is requested.\n override fun newSSLContext(): SSLContext = SSLContext.getInstance(\"TLSv1.3\", provider)\n\n override fun platformTrustManager(): X509TrustManager {\n val factory =\n TrustManagerFactory.getInstance(\n TrustManagerFactory.getDefaultAlgorithm(),\n provider,\n )\n factory.init(null as KeyStore?)\n val trustManagers = factory.trustManagers!!\n check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {\n \"Unexpected default trust managers: ${trustManagers.contentToString()}\"\n }\n return trustManagers[0] as X509TrustManager\n }\n\n override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager =\n throw UnsupportedOperationException(\n \"clientBuilder.sslSocketFactory(SSLSocketFactory) not supported with OpenJSSE\",\n )\n\n override fun configureT"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/OpenJSSEPlatform.kt","line":42,"symbol":"newSSLContext","kind":"function","lang":"kotlin","doc":"Selects TLSv1.3 so we are specific about our intended version ranges (not just 1.3) and because it's a common pattern for VMs to have differences between supported and defaulted versions for TLS based on what is requested.","code":"override fun newSSLContext(): SSLContext = SSLContext.getInstance(\"TLSv1.3\", provider)"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/OpenJSSEPlatform.kt","line":44,"symbol":"platformTrustManager","kind":"function","lang":"kotlin","code":"override fun platformTrustManager(): X509TrustManager {\n val factory =\n TrustManagerFactory.getInstance(\n TrustManagerFactory.getDefaultAlgorithm(),\n provider,\n )\n factory.init(null as KeyStore?)\n val trustManagers = factory.trustManagers!!\n check(trustManagers.size == 1 && trustManagers[0] is X509TrustManager) {\n \"Unexpected default trust managers: ${trustManagers.contentToString()}\"\n }\n return trustManagers[0] as X509TrustManager\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/OpenJSSEPlatform.kt","line":58,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"override fun trustManager(sslSocketFactory: SSLSocketFactory): X509TrustManager =\n throw UnsupportedOperationException(\n \"clientBuilder.sslSocketFactory(SSLSocketFactory) not supported with OpenJSSE\",\n )"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/OpenJSSEPlatform.kt","line":63,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n if (sslSocket is org.openjsse.javax.net.ssl.SSLSocket) {\n val sslParameters = sslSocket.sslParameters\n\n if (sslParameters is org.openjsse.javax.net.ssl.SSLParameters) {\n // Enable ALPN.\n val names = alpnProtocolNames(protocols)\n sslParameters.applicationProtocols = names.toTypedArray()\n\n sslSocket.sslParameters = sslParameters\n }\n } else {\n super.configureTlsExtensions(sslSocket, hostname, protocols, echConfigList)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/OpenJSSEPlatform.kt","line":84,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? =\n if (sslSocket is org.openjsse.javax.net.ssl.SSLSocket) {\n when (val protocol = sslSocket.applicationProtocol) {\n // Handles both un-configured and none selected.\n null, \"\" -> null\n\n else -> protocol\n }\n } else {\n super.getSelectedProtocol(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/OpenJSSEPlatform.kt","line":107,"symbol":"buildIfSupported","kind":"function","lang":"kotlin","code":"fun buildIfSupported(): OpenJSSEPlatform? = if (isSupported) OpenJSSEPlatform() else null"} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/PlatformRegistry.kt","line":20,"symbol":"PlatformRegistry","kind":"object","lang":"kotlin","code":"actual object PlatformRegistry {\n private val isConscryptPreferred: Boolean\n get() {\n val preferredProvider = Security.getProviders()[0].name\n return \"Conscrypt\" == preferredProvider\n }\n\n private val isOpenJSSEPreferred: Boolean\n get() {\n val preferredProvider = Security.getProviders()[0].name\n return \"OpenJSSE\" == preferredProvider\n }\n\n private val isBouncyCastlePreferred: Boolean\n get() {\n val preferredProvider = Security.getProviders()[0].name\n return \"BC\" == preferredProvider\n }\n\n actual fun findPlatform(): Platform {\n if (isConscryptPreferred) {\n val conscrypt = ConscryptPlatform.buildIfSupported()\n\n if (conscrypt != null) {\n return conscrypt\n }\n }\n\n if (isBouncyCastlePreferred) {\n val bc = BouncyCastlePlatform.buildIfSupported()\n\n if (bc != null) {\n return bc\n }\n }\n\n if (isOpenJSSEPreferred) {\n val openJSSE = OpenJSSEPlatform.buildIfSupported()\n\n if (openJSSE != null) {\n return openJSSE\n }\n }\n\n // An Oracle JDK 9 like OpenJDK, or JDK 8 251+.\n val jdk9 = Jdk9Platform.buildIfSupported()\n\n if (jdk9 != null) {\n return jdk9\n }\n\n "} {"repo":"okhttp","file":"okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/PlatformRegistry.kt","line":39,"symbol":"findPlatform","kind":"function","lang":"kotlin","code":"actual fun findPlatform(): Platform {\n if (isConscryptPreferred) {\n val conscrypt = ConscryptPlatform.buildIfSupported()\n\n if (conscrypt != null) {\n return conscrypt\n }\n }\n\n if (isBouncyCastlePreferred) {\n val bc = BouncyCastlePlatform.buildIfSupported()\n\n if (bc != null) {\n return bc\n }\n }\n\n if (isOpenJSSEPreferred) {\n val openJSSE = OpenJSSEPlatform.buildIfSupported()\n\n if (openJSSE != null) {\n return openJSSE\n }\n }\n\n // An Oracle JDK 9 like OpenJDK, or JDK 8 251+.\n val jdk9 = Jdk9Platform.buildIfSupported()\n\n if (jdk9 != null) {\n return jdk9\n }\n\n // An Oracle JDK 8 like OpenJDK, pre 251.\n val jdkWithJettyBoot = Jdk8WithJettyBootPlatform.buildIfSupported()\n\n if (jdkWithJettyBoot != null) {\n return jdkWithJettyBoot\n }\n\n return Platform()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmMain/resources/META-INF/native-image/okhttp/okhttp/native-image.properties","line":1,"symbol":"Args","kind":"field","lang":"properties","code":"Args = -H:+AddAllCharsets --enable-http --enable-https --features=okhttp3.internal.graal.OkHttpFeature"} {"repo":"okhttp","file":"okhttp/src/jvmTest/java/okhttp3/CallJavaTest.java","line":22,"symbol":"CallJavaTest","kind":"class","lang":"java","code":"public class CallJavaTest {\n @RegisterExtension\n OkHttpClientTestRule clientTestRule = new OkHttpClientTestRule();\n\n private OkHttpClient client = clientTestRule.newClient();\n\n @Test\n public void tagsSeededFromRequest() {\n Request request = new Request.Builder()\n .url(HttpUrl.get(\"https://square.com/\"))\n .tag(Integer.class, 5)\n .tag(String.class, \"hello\")\n .build();\n Call call = client.newCall(request);\n\n assertEquals(5, call.tag(Integer.class));\n assertEquals(\"hello\", call.tag(String.class));\n assertEquals(null, call.tag(Boolean.class));\n assertEquals(null, call.tag(Object.class));\n }\n\n @Test\n public void tagsCanBeComputed() {\n Request request = new Request.Builder()\n .url(HttpUrl.get(\"https://square.com/\"))\n .build();\n Call call = client.newCall(request);\n\n assertEquals(\"a\", call.tag(String.class, () -> \"a\"));\n assertEquals(\"a\", call.tag(String.class, () -> \"b\"));\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/java/okhttp3/CallJavaTest.java","line":28,"symbol":"tagsSeededFromRequest","kind":"method","lang":"java","code":"@Test\n public void tagsSeededFromRequest() {\n Request request = new Request.Builder()\n .url(HttpUrl.get(\"https://square.com/\"))\n .tag(Integer.class, 5)\n .tag(String.class, \"hello\")\n .build();\n Call call = client.newCall(request);\n\n assertEquals(5, call.tag(Integer.class));\n assertEquals(\"hello\", call.tag(String.class));\n assertEquals(null, call.tag(Boolean.class));\n assertEquals(null, call.tag(Object.class));\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/java/okhttp3/CallJavaTest.java","line":43,"symbol":"tagsCanBeComputed","kind":"method","lang":"java","code":"@Test\n public void tagsCanBeComputed() {\n Request request = new Request.Builder()\n .url(HttpUrl.get(\"https://square.com/\"))\n .build();\n Call call = client.newCall(request);\n\n assertEquals(\"a\", call.tag(String.class, () -> \"a\"));\n assertEquals(\"a\", call.tag(String.class, () -> \"b\"));\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AddressTest.kt","line":26,"symbol":"AddressTest","kind":"class","lang":"kotlin","code":"class AddressTest {\n private val factory =\n TestValueFactory().apply {\n uriHost = \"example.com\"\n uriPort = 80\n }\n\n @AfterEach fun tearDown() {\n factory.close()\n }\n\n @Test fun equalsAndHashcode() {\n val a = factory.newAddress()\n val b = factory.newAddress()\n assertThat(b).isEqualTo(a)\n assertThat(b.hashCode()).isEqualTo(a.hashCode())\n }\n\n @Test fun differentProxySelectorsAreDifferent() {\n val a = factory.newAddress(proxySelector = RecordingProxySelector())\n val b = factory.newAddress(proxySelector = RecordingProxySelector())\n assertThat(b).isNotEqualTo(a)\n }\n\n @Test fun addressToString() {\n val address = factory.newAddress()\n assertThat(address.toString())\n .isEqualTo(\"Address{example.com:80, proxySelector=RecordingProxySelector}\")\n }\n\n @Test fun addressWithProxyToString() {\n val address = factory.newAddress(proxy = Proxy.NO_PROXY)\n assertThat(address.toString())\n .isEqualTo(\"Address{example.com:80, proxy=${Proxy.NO_PROXY}}\")\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AddressTest.kt","line":33,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n factory.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AddressTest.kt","line":37,"symbol":"equalsAndHashcode","kind":"function","lang":"kotlin","code":"@Test fun equalsAndHashcode() {\n val a = factory.newAddress()\n val b = factory.newAddress()\n assertThat(b).isEqualTo(a)\n assertThat(b.hashCode()).isEqualTo(a.hashCode())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AddressTest.kt","line":44,"symbol":"differentProxySelectorsAreDifferent","kind":"function","lang":"kotlin","code":"@Test fun differentProxySelectorsAreDifferent() {\n val a = factory.newAddress(proxySelector = RecordingProxySelector())\n val b = factory.newAddress(proxySelector = RecordingProxySelector())\n assertThat(b).isNotEqualTo(a)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AddressTest.kt","line":50,"symbol":"addressToString","kind":"function","lang":"kotlin","code":"@Test fun addressToString() {\n val address = factory.newAddress()\n assertThat(address.toString())\n .isEqualTo(\"Address{example.com:80, proxySelector=RecordingProxySelector}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AddressTest.kt","line":56,"symbol":"addressWithProxyToString","kind":"function","lang":"kotlin","code":"@Test fun addressWithProxyToString() {\n val address = factory.newAddress(proxy = Proxy.NO_PROXY)\n assertThat(address.toString())\n .isEqualTo(\"Address{example.com:80, proxy=${Proxy.NO_PROXY}}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":29,"symbol":"AutobahnTester","kind":"class","lang":"kotlin","doc":"Exercises the web socket implementation against the [Autobahn Testsuite](http://autobahn.ws/testsuite/).","code":"class AutobahnTester {\n val client = OkHttpClient()\n\n private fun newWebSocket(\n path: String,\n listener: WebSocketListener,\n ): WebSocket {\n val request =\n Request\n .Builder()\n .url(HOST + path)\n .build()\n return client.newWebSocket(request, listener)\n }\n\n fun run() {\n try {\n val count = getTestCount()\n println(\"Test count: $count\")\n for (number in 1..count) {\n runTest(number, count)\n }\n updateReports()\n } finally {\n client.dispatcher.executorService.shutdown()\n }\n }\n\n private fun runTest(\n number: Long,\n count: Long,\n ) {\n val latch = CountDownLatch(1)\n val startNanos = AtomicLong()\n newWebSocket(\n \"/runCase?case=$number&agent=okhttp\",\n object : WebSocketListener() {\n override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n println(\"Executing test case $number/$count\")\n startNanos.set(System.nanoTime())\n }\n\n override fun onMessage(\n webSocket: WebSocket,\n bytes: ByteString,\n ) {\n webSocket.send(bytes)\n }\n\n override fun onMessage(\n w"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":32,"symbol":"newWebSocket","kind":"function","lang":"kotlin","code":"private fun newWebSocket(\n path: String,\n listener: WebSocketListener,\n ): WebSocket {\n val request =\n Request\n .Builder()\n .url(HOST + path)\n .build()\n return client.newWebSocket(request, listener)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":44,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n try {\n val count = getTestCount()\n println(\"Test count: $count\")\n for (number in 1..count) {\n runTest(number, count)\n }\n updateReports()\n } finally {\n client.dispatcher.executorService.shutdown()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":57,"symbol":"runTest","kind":"function","lang":"kotlin","code":"private fun runTest(\n number: Long,\n count: Long,\n ) {\n val latch = CountDownLatch(1)\n val startNanos = AtomicLong()\n newWebSocket(\n \"/runCase?case=$number&agent=okhttp\",\n object : WebSocketListener() {\n override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n println(\"Executing test case $number/$count\")\n startNanos.set(System.nanoTime())\n }\n\n override fun onMessage(\n webSocket: WebSocket,\n bytes: ByteString,\n ) {\n webSocket.send(bytes)\n }\n\n override fun onMessage(\n webSocket: WebSocket,\n text: String,\n ) {\n webSocket.send(text)\n }\n\n override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n webSocket.close(1000, null)\n latch.countDown()\n }\n\n override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n t.printStackTrace(System.out)\n latch.countDown()\n }\n },\n )\n\n check(latch.await(30, TimeUnit.SECONDS"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":66,"symbol":"onOpen","kind":"function","lang":"kotlin","code":"override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n println(\"Executing test case $number/$count\")\n startNanos.set(System.nanoTime())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":74,"symbol":"onMessage","kind":"function","lang":"kotlin","code":"override fun onMessage(\n webSocket: WebSocket,\n bytes: ByteString,\n ) {\n webSocket.send(bytes)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":81,"symbol":"onMessage","kind":"function","lang":"kotlin","code":"override fun onMessage(\n webSocket: WebSocket,\n text: String,\n ) {\n webSocket.send(text)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":88,"symbol":"onClosing","kind":"function","lang":"kotlin","code":"override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n webSocket.close(1000, null)\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":97,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n t.printStackTrace(System.out)\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":114,"symbol":"getTestCount","kind":"function","lang":"kotlin","code":"private fun getTestCount(): Long {\n val latch = CountDownLatch(1)\n val countRef = AtomicLong()\n val failureRef = AtomicReference()\n\n newWebSocket(\n \"/getCaseCount\",\n object : WebSocketListener() {\n override fun onMessage(\n webSocket: WebSocket,\n text: String,\n ) {\n countRef.set(text.toLong())\n }\n\n override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n webSocket.close(1000, null)\n latch.countDown()\n }\n\n override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n failureRef.set(t)\n latch.countDown()\n }\n },\n )\n\n check(latch.await(10, TimeUnit.SECONDS)) { \"Timed out waiting for count.\" }\n\n val failure = failureRef.get()\n if (failure != null) {\n throw RuntimeException(failure)\n }\n\n return countRef.get()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":122,"symbol":"onMessage","kind":"function","lang":"kotlin","code":"override fun onMessage(\n webSocket: WebSocket,\n text: String,\n ) {\n countRef.set(text.toLong())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":129,"symbol":"onClosing","kind":"function","lang":"kotlin","code":"override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n webSocket.close(1000, null)\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":138,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n failureRef.set(t)\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":159,"symbol":"updateReports","kind":"function","lang":"kotlin","code":"private fun updateReports() {\n val latch = CountDownLatch(1)\n newWebSocket(\n \"/updateReports?agent=$USER_AGENT\",\n object : WebSocketListener() {\n override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n webSocket.close(1000, null)\n latch.countDown()\n }\n\n override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n latch.countDown()\n }\n },\n )\n\n check(latch.await(10, TimeUnit.SECONDS)) { \"Timed out waiting for count.\" }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":164,"symbol":"onClosing","kind":"function","lang":"kotlin","code":"override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n webSocket.close(1000, null)\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":173,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/AutobahnTester.kt","line":189,"symbol":"main","kind":"function","lang":"kotlin","code":"@JvmStatic fun main(args: Array) {\n AutobahnTester().run()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/BouncyCastleTest.kt","line":28,"symbol":"BouncyCastleTest","kind":"class","lang":"kotlin","code":"class BouncyCastleTest {\n @JvmField @RegisterExtension\n var platform = PlatformRule()\n\n @JvmField @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n var client = clientTestRule.newClient()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n OkHttpDebugLogging.enable(\"org.bouncycastle.jsse\")\n platform.assumeBouncyCastle()\n }\n\n @Test\n fun testMozilla() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://mozilla.org/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/BouncyCastleTest.kt","line":39,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n OkHttpDebugLogging.enable(\"org.bouncycastle.jsse\")\n platform.assumeBouncyCastle()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/BouncyCastleTest.kt","line":45,"symbol":"testMozilla","kind":"function","lang":"kotlin","code":"@Test\n fun testMozilla() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://mozilla.org/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":29,"symbol":"CacheControlJvmTest","kind":"class","lang":"kotlin","code":"class CacheControlJvmTest {\n @Test\n @Throws(Exception::class)\n fun completeBuilder() {\n val cacheControl =\n CacheControl\n .Builder()\n .noCache()\n .noStore()\n .maxAge(1, TimeUnit.SECONDS)\n .maxStale(2, TimeUnit.SECONDS)\n .minFresh(3, TimeUnit.SECONDS)\n .onlyIfCached()\n .noTransform()\n .immutable()\n .build()\n assertThat(cacheControl.toString()).isEqualTo(\n \"no-cache, no-store, max-age=1, max-stale=2, min-fresh=3, only-if-cached, \" +\n \"no-transform, immutable\",\n )\n assertThat(cacheControl.noCache).isTrue()\n assertThat(cacheControl.noStore).isTrue()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(1)\n assertThat(cacheControl.maxStaleSeconds).isEqualTo(2)\n assertThat(cacheControl.minFreshSeconds).isEqualTo(3)\n assertThat(cacheControl.onlyIfCached).isTrue()\n assertThat(cacheControl.noTransform).isTrue()\n assertThat(cacheControl.immutable).isTrue()\n\n // These members are accessible to response headers only.\n assertThat(cacheControl.sMaxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.isPrivate).isFalse()\n assertThat(cacheControl.isPublic).isFalse()\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":30,"symbol":"completeBuilder","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun completeBuilder() {\n val cacheControl =\n CacheControl\n .Builder()\n .noCache()\n .noStore()\n .maxAge(1, TimeUnit.SECONDS)\n .maxStale(2, TimeUnit.SECONDS)\n .minFresh(3, TimeUnit.SECONDS)\n .onlyIfCached()\n .noTransform()\n .immutable()\n .build()\n assertThat(cacheControl.toString()).isEqualTo(\n \"no-cache, no-store, max-age=1, max-stale=2, min-fresh=3, only-if-cached, \" +\n \"no-transform, immutable\",\n )\n assertThat(cacheControl.noCache).isTrue()\n assertThat(cacheControl.noStore).isTrue()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(1)\n assertThat(cacheControl.maxStaleSeconds).isEqualTo(2)\n assertThat(cacheControl.minFreshSeconds).isEqualTo(3)\n assertThat(cacheControl.onlyIfCached).isTrue()\n assertThat(cacheControl.noTransform).isTrue()\n assertThat(cacheControl.immutable).isTrue()\n\n // These members are accessible to response headers only.\n assertThat(cacheControl.sMaxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.isPrivate).isFalse()\n assertThat(cacheControl.isPublic).isFalse()\n assertThat(cacheControl.mustRe"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":65,"symbol":"parseEmpty","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun parseEmpty() {\n val cacheControl =\n parse(\n Headers.Builder().set(\"Cache-Control\", \"\").build(),\n )\n assertThat(cacheControl.toString()).isEqualTo(\"\")\n assertThat(cacheControl.noCache).isFalse()\n assertThat(cacheControl.noStore).isFalse()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.sMaxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.isPublic).isFalse()\n assertThat(cacheControl.mustRevalidate).isFalse()\n assertThat(cacheControl.maxStaleSeconds).isEqualTo(-1)\n assertThat(cacheControl.minFreshSeconds).isEqualTo(-1)\n assertThat(cacheControl.onlyIfCached).isFalse()\n assertThat(cacheControl.mustRevalidate).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":85,"symbol":"parse","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun parse() {\n val header = (\n \"no-cache, no-store, max-age=1, s-maxage=2, private, public, must-revalidate, \" +\n \"max-stale=3, min-fresh=4, only-if-cached, no-transform\"\n )\n val cacheControl =\n parse(\n Headers\n .Builder()\n .set(\"Cache-Control\", header)\n .build(),\n )\n assertThat(cacheControl.noCache).isTrue()\n assertThat(cacheControl.noStore).isTrue()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(1)\n assertThat(cacheControl.sMaxAgeSeconds).isEqualTo(2)\n assertThat(cacheControl.isPrivate).isTrue()\n assertThat(cacheControl.isPublic).isTrue()\n assertThat(cacheControl.mustRevalidate).isTrue()\n assertThat(cacheControl.maxStaleSeconds).isEqualTo(3)\n assertThat(cacheControl.minFreshSeconds).isEqualTo(4)\n assertThat(cacheControl.onlyIfCached).isTrue()\n assertThat(cacheControl.noTransform).isTrue()\n assertThat(cacheControl.toString()).isEqualTo(header)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":113,"symbol":"parseIgnoreCacheControlExtensions","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun parseIgnoreCacheControlExtensions() {\n // Example from http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.6\n val header = \"private, community=\\\"UCI\\\"\"\n val cacheControl =\n parse(\n Headers\n .Builder()\n .set(\"Cache-Control\", header)\n .build(),\n )\n assertThat(cacheControl.noCache).isFalse()\n assertThat(cacheControl.noStore).isFalse()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.sMaxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.isPrivate).isTrue()\n assertThat(cacheControl.isPublic).isFalse()\n assertThat(cacheControl.mustRevalidate).isFalse()\n assertThat(cacheControl.maxStaleSeconds).isEqualTo(-1)\n assertThat(cacheControl.minFreshSeconds).isEqualTo(-1)\n assertThat(cacheControl.onlyIfCached).isFalse()\n assertThat(cacheControl.noTransform).isFalse()\n assertThat(cacheControl.immutable).isFalse()\n assertThat(cacheControl.toString()).isEqualTo(header)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":140,"symbol":"parseCacheControlAndPragmaAreCombined","kind":"function","lang":"kotlin","code":"@Test\n fun parseCacheControlAndPragmaAreCombined() {\n val headers = headersOf(\"Cache-Control\", \"max-age=12\", \"Pragma\", \"must-revalidate\", \"Pragma\", \"public\")\n val cacheControl = parse(headers)\n assertThat(cacheControl.toString()).isEqualTo(\"max-age=12, public, must-revalidate\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":147,"symbol":"parseCacheControlHeaderValueIsRetained","kind":"function","lang":"kotlin","code":"@Test\n fun parseCacheControlHeaderValueIsRetained() {\n val value = \"max-age=12\"\n val headers = headersOf(\"Cache-Control\", value)\n val cacheControl = parse(headers)\n assertThat(cacheControl.toString()).isSameInstanceAs(value)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":155,"symbol":"parseCacheControlHeaderValueInvalidatedByPragma","kind":"function","lang":"kotlin","code":"@Test\n fun parseCacheControlHeaderValueInvalidatedByPragma() {\n val headers =\n headersOf(\n \"Cache-Control\",\n \"max-age=12\",\n \"Pragma\",\n \"must-revalidate\",\n )\n val cacheControl = parse(headers)\n assertThat(cacheControl.toString()).isEqualTo(\"max-age=12, must-revalidate\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":168,"symbol":"parseCacheControlHeaderValueInvalidatedByTwoValues","kind":"function","lang":"kotlin","code":"@Test\n fun parseCacheControlHeaderValueInvalidatedByTwoValues() {\n val headers =\n headersOf(\n \"Cache-Control\",\n \"max-age=12\",\n \"Cache-Control\",\n \"must-revalidate\",\n )\n val cacheControl = parse(headers)\n assertThat(cacheControl.toString()).isEqualTo(\"max-age=12, must-revalidate\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":181,"symbol":"parsePragmaHeaderValueIsNotRetained","kind":"function","lang":"kotlin","code":"@Test\n fun parsePragmaHeaderValueIsNotRetained() {\n val headers = headersOf(\"Pragma\", \"must-revalidate\")\n val cacheControl = parse(headers)\n assertThat(cacheControl.toString()).isEqualTo(\"must-revalidate\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":188,"symbol":"computedHeaderValueIsCached","kind":"function","lang":"kotlin","code":"@Test\n fun computedHeaderValueIsCached() {\n val cacheControl =\n CacheControl\n .Builder()\n .maxAge(2, TimeUnit.DAYS)\n .build()\n assertThat(cacheControl.toString()).isEqualTo(\"max-age=172800\")\n assertThat(cacheControl.toString()).isSameInstanceAs(cacheControl.toString())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":199,"symbol":"timeDurationTruncatedToMaxValue","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun timeDurationTruncatedToMaxValue() {\n val cacheControl =\n CacheControl\n .Builder()\n .maxAge(365 * 100, TimeUnit.DAYS) // Longer than Integer.MAX_VALUE seconds.\n .build()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(Int.MAX_VALUE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":210,"symbol":"secondsMustBeNonNegative","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun secondsMustBeNonNegative() {\n val builder = CacheControl.Builder()\n assertFailsWith {\n builder.maxAge(-1, TimeUnit.SECONDS)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlJvmTest.kt","line":219,"symbol":"timePrecisionIsTruncatedToSeconds","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun timePrecisionIsTruncatedToSeconds() {\n val cacheControl =\n CacheControl\n .Builder()\n .maxAge(4999, TimeUnit.MILLISECONDS)\n .build()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(4)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlTest.kt","line":25,"symbol":"CacheControlTest","kind":"class","lang":"kotlin","code":"class CacheControlTest {\n @Test\n @Throws(Exception::class)\n fun emptyBuilderIsEmpty() {\n val cacheControl = CacheControl.Builder().build()\n assertThat(cacheControl.toString()).isEqualTo(\"\")\n assertThat(cacheControl.noCache).isFalse()\n assertThat(cacheControl.noStore).isFalse()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.sMaxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.isPrivate).isFalse()\n assertThat(cacheControl.isPublic).isFalse()\n assertThat(cacheControl.mustRevalidate).isFalse()\n assertThat(cacheControl.maxStaleSeconds).isEqualTo(-1)\n assertThat(cacheControl.minFreshSeconds).isEqualTo(-1)\n assertThat(cacheControl.onlyIfCached).isFalse()\n assertThat(cacheControl.mustRevalidate).isFalse()\n }\n\n @Test\n @Throws(Exception::class)\n fun completeBuilder() {\n val cacheControl =\n CacheControl\n .Builder()\n .noCache()\n .noStore()\n .maxAge(1.seconds)\n .maxStale(2.seconds)\n .minFresh(3.seconds)\n .onlyIfCached()\n .noTransform()\n .immutable()\n .build()\n assertThat(cacheControl.toString()).isEqualTo(\n \"no-cache, no-store, max"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlTest.kt","line":26,"symbol":"emptyBuilderIsEmpty","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun emptyBuilderIsEmpty() {\n val cacheControl = CacheControl.Builder().build()\n assertThat(cacheControl.toString()).isEqualTo(\"\")\n assertThat(cacheControl.noCache).isFalse()\n assertThat(cacheControl.noStore).isFalse()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.sMaxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.isPrivate).isFalse()\n assertThat(cacheControl.isPublic).isFalse()\n assertThat(cacheControl.mustRevalidate).isFalse()\n assertThat(cacheControl.maxStaleSeconds).isEqualTo(-1)\n assertThat(cacheControl.minFreshSeconds).isEqualTo(-1)\n assertThat(cacheControl.onlyIfCached).isFalse()\n assertThat(cacheControl.mustRevalidate).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheControlTest.kt","line":44,"symbol":"completeBuilder","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun completeBuilder() {\n val cacheControl =\n CacheControl\n .Builder()\n .noCache()\n .noStore()\n .maxAge(1.seconds)\n .maxStale(2.seconds)\n .minFresh(3.seconds)\n .onlyIfCached()\n .noTransform()\n .immutable()\n .build()\n assertThat(cacheControl.toString()).isEqualTo(\n \"no-cache, no-store, max-age=1, max-stale=2, min-fresh=3, only-if-cached, no-transform, immutable\",\n )\n assertThat(cacheControl.noCache).isTrue()\n assertThat(cacheControl.noStore).isTrue()\n assertThat(cacheControl.maxAgeSeconds).isEqualTo(1)\n assertThat(cacheControl.maxStaleSeconds).isEqualTo(2)\n assertThat(cacheControl.minFreshSeconds).isEqualTo(3)\n assertThat(cacheControl.onlyIfCached).isTrue()\n assertThat(cacheControl.noTransform).isTrue()\n assertThat(cacheControl.immutable).isTrue()\n\n // These members are accessible to response headers only.\n assertThat(cacheControl.sMaxAgeSeconds).isEqualTo(-1)\n assertThat(cacheControl.isPrivate).isFalse()\n assertThat(cacheControl.isPublic).isFalse()\n assertThat(cacheControl.mustRevalidate).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":46,"symbol":"CacheCorruptionTest","kind":"class","lang":"kotlin","code":"class CacheCorruptionTest {\n var fileSystem = FakeFileSystem()\n\n @JvmField\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @JvmField\n @RegisterExtension\n val platform = PlatformRule()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private lateinit var client: OkHttpClient\n private lateinit var cache: Cache\n private val nullHostnameVerifier = HostnameVerifier { _: String?, _: SSLSession? -> true }\n private val cookieManager = CookieManager()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n server.protocolNegotiationEnabled = false\n val loggingFileSystem = LoggingFilesystem(fileSystem)\n cache = buildCache(\"/cache/\".toPath(), Int.MAX_VALUE.toLong(), loggingFileSystem)\n client =\n clientTestRule\n .newClientBuilder()\n .cache(cache)\n .cookieJar(JavaNetCookieJar(cookieManager))\n .build()\n }\n\n @AfterEach\n fun tearDown() {\n ResponseCache.setDefault(null)\n if (this::cache.isInitialized) {\n cache.delete()\n }\n }\n\n @Test\n fun corruptedCipher() {\n val response =\n testCorruptingCache {\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":66,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n server.protocolNegotiationEnabled = false\n val loggingFileSystem = LoggingFilesystem(fileSystem)\n cache = buildCache(\"/cache/\".toPath(), Int.MAX_VALUE.toLong(), loggingFileSystem)\n client =\n clientTestRule\n .newClientBuilder()\n .cache(cache)\n .cookieJar(JavaNetCookieJar(cookieManager))\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":80,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n ResponseCache.setDefault(null)\n if (this::cache.isInitialized) {\n cache.delete()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":88,"symbol":"corruptedCipher","kind":"function","lang":"kotlin","code":"@Test\n fun corruptedCipher() {\n val response =\n testCorruptingCache {\n corruptMetadata {\n // mess with cipher suite\n it.replace(\"TLS_\", \"SLT_\")\n }\n }\n\n assertThat(response.body.string()).isEqualTo(\"ABC.1\") // cached\n assertThat(cache.requestCount()).isEqualTo(2)\n assertThat(cache.networkCount()).isEqualTo(1)\n assertThat(cache.hitCount()).isEqualTo(1)\n\n assertThat(response.handshake!!.cipherSuite.javaName).startsWith(\"SLT_\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":106,"symbol":"truncatedMetadataEntry","kind":"function","lang":"kotlin","code":"@Test\n fun truncatedMetadataEntry() {\n val response =\n testCorruptingCache {\n corruptMetadata {\n // truncate metadata to 1/4 of length\n it.substring(0, it.length / 4)\n }\n }\n\n assertThat(response.body.string()).isEqualTo(\"ABC.2\") // not cached\n assertThat(cache.requestCount()).isEqualTo(2)\n assertThat(cache.networkCount()).isEqualTo(2)\n assertThat(cache.hitCount()).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":122,"symbol":"corruptedUrl","kind":"function","lang":"kotlin","code":"@Test fun corruptedUrl() {\n val response =\n testCorruptingCache {\n corruptMetadata {\n // strip https scheme\n it.substring(5)\n }\n }\n\n assertThat(response.body.string()).isEqualTo(\"ABC.2\") // not cached\n assertThat(cache.requestCount()).isEqualTo(2)\n assertThat(cache.networkCount()).isEqualTo(2)\n assertThat(cache.hitCount()).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":137,"symbol":"corruptMetadata","kind":"function","lang":"kotlin","code":"private fun corruptMetadata(corruptor: (String) -> String) {\n val metadataFile =\n fileSystem.allPaths.find {\n it.name.endsWith(\".0\")\n }\n\n if (metadataFile != null) {\n val contents =\n fileSystem.read(metadataFile) {\n readUtf8()\n }\n\n fileSystem.write(metadataFile) {\n writeUtf8(corruptor(contents))\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":155,"symbol":"testCorruptingCache","kind":"function","lang":"kotlin","code":"private fun testCorruptingCache(corruptor: () -> Unit): Response {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse(\n headers =\n headersOf(\n \"Last-Modified\",\n formatDate(-1, TimeUnit.HOURS)!!,\n \"Expires\",\n formatDate(1, TimeUnit.HOURS)!!,\n ),\n body = \"ABC.1\",\n ),\n )\n server.enqueue(\n MockResponse(\n headers =\n headersOf(\n \"Last-Modified\",\n formatDate(-1, TimeUnit.HOURS)!!,\n \"Expires\",\n formatDate(1, TimeUnit.HOURS)!!,\n ),\n body = \"ABC.2\",\n ),\n )\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(nullHostnameVerifier)\n .build()\n val request = Request(server.url(\"/\"))\n val response1: Response = client.newCall(request).execute()\n val bodySource = response1.body.source()\n assertThat(bodySource.readUtf8()).isEqualTo(\"ABC.1\")\n\n corruptor()\n\n return client.newCall(request).execute()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":203,"symbol":"formatDate","kind":"function","lang":"kotlin","doc":"@param delta the offset from the current date to use. Negative values yield dates in the past; positive values yield dates in the future.","code":"private fun formatDate(\n delta: Long,\n timeUnit: TimeUnit,\n ): String? = formatDate(Date(System.currentTimeMillis() + timeUnit.toMillis(delta)))"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheCorruptionTest.kt","line":208,"symbol":"formatDate","kind":"function","lang":"kotlin","code":"private fun formatDate(date: Date): String? {\n val rfc1123: DateFormat = SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss zzz\", Locale.US)\n rfc1123.timeZone = TimeZone.getTimeZone(\"GMT\")\n return rfc1123.format(date)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":72,"symbol":"CacheTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slow\")\nclass CacheTest {\n val fileSystem = FakeFileSystem()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @RegisterExtension\n val platform = PlatformRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @StartStop\n private val server2 = MockWebServer()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private lateinit var client: OkHttpClient\n private lateinit var cache: Cache\n private val cookieManager = CookieManager()\n\n @BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n server.protocolNegotiationEnabled = false\n fileSystem.emulateUnix()\n cache = Cache(fileSystem, \"/cache/\".toPath(), Long.MAX_VALUE)\n client =\n clientTestRule\n .newClientBuilder()\n .cache(cache)\n .cookieJar(JavaNetCookieJar(cookieManager))\n .build()\n }\n\n @AfterEach\n fun tearDown() {\n ResponseCache.setDefault(null)\n if (this::cache.isInitialized) {\n cache.delete()\n }\n }\n\n /**\n * Test that response caching is consistent with the RI and the spec.\n * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4\n */\n @Test\n fun responseCachingByResponseCode() "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":93,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n server.protocolNegotiationEnabled = false\n fileSystem.emulateUnix()\n cache = Cache(fileSystem, \"/cache/\".toPath(), Long.MAX_VALUE)\n client =\n clientTestRule\n .newClientBuilder()\n .cache(cache)\n .cookieJar(JavaNetCookieJar(cookieManager))\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":107,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n ResponseCache.setDefault(null)\n if (this::cache.isInitialized) {\n cache.delete()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":119,"symbol":"responseCachingByResponseCode","kind":"function","lang":"kotlin","doc":"Test that response caching is consistent with the RI and the spec. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4","code":"@Test\n fun responseCachingByResponseCode() {\n // Test each documented HTTP/1.1 code, plus the first unused value in each range.\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n\n // We can't test 100 because it's not really a response.\n // assertCached(false, 100);\n assertCached(false, 101)\n assertCached(true, 200)\n assertCached(false, 201)\n assertCached(false, 202)\n assertCached(true, 203)\n assertCached(true, 204)\n assertCached(false, 205)\n assertCached(false, 206) // Electing to not cache partial responses\n assertCached(false, 207)\n assertCached(true, 300)\n assertCached(true, 301)\n assertCached(true, 302)\n assertCached(false, 303)\n assertCached(false, 304)\n assertCached(false, 305)\n assertCached(false, 306)\n assertCached(true, 307)\n assertCached(true, 308)\n assertCached(false, 400)\n assertCached(false, 401)\n assertCached(false, 402)\n assertCached(false, 403)\n assertCached(true, 404)\n assertCached(true, 405)\n assertCached(false, 406)\n assertCached(false, 408)\n assertCached(false, 409)\n // the HTTP spec permits caching 410s, but the RI doesn't.\n assertCached(true, 410)\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":172,"symbol":"responseCachingWith1xxInformationalResponse","kind":"function","lang":"kotlin","code":"@Test\n fun responseCachingWith1xxInformationalResponse() {\n assertSubsequentResponseCached(102, 200)\n assertSubsequentResponseCached(103, 200)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":178,"symbol":"assertCached","kind":"function","lang":"kotlin","code":"private fun assertCached(\n shouldWriteToCache: Boolean,\n responseCode: Int,\n method: String = \"GET\",\n ) {\n var expectedResponseCode = responseCode\n val server = MockWebServer()\n val builder =\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .code(responseCode)\n .body(\"ABCDE\")\n .addHeader(\"WWW-Authenticate: challenge\")\n when (responseCode) {\n HttpURLConnection.HTTP_PROXY_AUTH -> {\n builder.addHeader(\"Proxy-Authenticate: Basic realm=\\\"protected area\\\"\")\n }\n\n HttpURLConnection.HTTP_UNAUTHORIZED -> {\n builder.addHeader(\"WWW-Authenticate: Basic realm=\\\"protected area\\\"\")\n }\n\n HttpURLConnection.HTTP_NO_CONTENT, HttpURLConnection.HTTP_RESET -> {\n builder.body(\"\") // We forbid bodies for 204 and 205.\n }\n }\n server.enqueue(builder.build())\n if (responseCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT) {\n // 408's are a bit of an outlier because we may repeat the request if we encounter this\n // response code. In this scenario, there are 2 responses: the initia"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":242,"symbol":"assertSubsequentResponseCached","kind":"function","lang":"kotlin","code":"private fun assertSubsequentResponseCached(\n initialResponseCode: Int,\n finalResponseCode: Int,\n ) {\n val server = MockWebServer()\n val builder =\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .code(finalResponseCode)\n .body(\"ABCDE\")\n .addInformationalResponse(MockResponse(initialResponseCode))\n server.enqueue(builder.build())\n server.start()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val response = client.newCall(request).execute()\n assertThat(response.code).isEqualTo(finalResponseCode)\n\n // Exhaust the content stream.\n response.body.string()\n val cached = cacheGet(cache, request)\n assertThat(cached).isNotNull()\n cached!!.body.close()\n server.close() // tearDown() isn't sufficient; this test starts multiple servers\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":273,"symbol":"responseCachingAndInputStreamSkipWithFixedLength","kind":"function","lang":"kotlin","code":"@Test\n fun responseCachingAndInputStreamSkipWithFixedLength() {\n testResponseCaching(TransferKind.FIXED_LENGTH)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":278,"symbol":"responseCachingAndInputStreamSkipWithChunkedEncoding","kind":"function","lang":"kotlin","code":"@Test\n fun responseCachingAndInputStreamSkipWithChunkedEncoding() {\n testResponseCaching(TransferKind.CHUNKED)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":283,"symbol":"responseCachingAndInputStreamSkipWithNoLengthHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun responseCachingAndInputStreamSkipWithNoLengthHeaders() {\n testResponseCaching(TransferKind.END_OF_STREAM)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":292,"symbol":"testResponseCaching","kind":"function","lang":"kotlin","doc":"Skipping bytes in the input stream caused ResponseCache corruption. http://code.google.com/p/android/issues/detail?id=8175","code":"private fun testResponseCaching(transferKind: TransferKind) {\n val mockResponse =\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .status(\"HTTP/1.1 200 Fantastic\")\n transferKind.setBody(mockResponse, \"I love puppies but hate spiders\", 1)\n server.enqueue(mockResponse.build())\n\n // Make sure that calling skip() doesn't omit bytes from the cache.\n val request = Request.Builder().url(server.url(\"/\")).build()\n val response1 = client.newCall(request).execute()\n val in1 = response1.body.source()\n assertThat(in1.readUtf8(\"I love \".length.toLong())).isEqualTo(\"I love \")\n in1.skip(\"puppies but hate \".length.toLong())\n assertThat(in1.readUtf8(\"spiders\".length.toLong())).isEqualTo(\"spiders\")\n assertThat(in1.exhausted()).isTrue()\n in1.close()\n assertThat(cache.writeSuccessCount()).isEqualTo(1)\n assertThat(cache.writeAbortCount()).isEqualTo(0)\n val response2 = client.newCall(request).execute()\n val in2 = response2.body.source()\n assertThat(in2.readUtf8(\"I love puppies but hate spiders\".length.toLong()))\n .isEq"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":329,"symbol":"secureResponseCaching","kind":"function","lang":"kotlin","code":"@Test\n fun secureResponseCaching() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .body(\"ABC\")\n .build(),\n )\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(NULL_HOSTNAME_VERIFIER)\n .build()\n val request = Request.Builder().url(server.url(\"/\")).build()\n val response1 = client.newCall(request).execute()\n val source = response1.body.source()\n assertThat(source.readUtf8()).isEqualTo(\"ABC\")\n\n // OpenJDK 6 fails on this line, complaining that the connection isn't open yet\n val cipherSuite = response1.handshake!!.cipherSuite\n val localCerts = response1.handshake.localCertificates\n val serverCerts = response1.handshake.peerCertificates\n val peerPrincipal = response1.handshake.peerPrincipal\n val localPrincipal = response1.handshake.localPrincipal\n val response2 = client.newCal"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":371,"symbol":"secureResponseCachingWithCorruption","kind":"function","lang":"kotlin","code":"@Test\n fun secureResponseCachingWithCorruption() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .body(\"ABC\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-5, TimeUnit.MINUTES))\n .addHeader(\"Expires: \" + formatDate(2, TimeUnit.HOURS))\n .body(\"DEF\")\n .build(),\n )\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(NULL_HOSTNAME_VERIFIER)\n .build()\n val request = Request.Builder().url(server.url(\"/\")).build()\n val response1 = client.newCall(request).execute()\n assertThat(response1.body.string()).isEqualTo(\"ABC\")\n val cacheEntry =\n fileSystem.allPaths\n .stream()\n .filter { e: Path -> e.name.endsWith(\".0\") }\n .findFirst()\n .orElseThrow { NoSuchElementException() }\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":415,"symbol":"corruptCertificate","kind":"function","lang":"kotlin","code":"private fun corruptCertificate(cacheEntry: Path) {\n var content = fileSystem.source(cacheEntry).buffer().readUtf8()\n content = content.replace(\"MII\", \"!!!\")\n fileSystem\n .sink(cacheEntry)\n .buffer()\n .writeUtf8(content)\n .close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":432,"symbol":"httpsResponseWithNullHandshakeDoesNotCrashWriteTo","kind":"function","lang":"kotlin","doc":"A network interceptor strips the handshake from a real HTTPS response before the CacheInterceptor writes it to disk. This creates the bug condition: url.isHttps=true but handshake=null. Before the fix, `handshake!!` in writeTo() threw NPE. https://github.com/lysine-dev/okhttp/issues/8962","code":"@Test\n fun httpsResponseWithNullHandshakeDoesNotCrashWriteTo() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"secure content\")\n .addHeader(\"Cache-Control\", \"max-age=3600\")\n .build(),\n )\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(NULL_HOSTNAME_VERIFIER)\n .addNetworkInterceptor { chain ->\n chain\n .proceed(chain.request())\n .newBuilder()\n .handshake(null)\n .build()\n }.build()\n\n val response = client.newCall(Request(server.url(\"/\"))).execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"secure content\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":469,"symbol":"multipleHttpsRequestsWithNullHandshakeAllSucceed","kind":"function","lang":"kotlin","doc":"Verifies the null-handshake fix holds across multiple sequential cache writes, confirming it is not a one-time race condition. https://github.com/lysine-dev/okhttp/issues/8962","code":"@Test\n fun multipleHttpsRequestsWithNullHandshakeAllSucceed() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n repeat(3) {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"response $it\")\n .addHeader(\"Cache-Control\", \"max-age=3600\")\n .build(),\n )\n }\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(NULL_HOSTNAME_VERIFIER)\n .addNetworkInterceptor { chain ->\n chain\n .proceed(chain.request())\n .newBuilder()\n .handshake(null)\n .build()\n }.build()\n\n repeat(3) { i ->\n val response = client.newCall(Request(server.url(\"/path$i\"))).execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"response $i\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":511,"symbol":"httpsResponseWithNullHandshakeIsNotServedFromCache","kind":"function","lang":"kotlin","doc":"When handshake is null for an HTTPS URL, the TLS block is skipped making the entry unreadable on re-read. The response should still succeed but won't be served from cache on subsequent requests. https://github.com/lysine-dev/okhttp/issues/8962","code":"@Test\n fun httpsResponseWithNullHandshakeIsNotServedFromCache() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"first\")\n .addHeader(\"Cache-Control\", \"max-age=3600\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"second\")\n .addHeader(\"Cache-Control\", \"max-age=3600\")\n .build(),\n )\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(NULL_HOSTNAME_VERIFIER)\n .addNetworkInterceptor { chain ->\n chain\n .proceed(chain.request())\n .newBuilder()\n .handshake(null)\n .build()\n }.build()\n\n val response1 = client.newCall(Request(server.url(\"/\"))).execute()\n assertThat(response1.body.string()).isEqualTo(\"first\")\n\n // Second request hits the network again because the first entry was not cacheable\n val response2 = client.newCall(Request(server.url(\"/\"))).execute()\n assertThat(response2.body.string()).isEqualTo(\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":553,"symbol":"responseCachingAndRedirects","kind":"function","lang":"kotlin","code":"@Test\n fun responseCachingAndRedirects() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .code(HttpURLConnection.HTTP_MOVED_PERM)\n .addHeader(\"Location: /foo\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .body(\"ABC\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"DEF\")\n .build(),\n )\n val request = Request.Builder().url(server.url(\"/\")).build()\n val response1 = client.newCall(request).execute()\n assertThat(response1.body.string()).isEqualTo(\"ABC\")\n val response2 = client.newCall(request).execute() // Cached!\n assertThat(response2.body.string()).isEqualTo(\"ABC\")\n\n // 2 requests + 2 redirects\n assertThat(cache.requestCount()).isEqualTo(4)\n assertThat(cache.networkCount()).isEqualTo(2)\n assertThat(cache.hitCount()).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":590,"symbol":"redirectToCachedResult","kind":"function","lang":"kotlin","code":"@Test\n fun redirectToCachedResult() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .body(\"ABC\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_MOVED_PERM)\n .addHeader(\"Location: /foo\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"DEF\")\n .build(),\n )\n val request1 = Request.Builder().url(server.url(\"/foo\")).build()\n val response1 = client.newCall(request1).execute()\n assertThat(response1.body.string()).isEqualTo(\"ABC\")\n val recordedRequest1 = server.takeRequest()\n assertThat(recordedRequest1.requestLine).isEqualTo(\"GET /foo HTTP/1.1\")\n assertThat(recordedRequest1.connectionIndex).isEqualTo(0)\n assertThat(recordedRequest1.exchangeIndex).isEqualTo(0)\n val request2 = Request.Builder().url(server.url(\"/bar\")).build()\n val response2 = client.newCall(request2).execute()\n assertThat(response2.body.string()).isEqualTo(\"ABC\")\n val recordedRequest2 = server.takeRequest()\n assertThat(recordedRequest2.requestLine).isEqualTo(\"GET /bar HTTP/1.1\")\n ass"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":637,"symbol":"getAndQueryRedirectToCachedResultIndependently","kind":"function","lang":"kotlin","code":"@Test\n fun getAndQueryRedirectToCachedResultIndependently() {\n // GET responses\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .body(\"ABC\")\n .build(),\n )\n // QUERY responses\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .body(\"DEF\")\n .build(),\n )\n\n val requestGet1 =\n Request\n .Builder()\n .url(server.url(\"/foo\"))\n .get()\n .build()\n val response1 = client.newCall(requestGet1).execute()\n assertThat(response1.body.string()).isEqualTo(\"ABC\")\n val recordedRequest1 = server.takeRequest()\n assertThat(recordedRequest1.requestLine).isEqualTo(\"GET /foo HTTP/1.1\")\n\n val requestQuery1 =\n Request\n .Builder()\n .url(server.url(\"/foo\"))\n .query(RequestBody.EMPTY)\n .build()\n val response2 = client.newCall(requestQuery1).execute()\n assertThat(response2.body.string()).isEqualTo(\"DEF\")\n val recordedRequest2 = server.takeRequest()\n assertThat(recordedRequest2.requestLine).isEqualTo(\"QUERY /foo HTTP/1.1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":679,"symbol":"queryRequestsCacheTheBodyWithCacheUrlOverride","kind":"function","lang":"kotlin","code":"@Test\n fun queryRequestsCacheTheBodyWithCacheUrlOverride() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .body(\"ABC\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .body(\"DEF\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .body(\"DEFa\")\n .build(),\n )\n\n val url = server.url(\"/same\")\n\n // First QUERY request with body \"foo\"\n val request1 =\n Request\n .Builder()\n .url(url)\n .query(\"foo\".toRequestBody())\n .cacheUrlOverride(url.newBuilder().addQueryParameter(\"body\", \"foo\").build())\n .build()\n val response1 = client.newCall(request1).execute()\n assertThat(response1.body.string()).isEqualTo(\"ABC\")\n\n // Second QUERY request with body \"bar\"\n val request2 =\n Request\n .Builder()\n .url(url)\n .query(\"bar\".toRequestBody())\n .cacheUrlOverride(url.newBuilder().addQueryParameter(\"body\", \"bar\").build())\n .build()\n val response2 = client.n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":746,"symbol":"oneshotBodyIsNotCachedForQueryRequest","kind":"function","lang":"kotlin","code":"@Test\n fun oneshotBodyIsNotCachedForQueryRequest() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .body(\"ABC1\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .body(\"ABC2\")\n .build(),\n )\n\n val url = server.url(\"/same\")\n\n // QUERY request with body \"foo\"\n val body = \"foo\"\n\n val request1 =\n Request\n .Builder()\n .url(url)\n .query(body.toOneShotRequestBody())\n .build()\n val response1 = client.newCall(request1).execute()\n assertThat(response1.body.string()).isEqualTo(\"ABC1\")\n\n // QUERY request with body \"foo\" again, should not be cached\n val request2 =\n Request\n .Builder()\n .url(url)\n .query(body.toOneShotRequestBody())\n .build()\n val response2 = client.newCall(request2).execute()\n assertThat(response2.body.string()).isEqualTo(\"ABC2\")\n\n // Check that the cache did not store the response\n assertThat(cache.requestCount()).isEqualTo(2)\n assertThat(cache.hitCount()).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":792,"symbol":"toOneShotRequestBody","kind":"function","lang":"kotlin","code":"private fun String.toOneShotRequestBody(): RequestBody =\n object : RequestBody() {\n val internalBody = Stream.of(this)\n\n override fun isOneShot(): Boolean = true\n\n override fun contentType(): MediaType? = \"application/text-plain\".toMediaTypeOrNull()\n\n override fun writeTo(sink: BufferedSink) {\n internalBody.forEach { _ ->\n sink.writeUtf8(this@toOneShotRequestBody)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":796,"symbol":"isOneShot","kind":"function","lang":"kotlin","code":"override fun isOneShot(): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":798,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = \"application/text-plain\".toMediaTypeOrNull()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":800,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n internalBody.forEach { _ ->\n sink.writeUtf8(this@toOneShotRequestBody)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":807,"symbol":"secureResponseCachingAndRedirects","kind":"function","lang":"kotlin","code":"@Test\n fun secureResponseCachingAndRedirects() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .code(HttpURLConnection.HTTP_MOVED_PERM)\n .addHeader(\"Location: /foo\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .body(\"ABC\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"DEF\")\n .build(),\n )\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(NULL_HOSTNAME_VERIFIER)\n .build()\n val response1 = get(server.url(\"/\"))\n assertThat(response1.body.string()).isEqualTo(\"ABC\")\n assertThat(response1.handshake!!.cipherSuite).isNotNull()\n\n // Cached!\n val response2 = get(ser"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":865,"symbol":"secureResponseCachingAndProtocolRedirects","kind":"function","lang":"kotlin","doc":"We've had bugs where caching and cross-protocol redirects yield class cast exceptions internal to the cache because we incorrectly assumed that HttpsURLConnection was always HTTPS and HttpURLConnection was always HTTP; in practice redirects mean that each can do either. https://github.com/lysine-dev/okhttp/issues/214","code":"@Test\n fun secureResponseCachingAndProtocolRedirects() {\n server2.useHttps(handshakeCertificates.sslSocketFactory())\n server2.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .body(\"ABC\")\n .build(),\n )\n server2.enqueue(\n MockResponse\n .Builder()\n .body(\"DEF\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .code(HttpURLConnection.HTTP_MOVED_PERM)\n .addHeader(\"Location: \" + server2.url(\"/\"))\n .build(),\n )\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(NULL_HOSTNAME_VERIFIER)\n .build()\n val response1 = get(server.url(\"/\"))\n assertThat(response1.body.string()).isEqualTo(\"ABC\")\n\n // Cached!\n val response2 = get(server.url(\"/\"))\n assertThat(respons"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":911,"symbol":"foundCachedWithExpiresHeader","kind":"function","lang":"kotlin","code":"@Test\n fun foundCachedWithExpiresHeader() {\n temporaryRedirectCachedWithCachingHeader(302, \"Expires\", formatDate(1, TimeUnit.HOURS))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":916,"symbol":"foundCachedWithCacheControlHeader","kind":"function","lang":"kotlin","code":"@Test\n fun foundCachedWithCacheControlHeader() {\n temporaryRedirectCachedWithCachingHeader(302, \"Cache-Control\", \"max-age=60\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":921,"symbol":"temporaryRedirectCachedWithExpiresHeader","kind":"function","lang":"kotlin","code":"@Test\n fun temporaryRedirectCachedWithExpiresHeader() {\n temporaryRedirectCachedWithCachingHeader(307, \"Expires\", formatDate(1, TimeUnit.HOURS))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":926,"symbol":"temporaryRedirectCachedWithCacheControlHeader","kind":"function","lang":"kotlin","code":"@Test\n fun temporaryRedirectCachedWithCacheControlHeader() {\n temporaryRedirectCachedWithCachingHeader(307, \"Cache-Control\", \"max-age=60\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":931,"symbol":"foundNotCachedWithoutCacheHeader","kind":"function","lang":"kotlin","code":"@Test\n fun foundNotCachedWithoutCacheHeader() {\n temporaryRedirectNotCachedWithoutCachingHeader(302)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":936,"symbol":"temporaryRedirectNotCachedWithoutCacheHeader","kind":"function","lang":"kotlin","code":"@Test\n fun temporaryRedirectNotCachedWithoutCacheHeader() {\n temporaryRedirectNotCachedWithoutCachingHeader(307)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":941,"symbol":"temporaryRedirectCachedWithCachingHeader","kind":"function","lang":"kotlin","code":"private fun temporaryRedirectCachedWithCachingHeader(\n responseCode: Int,\n headerName: String,\n headerValue: String,\n ) {\n server.enqueue(\n MockResponse\n .Builder()\n .code(responseCode)\n .addHeader(headerName, headerValue)\n .addHeader(\"Location\", \"/a\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(headerName, headerValue)\n .body(\"a\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"b\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"c\")\n .build(),\n )\n val url = server.url(\"/\")\n assertThat(get(url).body.string()).isEqualTo(\"a\")\n assertThat(get(url).body.string()).isEqualTo(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":978,"symbol":"temporaryRedirectNotCachedWithoutCachingHeader","kind":"function","lang":"kotlin","code":"private fun temporaryRedirectNotCachedWithoutCachingHeader(responseCode: Int) {\n server.enqueue(\n MockResponse\n .Builder()\n .code(responseCode)\n .addHeader(\"Location\", \"/a\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"a\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"b\")\n .build(),\n )\n val url = server.url(\"/\")\n assertThat(get(url).body.string()).isEqualTo(\"a\")\n assertThat(get(url).body.string()).isEqualTo(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1004,"symbol":"cachedRedirect","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/2198","code":"@Test\n fun cachedRedirect() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .addHeader(\"Cache-Control: max-age=60\")\n .addHeader(\"Location: /bar\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"ABC\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"ABC\")\n .build(),\n )\n val request1 = Request.Builder().url(server.url(\"/\")).build()\n val response1 = client.newCall(request1).execute()\n assertThat(response1.body.string()).isEqualTo(\"ABC\")\n val request2 = Request.Builder().url(server.url(\"/\")).build()\n val response2 = client.newCall(request2).execute()\n assertThat(response2.body.string()).isEqualTo(\"ABC\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1034,"symbol":"serverDisconnectsPrematurelyWithContentLengthHeader","kind":"function","lang":"kotlin","code":"@Test\n fun serverDisconnectsPrematurelyWithContentLengthHeader() {\n testServerPrematureDisconnect(TransferKind.FIXED_LENGTH)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1039,"symbol":"serverDisconnectsPrematurelyWithChunkedEncoding","kind":"function","lang":"kotlin","code":"@Test\n fun serverDisconnectsPrematurelyWithChunkedEncoding() {\n testServerPrematureDisconnect(TransferKind.CHUNKED)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1044,"symbol":"serverDisconnectsPrematurelyWithNoLengthHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun serverDisconnectsPrematurelyWithNoLengthHeaders() {\n // Intentionally empty. This case doesn't make sense because there's no\n // such thing as a premature disconnect when the disconnect itself\n // indicates the end of the data stream.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1051,"symbol":"testServerPrematureDisconnect","kind":"function","lang":"kotlin","code":"private fun testServerPrematureDisconnect(transferKind: TransferKind) {\n val mockResponse = MockResponse.Builder()\n transferKind.setBody(mockResponse, \"ABCDE\\nFGHIJKLMNOPQRSTUVWXYZ\", 16)\n server.enqueue(truncateViolently(mockResponse, 16).build())\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Request #2\")\n .build(),\n )\n val bodySource = get(server.url(\"/\")).body.source()\n assertThat(bodySource.readUtf8Line()).isEqualTo(\"ABCDE\")\n bodySource.use {\n assertFailsWith {\n bodySource.readUtf8(21)\n }\n }\n assertThat(cache.writeAbortCount()).isEqualTo(1)\n assertThat(cache.writeSuccessCount()).isEqualTo(0)\n val response = get(server.url(\"/\"))\n assertThat(response.body.string()).isEqualTo(\"Request #2\")\n assertThat(cache.writeAbortCount()).isEqualTo(1)\n assertThat(cache.writeSuccessCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1076,"symbol":"clientPrematureDisconnectWithContentLengthHeader","kind":"function","lang":"kotlin","code":"@Test\n fun clientPrematureDisconnectWithContentLengthHeader() {\n testClientPrematureDisconnect(TransferKind.FIXED_LENGTH)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1081,"symbol":"clientPrematureDisconnectWithChunkedEncoding","kind":"function","lang":"kotlin","code":"@Test\n fun clientPrematureDisconnectWithChunkedEncoding() {\n testClientPrematureDisconnect(TransferKind.CHUNKED)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1086,"symbol":"clientPrematureDisconnectWithNoLengthHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun clientPrematureDisconnectWithNoLengthHeaders() {\n testClientPrematureDisconnect(TransferKind.END_OF_STREAM)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1091,"symbol":"testClientPrematureDisconnect","kind":"function","lang":"kotlin","code":"private fun testClientPrematureDisconnect(transferKind: TransferKind) {\n // Setting a low transfer speed ensures that stream discarding will time out.\n val builder =\n MockResponse\n .Builder()\n .throttleBody(6, 1, TimeUnit.SECONDS)\n transferKind.setBody(builder, \"ABCDE\\nFGHIJKLMNOPQRSTUVWXYZ\", 1024)\n server.enqueue(builder.build())\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Request #2\")\n .build(),\n )\n val response1 = get(server.url(\"/\"))\n val source = response1.body.source()\n assertThat(source.readUtf8(5)).isEqualTo(\"ABCDE\")\n source.close()\n assertFailsWith {\n source.readByte()\n }\n assertThat(cache.writeAbortCount()).isEqualTo(1)\n assertThat(cache.writeSuccessCount()).isEqualTo(0)\n val response2 = get(server.url(\"/\"))\n assertThat(response2.body.string()).isEqualTo(\"Request #2\")\n assertThat(cache.writeAbortCount()).isEqualTo(1)\n assertThat(cache.writeSuccessCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1120,"symbol":"defaultExpirationDateFullyCachedForLessThan24Hours","kind":"function","lang":"kotlin","code":"@Test\n fun defaultExpirationDateFullyCachedForLessThan24Hours() {\n // last modified: 105 seconds ago\n // served: 5 seconds ago\n // default lifetime: (105 - 5) / 10 = 10 seconds\n // expires: 10 seconds from served date = 5 seconds from now\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-105, TimeUnit.SECONDS))\n .addHeader(\"Date: \" + formatDate(-5, TimeUnit.SECONDS))\n .body(\"A\")\n .build(),\n )\n val url = server.url(\"/\")\n val response1 = get(url)\n assertThat(response1.body.string()).isEqualTo(\"A\")\n val response2 = get(url)\n assertThat(response2.body.string()).isEqualTo(\"A\")\n assertThat(response2.header(\"Warning\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1142,"symbol":"defaultExpirationDateConditionallyCached","kind":"function","lang":"kotlin","code":"@Test\n fun defaultExpirationDateConditionallyCached() {\n // last modified: 115 seconds ago\n // served: 15 seconds ago\n // default lifetime: (115 - 15) / 10 = 10 seconds\n // expires: 10 seconds from served date = 5 seconds ago\n val lastModifiedDate = formatDate(-115, TimeUnit.SECONDS)\n val conditionalRequest =\n assertConditionallyCached(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: $lastModifiedDate\")\n .addHeader(\"Date: \" + formatDate(-15, TimeUnit.SECONDS))\n .build(),\n )\n assertThat(conditionalRequest.headers[\"If-Modified-Since\"])\n .isEqualTo(lastModifiedDate)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1161,"symbol":"defaultExpirationDateFullyCachedForMoreThan24Hours","kind":"function","lang":"kotlin","code":"@Test\n fun defaultExpirationDateFullyCachedForMoreThan24Hours() {\n // last modified: 105 days ago\n // served: 5 days ago\n // default lifetime: (105 - 5) / 10 = 10 days\n // expires: 10 days from served date = 5 days from now\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-105, TimeUnit.DAYS))\n .addHeader(\"Date: \" + formatDate(-5, TimeUnit.DAYS))\n .body(\"A\")\n .build(),\n )\n assertThat(get(server.url(\"/\")).body.string()).isEqualTo(\"A\")\n val response = get(server.url(\"/\"))\n assertThat(response.body.string()).isEqualTo(\"A\")\n assertThat(response.header(\"Warning\")).isEqualTo(\n \"113 HttpURLConnection \\\"Heuristic expiration\\\"\",\n )\n }\n\n @Test\n fun noDefaultExpirationForUrlsWithQueryString() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-105, TimeUnit.SECONDS))\n .addHeader(\"Date: \" + formatDate(-5, TimeUnit.SECONDS))\n .body(\"A\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"B\")\n .build(),\n )\n val url =\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1209,"symbol":"expirationDateInThePastWithLastModifiedHeader","kind":"function","lang":"kotlin","code":"@Test\n fun expirationDateInThePastWithLastModifiedHeader() {\n val lastModifiedDate = formatDate(-2, TimeUnit.HOURS)\n val conditionalRequest =\n assertConditionallyCached(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: $lastModifiedDate\")\n .addHeader(\"Expires: \" + formatDate(-1, TimeUnit.HOURS))\n .build(),\n )\n assertThat(conditionalRequest.headers[\"If-Modified-Since\"])\n .isEqualTo(lastModifiedDate)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1224,"symbol":"expirationDateInThePastWithNoLastModifiedHeader","kind":"function","lang":"kotlin","code":"@Test\n fun expirationDateInThePastWithNoLastModifiedHeader() {\n assertNotCached(\n MockResponse\n .Builder()\n .addHeader(\"Expires: \" + formatDate(-1, TimeUnit.HOURS))\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1234,"symbol":"expirationDateInTheFuture","kind":"function","lang":"kotlin","code":"@Test\n fun expirationDateInTheFuture() {\n assertFullyCached(\n MockResponse\n .Builder()\n .addHeader(\"Expires: \" + formatDate(1, TimeUnit.HOURS))\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1244,"symbol":"maxAgePreferredWithMaxAgeAndExpires","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgePreferredWithMaxAgeAndExpires() {\n assertFullyCached(\n MockResponse\n .Builder()\n .addHeader(\"Date: \" + formatDate(0, TimeUnit.HOURS))\n .addHeader(\"Expires: \" + formatDate(-1, TimeUnit.HOURS))\n .addHeader(\"Cache-Control: max-age=60\")\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1256,"symbol":"maxAgeInThePastWithDateAndLastModifiedHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgeInThePastWithDateAndLastModifiedHeaders() {\n val lastModifiedDate = formatDate(-2, TimeUnit.HOURS)\n val conditionalRequest =\n assertConditionallyCached(\n MockResponse\n .Builder()\n .addHeader(\"Date: \" + formatDate(-120, TimeUnit.SECONDS))\n .addHeader(\"Last-Modified: $lastModifiedDate\")\n .addHeader(\"Cache-Control: max-age=60\")\n .build(),\n )\n assertThat(conditionalRequest.headers[\"If-Modified-Since\"])\n .isEqualTo(lastModifiedDate)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1272,"symbol":"maxAgeInThePastWithDateHeaderButNoLastModifiedHeader","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgeInThePastWithDateHeaderButNoLastModifiedHeader() {\n // Chrome interprets max-age relative to the local clock. Both our cache\n // and Firefox both use the earlier of the local and server's clock.\n assertNotCached(\n MockResponse\n .Builder()\n .addHeader(\"Date: \" + formatDate(-120, TimeUnit.SECONDS))\n .addHeader(\"Cache-Control: max-age=60\")\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1285,"symbol":"maxAgeInTheFutureWithDateHeader","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgeInTheFutureWithDateHeader() {\n assertFullyCached(\n MockResponse\n .Builder()\n .addHeader(\"Date: \" + formatDate(0, TimeUnit.HOURS))\n .addHeader(\"Cache-Control: max-age=60\")\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1296,"symbol":"maxAgeInTheFutureWithNoDateHeader","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgeInTheFutureWithNoDateHeader() {\n assertFullyCached(\n MockResponse\n .Builder()\n .addHeader(\"Cache-Control: max-age=60\")\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1306,"symbol":"maxAgeWithLastModifiedButNoServedDate","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgeWithLastModifiedButNoServedDate() {\n assertFullyCached(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-120, TimeUnit.SECONDS))\n .addHeader(\"Cache-Control: max-age=60\")\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1317,"symbol":"maxAgeInTheFutureWithDateAndLastModifiedHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgeInTheFutureWithDateAndLastModifiedHeaders() {\n assertFullyCached(\n MockResponse\n .Builder()\n .addHeader(\"Last-Modified: \" + formatDate(-120, TimeUnit.SECONDS))\n .addHeader(\"Date: \" + formatDate(0, TimeUnit.SECONDS))\n .addHeader(\"Cache-Control: max-age=60\")\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1329,"symbol":"maxAgePreferredOverLowerSharedMaxAge","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgePreferredOverLowerSharedMaxAge() {\n assertFullyCached(\n MockResponse\n .Builder()\n .addHeader(\"Date: \" + formatDate(-2, TimeUnit.MINUTES))\n .addHeader(\"Cache-Control: s-maxage=60\")\n .addHeader(\"Cache-Control: max-age=180\")\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CacheTest.kt","line":1341,"symbol":"maxAgePreferredOverHigherMaxAge","kind":"function","lang":"kotlin","code":"@Test\n fun maxAgePreferredOverHigherMaxAge() {\n assertNotCached(\n MockResponse\n .Builder()\n .addHeader(\"Date: \" + formatDate(-2, TimeUnit.MINUTES))\n .addHeader(\"Cache-Control: s-maxage=180\")\n .addHeader(\"Cache-Control: max-age=60\")\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":43,"symbol":"CallHandshakeTest","kind":"class","lang":"kotlin","code":"class CallHandshakeTest {\n private lateinit var client: OkHttpClient\n\n @StartStop\n private val server = MockWebServer()\n\n @RegisterExtension\n @JvmField\n val clientTestRule = OkHttpClientTestRule()\n\n @RegisterExtension\n @JvmField\n var platform = PlatformRule()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n\n /** Ciphers in order we observed directly on the socket. */\n private lateinit var handshakeEnabledCipherSuites: List\n\n /** Ciphers in order we observed on sslSocketFactory defaults. */\n private lateinit var defaultEnabledCipherSuites: List\n\n /** Ciphers in order we observed on sslSocketFactory supported. */\n private lateinit var defaultSupportedCipherSuites: List\n\n val expectedModernTls12CipherSuites =\n listOf(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384)\n val expectedModernTls13CipherSuites = listOf(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384)\n\n @BeforeEach\n fun setup() {\n server.enqueue(MockResponse())\n\n client =\n clientTestRule\n .newClientBuilder()\n .ssl"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":72,"symbol":"setup","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setup() {\n server.enqueue(MockResponse())\n\n client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n\n defaultEnabledCipherSuites =\n handshakeCertificates.sslSocketFactory().defaultCipherSuites.toList()\n defaultSupportedCipherSuites =\n handshakeCertificates.sslSocketFactory().supportedCipherSuites.toList()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":92,"symbol":"testDefaultHandshakeCipherSuiteOrderingTls12Restricted","kind":"function","lang":"kotlin","code":"@Test\n fun testDefaultHandshakeCipherSuiteOrderingTls12Restricted() {\n // We are avoiding making guarantees on ordering of secondary Platforms.\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n\n val client = makeClient(ConnectionSpec.RESTRICTED_TLS, TlsVersion.TLS_1_2)\n\n val handshake = makeRequest(client)\n\n assertThat(handshake.cipherSuite).isIn(*expectedModernTls12CipherSuites.toTypedArray())\n\n // Probably something like\n // TLS_AES_128_GCM_SHA256\n // TLS_AES_256_GCM_SHA384\n // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\n // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\n // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n assertThat(handshakeEnabledCipherSuites).containsExactly(\n *expectedConnectionCipherSuites(client).toTypedArray(),\n )\n assertThat(handshake.tlsVersion).isEqualTo(TlsVersion.TLS_1_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":117,"symbol":"testDefaultHandshakeCipherSuiteOrderingTls12Modern","kind":"function","lang":"kotlin","code":"@Test\n fun testDefaultHandshakeCipherSuiteOrderingTls12Modern() {\n // We are avoiding making guarantees on ordering of secondary Platforms.\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n\n val client = makeClient(ConnectionSpec.MODERN_TLS, TlsVersion.TLS_1_2)\n\n val handshake = makeRequest(client)\n\n assertThat(handshake.cipherSuite).isIn(*expectedModernTls12CipherSuites.toTypedArray())\n\n // Probably something like\n // TLS_AES_128_GCM_SHA256\n // TLS_AES_256_GCM_SHA384\n // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\n // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\n // TLS_RSA_WITH_AES_256_GCM_SHA384\n // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n // TLS_RSA_WITH_AES_128_GCM_SHA256\n // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\n // TLS_RSA_WITH_AES_256_CBC_SHA\n // TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\n // TLS_RSA_WITH_AES_128_CBC_SHA\n assertThat(handshakeEnabledCipherSuites).containsExactly(\n *expectedConnectionCipherSuites(client).toTypedArray(),\n )\n assertThat(handshake.tlsVersion).isEqualTo(TlsVersion.TLS_1_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":148,"symbol":"testDefaultHandshakeCipherSuiteOrderingTls13Modern","kind":"function","lang":"kotlin","code":"@Test\n fun testDefaultHandshakeCipherSuiteOrderingTls13Modern() {\n // We are avoiding making guarantees on ordering of secondary Platforms.\n platform.assumeNotBouncyCastle()\n\n val client = makeClient(ConnectionSpec.MODERN_TLS, TlsVersion.TLS_1_3)\n\n val handshake = makeRequest(client)\n\n assertThat(handshake.cipherSuite).isIn(*expectedModernTls13CipherSuites.toTypedArray())\n\n // TODO: filter down to TLSv1.3 when only activated.\n // Probably something like\n // TLS_AES_128_GCM_SHA256\n // TLS_AES_256_GCM_SHA384\n // TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\n // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n // TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384\n // TLS_RSA_WITH_AES_256_GCM_SHA384\n // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n // TLS_RSA_WITH_AES_128_GCM_SHA256\n // TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA\n // TLS_RSA_WITH_AES_256_CBC_SHA\n // TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\n // TLS_RSA_WITH_AES_128_CBC_SHA\n assertThat(handshakeEnabledCipherSuites).containsExactly(\n *expectedConnectionCipherSuites(client).toTypedArray(),\n )\n assertThat(handshake.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":179,"symbol":"testHandshakeCipherSuiteOrderingWhenReversed","kind":"function","lang":"kotlin","code":"@Test\n fun testHandshakeCipherSuiteOrderingWhenReversed() {\n // We are avoiding making guarantees on ordering of secondary Platforms.\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n\n val reversed = ConnectionSpec.COMPATIBLE_TLS.cipherSuites!!.reversed()\n val client =\n makeClient(\n ConnectionSpec.COMPATIBLE_TLS,\n TlsVersion.TLS_1_2,\n reversed,\n )\n\n makeRequest(client)\n\n val expectedConnectionCipherSuites = expectedConnectionCipherSuites(client)\n // Will choose a poor cipher suite but not plaintext.\n// assertThat(handshake.cipherSuite).isEqualTo(\"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\")\n assertThat(handshakeEnabledCipherSuites).containsExactly(\n *expectedConnectionCipherSuites.toTypedArray(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":203,"symbol":"clientOrderApplied","kind":"function","lang":"kotlin","code":"@Test\n fun clientOrderApplied() {\n// // Flaky in CI\n// // CallHandshakeTest[jvm] > defaultOrderMaintained()[jvm] FAILED\n// // org.bouncycastle.tls.TlsFatalAlertReceived: handshake_failure(40)\n// platform.assumeNotBouncyCastle()\n\n val client = makeClient()\n makeRequest(client)\n\n // As of OkHttp 5 we now apply the ordering from the OkHttpClient, which defaults to MODERN_TLS\n // Clients might need a changed order, but can at least define a preferred order to override that default.\n val socketOrderedByDefaults =\n handshakeEnabledCipherSuites.sortedBy { ConnectionSpec.MODERN_TLS.cipherSuitesAsString!!.indexOf(it) }\n\n assertThat(handshakeEnabledCipherSuites).containsExactly(\n *socketOrderedByDefaults.toTypedArray(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":223,"symbol":"advertisedOrderInRestricted","kind":"function","lang":"kotlin","code":"@Test\n fun advertisedOrderInRestricted() {\n assertThat(ConnectionSpec.RESTRICTED_TLS.cipherSuites!!).containsExactly(\n TLS_AES_128_GCM_SHA256,\n TLS_AES_256_GCM_SHA384,\n TLS_CHACHA20_POLY1305_SHA256,\n TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,\n TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":238,"symbol":"effectiveOrderInRestrictedJdk11","kind":"function","lang":"kotlin","code":"@Test\n fun effectiveOrderInRestrictedJdk11() {\n platform.assumeJdkVersion(11)\n // We are avoiding making guarantees on ordering of secondary Platforms.\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n\n val platform = Platform.get()\n val platformDefaultCipherSuites =\n platform.newSslSocketFactory(platform.platformTrustManager()).defaultCipherSuites\n val cipherSuites =\n ConnectionSpec.RESTRICTED_TLS.effectiveCipherSuites(platformDefaultCipherSuites)\n\n if (cipherSuites.contains(TLS_CHACHA20_POLY1305_SHA256.javaName)) {\n assertThat(cipherSuites).containsExactly(\n TLS_AES_128_GCM_SHA256.javaName,\n TLS_AES_256_GCM_SHA384.javaName,\n TLS_CHACHA20_POLY1305_SHA256.javaName,\n TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256.javaName,\n TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384.javaName,\n TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384.javaName,\n TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256.javaName,\n TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256.javaName,\n )\n } else {\n assertThat(cipherSuites).containsExactly(\n TLS_AES_128_GCM_SH"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":275,"symbol":"expectedConnectionCipherSuites","kind":"function","lang":"kotlin","code":"private fun expectedConnectionCipherSuites(client: OkHttpClient): Set =\n client.connectionSpecs\n .first()\n .cipherSuites!!\n .map {\n it.javaName\n }.intersect(defaultEnabledCipherSuites.toSet())"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":283,"symbol":"makeClient","kind":"function","lang":"kotlin","code":"private fun makeClient(\n connectionSpec: ConnectionSpec? = null,\n tlsVersion: TlsVersion? = null,\n cipherSuites: List? = null,\n ): OkHttpClient =\n this.client\n .newBuilder()\n .apply {\n if (connectionSpec != null) {\n connectionSpecs(\n listOf(\n ConnectionSpec\n .Builder(connectionSpec)\n .apply {\n if (tlsVersion != null) {\n tlsVersions(tlsVersion)\n }\n if (cipherSuites != null) {\n cipherSuites(*cipherSuites.toTypedArray())\n }\n }.build(),\n ),\n )\n }\n }.addNetworkInterceptor {\n val socket = it.connection()!!.socket() as SSLSocket\n\n handshakeEnabledCipherSuites = socket.enabledCipherSuites.toList()\n\n it.proceed(it.request())\n }.build()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallHandshakeTest.kt","line":315,"symbol":"makeRequest","kind":"function","lang":"kotlin","code":"private fun makeRequest(client: OkHttpClient): Handshake {\n val call = client.newCall(Request(server.url(\"/\")))\n return call.execute().use { it.handshake!! }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":48,"symbol":"CallKotlinTest","kind":"class","lang":"kotlin","code":"@Timeout(30)\nclass CallKotlinTest {\n @JvmField @RegisterExtension\n val platform = PlatformRule()\n\n @JvmField @RegisterExtension\n val clientTestRule =\n OkHttpClientTestRule().apply {\n recordFrames = true\n recordSslDebug = true\n }\n\n private var client = clientTestRule.newClient()\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n\n @StartStop\n private val server = MockWebServer()\n\n @Test\n fun legalToExecuteTwiceCloning() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n\n val request = Request(server.url(\"/\"))\n\n val call = client.newCall(request)\n val response1 = call.execute()\n\n val cloned = call.clone()\n val response2 = cloned.execute()\n\n assertThat(\"abc\").isEqualTo(response1.body.string())\n assertThat(\"def\").isEqualTo(response2.body.string())\n }\n\n @Test\n @Flaky\n fun testMockWebserverRequest() {\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n assertEquals(\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":66,"symbol":"legalToExecuteTwiceCloning","kind":"function","lang":"kotlin","code":"@Test\n fun legalToExecuteTwiceCloning() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n\n val request = Request(server.url(\"/\"))\n\n val call = client.newCall(request)\n val response1 = call.execute()\n\n val cloned = call.clone()\n val response2 = cloned.execute()\n\n assertThat(\"abc\").isEqualTo(response1.body.string())\n assertThat(\"def\").isEqualTo(response2.body.string())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":83,"symbol":"testMockWebserverRequest","kind":"function","lang":"kotlin","code":"@Test\n @Flaky\n fun testMockWebserverRequest() {\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request.Builder().url(server.url(\"/\")).build()\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n assertEquals(\n \"CN=localhost\",\n (response.handshake!!.peerCertificates.single() as X509Certificate).subjectDN.name,\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":103,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":114,"symbol":"testHeadAfterPut","kind":"function","lang":"kotlin","code":"@RetryingTest(5)\n @Flaky\n fun testHeadAfterPut() {\n class ErringRequestBody : RequestBody() {\n override fun contentType(): MediaType = \"application/xml\".toMediaType()\n\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"\")\n sink.flush()\n }\n }\n\n server.enqueue(MockResponse(code = 201))\n server.enqueue(MockResponse(code = 204))\n server.enqueue(MockResponse(code = 204))\n\n val endpointUrl = server.url(\"/endpoint\")\n\n var request =\n Request\n .Builder()\n .url(endpointUrl)\n .header(\"Content-Type\", \"application/xml\")\n .put(ValidRequestBody())\n .build()\n client.newCall(request).execute().use {\n assertEquals(201, it.code)\n }\n\n request =\n Request\n .Builder()\n .url(endpointUrl)\n .head()\n .build()\n client.newCall(request).execute().use {\n assert"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":117,"symbol":"ErringRequestBody","kind":"class","lang":"kotlin","code":"class ErringRequestBody : RequestBody() {\n override fun contentType(): MediaType = \"application/xml\".toMediaType()\n\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"\")\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":128,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType = \"application/xml\".toMediaType()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":130,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"\")\n sink.flush()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":186,"symbol":"staleConnectionNotReusedForNonIdempotentRequest","kind":"function","lang":"kotlin","code":"@Test\n fun staleConnectionNotReusedForNonIdempotentRequest() {\n // Capture the connection so that we can later make it stale.\n var connection: RealConnection? = null\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(\n Interceptor { chain ->\n connection = chain.connection() as RealConnection\n chain.proceed(chain.request())\n },\n ).build()\n\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"a\")\n .onResponseEnd(\n CloseSocket(\n closeSocket = false,\n shutdownOutput = true,\n ),\n ).build(),\n )\n server.enqueue(MockResponse(body = \"b\"))\n\n val requestA = Request(server.url(\"/\"))\n val responseA = client.newCall(requestA).execute()\n\n assertThat(responseA.body.string()).isEqualTo(\"a\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n\n // Give the socket a chance to become stale.\n connection!!.idleAtNs -= IDLE_CONNECTION_HEALTHY_NS\n Thread.sleep(250)\n\n val requestB =\n Request(\n url = server.url(\"/\"),\n body = \"b\".toRequestBody(\"text/plain\".toMediaType()),\n )\n val responseB "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":234,"symbol":"connectExceptionsAreReturnedAsSuppressed","kind":"function","lang":"kotlin","doc":"Confirm suppressed exceptions that occur while connecting are returned.","code":"@Test fun connectExceptionsAreReturnedAsSuppressed() {\n val proxySelector = RecordingProxySelector()\n proxySelector.proxies.add(Proxy(Proxy.Type.HTTP, TestUtil.UNREACHABLE_ADDRESS_IPV4))\n proxySelector.proxies.add(Proxy.NO_PROXY)\n server.close()\n\n client =\n client\n .newBuilder()\n .proxySelector(proxySelector)\n .readTimeout(Duration.ofMillis(100))\n .connectTimeout(Duration.ofMillis(100))\n .build()\n\n val request = Request(server.url(\"/\"))\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n expected.assertSuppressed {\n val suppressed = it.single()\n assertThat(suppressed).isInstanceOf(IOException::class.java)\n assertThat(suppressed).isNotSameAs(expected)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":261,"symbol":"httpExceptionsAreReturnedAsSuppressed","kind":"function","lang":"kotlin","doc":"Confirm suppressed exceptions that occur after connecting are returned.","code":"@Test fun httpExceptionsAreReturnedAsSuppressed() {\n server.enqueue(MockResponse.Builder().onRequestStart(CloseSocket()).build())\n server.enqueue(MockResponse.Builder().onRequestStart(CloseSocket()).build())\n\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns()) // Two routes so we get two failures.\n .build()\n\n val request = Request(server.url(\"/\"))\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n expected.assertSuppressed {\n val suppressed = it.single()\n assertThat(suppressed).isInstanceOf(IOException::class.java)\n assertThat(suppressed).isNotSameAs(expected)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallKotlinTest.kt","line":283,"symbol":"responseRequestIsLastRedirect","kind":"function","lang":"kotlin","code":"@Test\n fun responseRequestIsLastRedirect() {\n server.enqueue(\n MockResponse(\n code = 302,\n headers = headersOf(\"Location\", \"/b\"),\n ),\n )\n server.enqueue(MockResponse())\n\n val request = Request(server.url(\"/\"))\n val call = client.newCall(request)\n val response = call.execute()\n\n assertThat(response.request.url.encodedPath).isEqualTo(\"/b\")\n assertThat(response.request.headers).isEqualTo(headersOf())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallLimitsTest.kt","line":32,"symbol":"CallLimitsTest","kind":"class","lang":"kotlin","code":"@Burst\nclass CallLimitsTest(\n private val protocol: Protocol = burstValues(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1),\n) {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server =\n MockWebServer().apply {\n protocols = listOf(protocol)\n }\n\n private var client =\n clientTestRule\n .newClientBuilder()\n .protocols(listOf(protocol))\n .build()\n\n @Test\n fun largeStatusLine() {\n assumeTrue(protocol == Protocol.HTTP_1_1)\n\n server.enqueue(\n MockResponse\n .Builder()\n .status(\"HTTP/1.1 200 ${\"O\".repeat(256 * 1024)}K\")\n .body(\"I'm not even supposed to be here today.\")\n .build(),\n )\n val call = client.newCall(Request(url = server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }\n }\n\n /** Use a header that exceeds the limits on its own. */\n @Test\n fun largeResponseHeader() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Set-Cookie\", \"a=${\"A\".repeat(256 * 1024)}\")\n .body(\"I'm not even supposed to be here today.\")\n .build(),\n )\n val call = cl"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallLimitsTest.kt","line":54,"symbol":"largeStatusLine","kind":"function","lang":"kotlin","code":"@Test\n fun largeStatusLine() {\n assumeTrue(protocol == Protocol.HTTP_1_1)\n\n server.enqueue(\n MockResponse\n .Builder()\n .status(\"HTTP/1.1 200 ${\"O\".repeat(256 * 1024)}K\")\n .body(\"I'm not even supposed to be here today.\")\n .build(),\n )\n val call = client.newCall(Request(url = server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallLimitsTest.kt","line":72,"symbol":"largeResponseHeader","kind":"function","lang":"kotlin","doc":"Use a header that exceeds the limits on its own.","code":"@Test\n fun largeResponseHeader() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Set-Cookie\", \"a=${\"A\".repeat(256 * 1024)}\")\n .body(\"I'm not even supposed to be here today.\")\n .build(),\n )\n val call = client.newCall(Request(url = server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallLimitsTest.kt","line":88,"symbol":"largeCompressedResponseHeader","kind":"function","lang":"kotlin","doc":"Use a header that is large even when it is compressed.","code":"@Test\n fun largeCompressedResponseHeader() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Set-Cookie\", \"a=${randomString(256 * 1024)}\")\n .body(\"I'm not even supposed to be here today.\")\n .build(),\n )\n val call = client.newCall(Request(url = server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallLimitsTest.kt","line":104,"symbol":"largeResponseHeadersList","kind":"function","lang":"kotlin","doc":"A collection of headers that collectively exceed the limits.","code":"@Test\n fun largeResponseHeadersList() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Set-Cookie\", \"a=${\"A\".repeat(255 * 1024)}\")\n .addHeader(\"Set-Cookie\", \"b=${\"B\".repeat(1 * 1024)}\")\n .body(\"I'm not even supposed to be here today.\")\n .build(),\n )\n val call = client.newCall(Request(url = server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallLimitsTest.kt","line":120,"symbol":"randomString","kind":"function","lang":"kotlin","code":"private fun randomString(length: Int): String {\n val byteArray = ByteArray(length)\n Random(0).nextBytes(byteArray)\n return byteArray.toByteString().base64()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTagsTest.kt","line":25,"symbol":"CallTagsTest","kind":"class","lang":"kotlin","code":"class CallTagsTest {\n @JvmField @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private var client = clientTestRule.newClient()\n\n @Test\n fun tagsSeededFromRequest() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com/\".toHttpUrl())\n .tag(Integer::class, 5 as Integer)\n .tag(String::class, \"hello\")\n .build()\n val call = client.newCall(request)\n\n // Check the Kotlin-focused APIs.\n assertThat(call.tag(String::class)).isEqualTo(\"hello\")\n assertThat(call.tag(Integer::class)).isEqualTo(5)\n assertThat(call.tag(Boolean::class)).isNull()\n assertThat(call.tag(Any::class)).isNull()\n\n // Check the Java APIs too.\n assertThat(call.tag(String::class.java)).isEqualTo(\"hello\")\n assertThat(call.tag(Integer::class.java)).isEqualTo(5)\n assertThat(call.tag(Boolean::class.java)).isNull()\n assertThat(call.tag(Any::class.java)).isNull()\n }\n\n @Test\n fun tagsCanBeComputed() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .build()\n val call = client.newCall(request)\n\n // Check the Kotlin-focused APIs.\n assertThat(call.tag(String::class) { \"a"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTagsTest.kt","line":31,"symbol":"tagsSeededFromRequest","kind":"function","lang":"kotlin","code":"@Test\n fun tagsSeededFromRequest() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com/\".toHttpUrl())\n .tag(Integer::class, 5 as Integer)\n .tag(String::class, \"hello\")\n .build()\n val call = client.newCall(request)\n\n // Check the Kotlin-focused APIs.\n assertThat(call.tag(String::class)).isEqualTo(\"hello\")\n assertThat(call.tag(Integer::class)).isEqualTo(5)\n assertThat(call.tag(Boolean::class)).isNull()\n assertThat(call.tag(Any::class)).isNull()\n\n // Check the Java APIs too.\n assertThat(call.tag(String::class.java)).isEqualTo(\"hello\")\n assertThat(call.tag(Integer::class.java)).isEqualTo(5)\n assertThat(call.tag(Boolean::class.java)).isNull()\n assertThat(call.tag(Any::class.java)).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTagsTest.kt","line":55,"symbol":"tagsCanBeComputed","kind":"function","lang":"kotlin","code":"@Test\n fun tagsCanBeComputed() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .build()\n val call = client.newCall(request)\n\n // Check the Kotlin-focused APIs.\n assertThat(call.tag(String::class) { \"a\" }).isEqualTo(\"a\")\n assertThat(call.tag(String::class) { \"b\" }).isEqualTo(\"a\")\n assertThat(call.tag(String::class)).isEqualTo(\"a\")\n\n // Check the Java-focused APIs.\n assertThat(call.tag(Integer::class) { 1 as Integer }).isEqualTo(1)\n assertThat(call.tag(Integer::class) { 2 as Integer }).isEqualTo(1)\n assertThat(call.tag(Integer::class)).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTagsTest.kt","line":75,"symbol":"computedTagsAreNotRetainedInClone","kind":"function","lang":"kotlin","code":"@Test\n fun computedTagsAreNotRetainedInClone() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .build()\n val callA = client.newCall(request)\n assertThat(callA.tag(String::class) { \"a\" }).isEqualTo(\"a\")\n assertThat(callA.tag(String::class) { \"b\" }).isEqualTo(\"a\")\n\n val callB = callA.clone()\n assertThat(callB.tag(String::class) { \"c\" }).isEqualTo(\"c\")\n assertThat(callB.tag(String::class) { \"d\" }).isEqualTo(\"c\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":178,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":183,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n cache.close()\n fileSystem.checkNoOpenFiles()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":189,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test\n fun get() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .clearHeaders()\n .addHeader(\"content-type: text/plain\")\n .addHeader(\"content-length\", \"3\")\n .build(),\n )\n val sentAt = System.currentTimeMillis()\n val recordedResponse = executeSynchronously(\"/\", \"User-Agent\", \"SyncApiTest\")\n val receivedAt = System.currentTimeMillis()\n recordedResponse\n .assertCode(200)\n .assertSuccessful()\n .assertHeaders(\n Headers\n .Builder()\n .add(\"content-type\", \"text/plain\")\n .add(\"content-length\", \"3\")\n .build(),\n ).assertBody(\"abc\")\n .assertSentRequestAtMillis(sentAt, receivedAt)\n .assertReceivedResponseAtMillis(sentAt, receivedAt)\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"GET\")\n assertThat(recordedRequest.headers[\"User-Agent\"]).isEqualTo(\"SyncApiTest\")\n assertThat(recordedRequest.body).isNull()\n assertThat(recordedRequest.headers[\"Content-Length\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":222,"symbol":"buildRequestUsingHttpUrl","kind":"function","lang":"kotlin","code":"@Test\n fun buildRequestUsingHttpUrl() {\n server.enqueue(MockResponse())\n executeSynchronously(\"/\").assertSuccessful()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":228,"symbol":"invalidScheme","kind":"function","lang":"kotlin","code":"@Test\n fun invalidScheme() {\n val requestBuilder = Request.Builder()\n assertFailsWith {\n requestBuilder.url(\"ftp://hostname/path\")\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Expected URL scheme 'http' or 'https' but was 'ftp'\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":288,"symbol":"repeatedHeaderNames_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun repeatedHeaderNames_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n repeatedHeaderNames()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":294,"symbol":"getWithRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun getWithRequestBody() {\n server.enqueue(MockResponse())\n assertFailsWith {\n Request.Builder().method(\"GET\", \"abc\".toRequestBody(\"text/plain\".toMediaType()))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":302,"symbol":"head","kind":"function","lang":"kotlin","code":"@Test\n fun head() {\n server.enqueue(\n MockResponse(\n headers = headersOf(\"Content-Type\", \"text/plain\"),\n ),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .head()\n .header(\"User-Agent\", \"SyncApiTest\")\n .build()\n executeSynchronously(request)\n .assertCode(200)\n .assertHeader(\"Content-Type\", \"text/plain\")\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"HEAD\")\n assertThat(recordedRequest.headers[\"User-Agent\"]).isEqualTo(\"SyncApiTest\")\n assertThat(recordedRequest.body).isNull()\n assertThat(recordedRequest.headers[\"Content-Length\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":326,"symbol":"headResponseContentLengthIsIgnored","kind":"function","lang":"kotlin","code":"@Test\n fun headResponseContentLengthIsIgnored() {\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .addHeader(\"Content-Length\", \"100\")\n .build(),\n )\n server.enqueue(\n MockResponse(body = \"abc\"),\n )\n val headRequest =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .head()\n .build()\n val response = client.newCall(headRequest).execute()\n assertThat(response.code).isEqualTo(200)\n assertArrayEquals(ByteArray(0), response.body.bytes())\n val getRequest = Request(server.url(\"/\"))\n executeSynchronously(getRequest)\n .assertCode(200)\n .assertBody(\"abc\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":355,"symbol":"headResponseContentEncodingIsIgnored","kind":"function","lang":"kotlin","code":"@Test\n fun headResponseContentEncodingIsIgnored() {\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .addHeader(\"Content-Encoding\", \"chunked\")\n .build(),\n )\n server.enqueue(MockResponse(body = \"abc\"))\n val headRequest =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .head()\n .build()\n executeSynchronously(headRequest)\n .assertCode(200)\n .assertHeader(\"Content-Encoding\", \"chunked\")\n .assertBody(\"\")\n val getRequest = Request(server.url(\"/\"))\n executeSynchronously(getRequest)\n .assertCode(200)\n .assertBody(\"abc\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":383,"symbol":"head_HTTPS","kind":"function","lang":"kotlin","code":"@Test\n fun head_HTTPS() {\n enableTls()\n head()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":389,"symbol":"head_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun head_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n head()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":395,"symbol":"post","kind":"function","lang":"kotlin","code":"@Test\n fun post() {\n server.enqueue(MockResponse(body = \"abc\"))\n val request =\n Request(\n url = server.url(\"/\"),\n body = \"def\".toRequestBody(\"text/plain\".toMediaType()),\n )\n executeSynchronously(request)\n .assertCode(200)\n .assertBody(\"abc\")\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"POST\")\n assertThat(recordedRequest.body?.utf8()).isEqualTo(\"def\")\n assertThat(recordedRequest.headers[\"Content-Length\"]).isEqualTo(\"3\")\n assertThat(recordedRequest.headers[\"Content-Type\"]).isEqualTo(\"text/plain; charset=utf-8\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":413,"symbol":"post_HTTPS","kind":"function","lang":"kotlin","code":"@Test\n fun post_HTTPS() {\n enableTls()\n post()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":419,"symbol":"post_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun post_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n post()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":425,"symbol":"postZeroLength","kind":"function","lang":"kotlin","code":"@Test\n fun postZeroLength() {\n server.enqueue(MockResponse(body = \"abc\"))\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .method(\"POST\", ByteArray(0).toRequestBody(null))\n .build()\n executeSynchronously(request)\n .assertCode(200)\n .assertBody(\"abc\")\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"POST\")\n assertThat(recordedRequest.body?.size).isEqualTo(0)\n assertThat(recordedRequest.headers[\"Content-Length\"]).isEqualTo(\"0\")\n assertThat(recordedRequest.headers[\"Content-Type\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":444,"symbol":"postZerolength_HTTPS","kind":"function","lang":"kotlin","code":"@Test\n fun postZerolength_HTTPS() {\n enableTls()\n postZeroLength()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":450,"symbol":"postZerolength_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun postZerolength_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n postZeroLength()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":456,"symbol":"postBodyRetransmittedAfterAuthorizationFail","kind":"function","lang":"kotlin","code":"@Test\n fun postBodyRetransmittedAfterAuthorizationFail() {\n postBodyRetransmittedAfterAuthorizationFail(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":461,"symbol":"postBodyRetransmittedAfterAuthorizationFail_HTTPS","kind":"function","lang":"kotlin","code":"@Test\n fun postBodyRetransmittedAfterAuthorizationFail_HTTPS() {\n enableTls()\n postBodyRetransmittedAfterAuthorizationFail(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":467,"symbol":"postBodyRetransmittedAfterAuthorizationFail_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun postBodyRetransmittedAfterAuthorizationFail_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n postBodyRetransmittedAfterAuthorizationFail(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":474,"symbol":"postEmptyBodyRetransmittedAfterAuthorizationFail","kind":"function","lang":"kotlin","doc":"Don't explode when resending an empty post. https://github.com/lysine-dev/okhttp/issues/1131","code":"@Test\n fun postEmptyBodyRetransmittedAfterAuthorizationFail() {\n postBodyRetransmittedAfterAuthorizationFail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":479,"symbol":"postEmptyBodyRetransmittedAfterAuthorizationFail_HTTPS","kind":"function","lang":"kotlin","code":"@Test\n fun postEmptyBodyRetransmittedAfterAuthorizationFail_HTTPS() {\n enableTls()\n postBodyRetransmittedAfterAuthorizationFail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":485,"symbol":"postEmptyBodyRetransmittedAfterAuthorizationFail_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun postEmptyBodyRetransmittedAfterAuthorizationFail_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n postBodyRetransmittedAfterAuthorizationFail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":491,"symbol":"postBodyRetransmittedAfterAuthorizationFail","kind":"function","lang":"kotlin","code":"private fun postBodyRetransmittedAfterAuthorizationFail(body: String) {\n server.enqueue(MockResponse(code = 401))\n server.enqueue(MockResponse())\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .method(\"POST\", body.toRequestBody(null))\n .build()\n val credential = basic(\"jesse\", \"secret\")\n client =\n client\n .newBuilder()\n .authenticator(RecordingOkAuthenticator(credential, null))\n .build()\n val response = client.newCall(request).execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val recordedRequest1 = server.takeRequest()\n assertThat(recordedRequest1.method).isEqualTo(\"POST\")\n assertThat(recordedRequest1.body?.utf8()).isEqualTo(body)\n assertThat(recordedRequest1.headers[\"Authorization\"]).isNull()\n val recordedRequest2 = server.takeRequest()\n assertThat(recordedRequest2.method).isEqualTo(\"POST\")\n assertThat(recordedRequest2.body?.utf8()).isEqualTo(body)\n assertThat(recordedRequest2.headers[\"Authorization\"]).isEqualTo(credential)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":519,"symbol":"attemptAuthorization20Times","kind":"function","lang":"kotlin","code":"@Test\n fun attemptAuthorization20Times() {\n for (i in 0..19) {\n server.enqueue(MockResponse(code = 401))\n }\n server.enqueue(MockResponse(body = \"Success!\"))\n val credential = basic(\"jesse\", \"secret\")\n client =\n client\n .newBuilder()\n .authenticator(RecordingOkAuthenticator(credential, null))\n .build()\n executeSynchronously(\"/\")\n .assertCode(200)\n .assertBody(\"Success!\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":536,"symbol":"doesNotAttemptAuthorization21Times","kind":"function","lang":"kotlin","code":"@Test\n fun doesNotAttemptAuthorization21Times() {\n for (i in 0..20) {\n server.enqueue(MockResponse(code = 401))\n }\n val credential = basic(\"jesse\", \"secret\")\n client =\n client\n .newBuilder()\n .authenticator(RecordingOkAuthenticator(credential, null))\n .build()\n assertFailsWith {\n client.newCall(Request.Builder().url(server.url(\"/0\")).build()).execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Too many follow-up requests: 21\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":558,"symbol":"authenticateWithNoConnection","kind":"function","lang":"kotlin","doc":"We had a bug where we were passing a null route to the authenticator. https://github.com/lysine-dev/okhttp/issues/3809","code":"@Test\n fun authenticateWithNoConnection() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(401)\n .addHeader(\"Connection\", \"close\")\n .onResponseEnd(ShutdownConnection)\n .build(),\n )\n val authenticator = RecordingOkAuthenticator(null, null)\n client =\n client\n .newBuilder()\n .authenticator(authenticator)\n .build()\n executeSynchronously(\"/\")\n .assertCode(401)\n assertThat(authenticator.onlyRoute()).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":579,"symbol":"delete","kind":"function","lang":"kotlin","code":"@Test\n fun delete() {\n server.enqueue(MockResponse(body = \"abc\"))\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .delete()\n .build()\n executeSynchronously(request)\n .assertCode(200)\n .assertBody(\"abc\")\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"DELETE\")\n assertThat(recordedRequest.body?.size).isEqualTo(0)\n assertThat(recordedRequest.headers[\"Content-Length\"]).isEqualTo(\"0\")\n assertThat(recordedRequest.headers[\"Content-Type\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":598,"symbol":"delete_HTTPS","kind":"function","lang":"kotlin","code":"@Test\n fun delete_HTTPS() {\n enableTls()\n delete()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":604,"symbol":"delete_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun delete_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n delete()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":610,"symbol":"deleteWithRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun deleteWithRequestBody() {\n server.enqueue(MockResponse(body = \"abc\"))\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .method(\"DELETE\", \"def\".toRequestBody(\"text/plain\".toMediaType()))\n .build()\n executeSynchronously(request)\n .assertCode(200)\n .assertBody(\"abc\")\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"DELETE\")\n assertThat(recordedRequest.body?.utf8()).isEqualTo(\"def\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":627,"symbol":"put","kind":"function","lang":"kotlin","code":"@Test\n fun put() {\n server.enqueue(MockResponse(body = \"abc\"))\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .put(\"def\".toRequestBody(\"text/plain\".toMediaType()))\n .build()\n executeSynchronously(request)\n .assertCode(200)\n .assertBody(\"abc\")\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"PUT\")\n assertThat(recordedRequest.body?.utf8()).isEqualTo(\"def\")\n assertThat(recordedRequest.headers[\"Content-Length\"]).isEqualTo(\"3\")\n assertThat(recordedRequest.headers[\"Content-Type\"]).isEqualTo(\n \"text/plain; charset=utf-8\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":648,"symbol":"put_HTTPS","kind":"function","lang":"kotlin","code":"@Test\n fun put_HTTPS() {\n enableTls()\n put()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":654,"symbol":"put_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun put_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n put()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":660,"symbol":"patch","kind":"function","lang":"kotlin","code":"@Test\n fun patch() {\n server.enqueue(MockResponse(body = \"abc\"))\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .patch(\"def\".toRequestBody(\"text/plain\".toMediaType()))\n .build()\n executeSynchronously(request)\n .assertCode(200)\n .assertBody(\"abc\")\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"PATCH\")\n assertThat(recordedRequest.body?.utf8()).isEqualTo(\"def\")\n assertThat(recordedRequest.headers[\"Content-Length\"]).isEqualTo(\"3\")\n assertThat(recordedRequest.headers[\"Content-Type\"]).isEqualTo(\"text/plain; charset=utf-8\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":679,"symbol":"patch_HTTP_2","kind":"function","lang":"kotlin","code":"@Test\n fun patch_HTTP_2() {\n enableProtocol(Protocol.HTTP_2)\n patch()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":685,"symbol":"patch_HTTPS","kind":"function","lang":"kotlin","code":"@Test\n fun patch_HTTPS() {\n enableTls()\n patch()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":691,"symbol":"customMethodWithBody","kind":"function","lang":"kotlin","code":"@Test\n fun customMethodWithBody() {\n server.enqueue(MockResponse(body = \"abc\"))\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .method(\"CUSTOM\", \"def\".toRequestBody(\"text/plain\".toMediaType()))\n .build()\n executeSynchronously(request)\n .assertCode(200)\n .assertBody(\"abc\")\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"CUSTOM\")\n assertThat(recordedRequest.body?.utf8()).isEqualTo(\"def\")\n assertThat(recordedRequest.headers[\"Content-Length\"]).isEqualTo(\"3\")\n assertThat(recordedRequest.headers[\"Content-Type\"])\n .isEqualTo(\"text/plain; charset=utf-8\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":711,"symbol":"unspecifiedRequestBodyContentTypeDoesNotGetDefault","kind":"function","lang":"kotlin","code":"@Test\n fun unspecifiedRequestBodyContentTypeDoesNotGetDefault() {\n server.enqueue(MockResponse())\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .method(\"POST\", \"abc\".toRequestBody(null))\n .build()\n executeSynchronously(request).assertCode(200)\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.headers[\"Content-Type\"]).isNull()\n assertThat(recordedRequest.headers[\"Content-Length\"]).isEqualTo(\"3\")\n assertThat(recordedRequest.body?.utf8()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":727,"symbol":"illegalToExecuteTwice","kind":"function","lang":"kotlin","code":"@Test\n fun illegalToExecuteTwice() {\n server.enqueue(\n MockResponse(\n headers = headersOf(\"Content-Type\", \"text/plain\"),\n body = \"abc\",\n ),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"User-Agent\", \"SyncApiTest\")\n .build()\n val call = client.newCall(request)\n val response = call.execute()\n response.body.close()\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Already Executed\")\n }\n assertFailsWith {\n call.enqueue(callback)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Already Executed\")\n }\n assertThat(server.takeRequest().headers[\"User-Agent\"]).isEqualTo(\"SyncApiTest\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":757,"symbol":"illegalToExecuteTwice_Async","kind":"function","lang":"kotlin","code":"@Test\n fun illegalToExecuteTwice_Async() {\n server.enqueue(\n MockResponse(\n headers = headersOf(\"Content-Type\", \"text/plain\"),\n body = \"abc\",\n ),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"User-Agent\", \"SyncApiTest\")\n .build()\n val call = client.newCall(request)\n call.enqueue(callback)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Already Executed\")\n }\n assertFailsWith {\n call.enqueue(callback)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Already Executed\")\n }\n assertThat(server.takeRequest().headers[\"User-Agent\"]).isEqualTo(\"SyncApiTest\")\n callback.await(request.url).assertSuccessful()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":787,"symbol":"legalToExecuteTwiceCloning","kind":"function","lang":"kotlin","code":"@Test\n fun legalToExecuteTwiceCloning() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n val request = Request(server.url(\"/\"))\n val call = client.newCall(request)\n val response1 = call.execute()\n val cloned = call.clone()\n val response2 = cloned.execute()\n assertThat(\"abc\").isEqualTo(response1.body.string())\n assertThat(\"def\").isEqualTo(response2.body.string())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":800,"symbol":"legalToExecuteTwiceCloning_Async","kind":"function","lang":"kotlin","code":"@Test\n fun legalToExecuteTwiceCloning_Async() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n val request = Request(server.url(\"/\"))\n val call = client.newCall(request)\n call.enqueue(callback)\n val cloned = call.clone()\n cloned.enqueue(callback)\n val firstResponse = callback.await(request.url).assertSuccessful()\n val secondResponse = callback.await(request.url).assertSuccessful()\n val bodies: MutableSet = LinkedHashSet()\n bodies.add(firstResponse.body)\n bodies.add(secondResponse.body)\n assertThat(bodies).contains(\"abc\")\n assertThat(bodies).contains(\"def\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":818,"symbol":"get_Async","kind":"function","lang":"kotlin","code":"@Test\n fun get_Async() {\n server.enqueue(\n MockResponse(\n headers = headersOf(\"Content-Type\", \"text/plain\"),\n body = \"abc\",\n ),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"User-Agent\", \"AsyncApiTest\")\n .build()\n client.newCall(request).enqueue(callback)\n callback\n .await(request.url)\n .assertCode(200)\n .assertHeader(\"Content-Type\", \"text/plain\")\n .assertBody(\"abc\")\n assertThat(server.takeRequest().headers[\"User-Agent\"]).isEqualTo(\"AsyncApiTest\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":841,"symbol":"exceptionThrownByOnResponseIsRedactedAndLogged","kind":"function","lang":"kotlin","code":"@Test\n fun exceptionThrownByOnResponseIsRedactedAndLogged() {\n server.enqueue(MockResponse())\n val request = Request(server.url(\"/secret\"))\n client.newCall(request).enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n fail(\"\")\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ): Unit = throw IOException(\"a\")\n },\n )\n assertThat(testLogHandler.take())\n .isEqualTo(\"INFO: Callback failure for call to \" + server.url(\"/\") + \"...\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":847,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":854,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ): Unit = throw IOException(\"a\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":864,"symbol":"connectionPooling","kind":"function","lang":"kotlin","code":"@Test\n fun connectionPooling() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n server.enqueue(MockResponse(body = \"ghi\"))\n executeSynchronously(\"/a\").assertBody(\"abc\")\n executeSynchronously(\"/b\").assertBody(\"def\")\n executeSynchronously(\"/c\").assertBody(\"ghi\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":883,"symbol":"connectionPoolingWithFreshClientSamePool","kind":"function","lang":"kotlin","doc":"Each OkHttpClient used to get its own instance of NullProxySelector, and because these weren't equal their connections weren't pooled. That's a nasty performance bug! https://github.com/lysine-dev/okhttp/issues/5519","code":"@Test\n fun connectionPoolingWithFreshClientSamePool() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n server.enqueue(MockResponse(body = \"ghi\"))\n client =\n OkHttpClient\n .Builder()\n .connectionPool(client.connectionPool)\n .proxy(server.proxyAddress)\n .build()\n executeSynchronously(\"/a\").assertBody(\"abc\")\n client =\n OkHttpClient\n .Builder()\n .connectionPool(client.connectionPool)\n .proxy(server.proxyAddress)\n .build()\n executeSynchronously(\"/b\").assertBody(\"def\")\n client =\n OkHttpClient\n .Builder()\n .connectionPool(client.connectionPool)\n .proxy(server.proxyAddress)\n .build()\n executeSynchronously(\"/c\").assertBody(\"ghi\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":914,"symbol":"connectionPoolingWithClientBuiltOffProxy","kind":"function","lang":"kotlin","code":"@Test\n fun connectionPoolingWithClientBuiltOffProxy() {\n client =\n OkHttpClient\n .Builder()\n .proxy(server.proxyAddress)\n .build()\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n server.enqueue(MockResponse(body = \"ghi\"))\n client = client.newBuilder().build()\n executeSynchronously(\"/a\").assertBody(\"abc\")\n client = client.newBuilder().build()\n executeSynchronously(\"/b\").assertBody(\"def\")\n client = client.newBuilder().build()\n executeSynchronously(\"/c\").assertBody(\"ghi\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":935,"symbol":"connectionPooling_Async","kind":"function","lang":"kotlin","code":"@Test\n fun connectionPooling_Async() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n server.enqueue(MockResponse(body = \"ghi\"))\n client.newCall(Request.Builder().url(server.url(\"/a\")).build()).enqueue(callback)\n callback.await(server.url(\"/a\")).assertBody(\"abc\")\n client.newCall(Request.Builder().url(server.url(\"/b\")).build()).enqueue(callback)\n callback.await(server.url(\"/b\")).assertBody(\"def\")\n client.newCall(Request.Builder().url(server.url(\"/c\")).build()).enqueue(callback)\n callback.await(server.url(\"/c\")).assertBody(\"ghi\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":951,"symbol":"connectionReuseWhenResponseBodyConsumed_Async","kind":"function","lang":"kotlin","code":"@Test\n fun connectionReuseWhenResponseBodyConsumed_Async() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n val request = Request.Builder().url(server.url(\"/a\")).build()\n client.newCall(request).enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ): Unit = throw AssertionError()\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val bytes = response.body.byteStream()\n assertThat(bytes.read()).isEqualTo('a'.code)\n assertThat(bytes.read()).isEqualTo('b'.code)\n assertThat(bytes.read()).isEqualTo('c'.code)\n\n // This request will share a connection with 'A' cause it's all done.\n client.newCall(Request.Builder().url(server.url(\"/b\")).build()).enqueue(callback)\n }\n },\n )\n callback.await(server.url(\"/b\")).assertCode(200).assertBody(\"def\")\n // New connection.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n // Connection reuse!\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":958,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ): Unit = throw AssertionError()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":963,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val bytes = response.body.byteStream()\n assertThat(bytes.read()).isEqualTo('a'.code)\n assertThat(bytes.read()).isEqualTo('b'.code)\n assertThat(bytes.read()).isEqualTo('c'.code)\n\n // This request will share a connection with 'A' cause it's all done.\n client.newCall(Request.Builder().url(server.url(\"/b\")).build()).enqueue(callback)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":984,"symbol":"timeoutsUpdatedOnReusedConnections","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutsUpdatedOnReusedConnections() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"def\")\n .throttleBody(1, 750, TimeUnit.MILLISECONDS)\n .build(),\n )\n\n // First request: time out after 1s.\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofSeconds(1))\n .build()\n executeSynchronously(\"/a\").assertBody(\"abc\")\n\n // Second request: time out after 250ms.\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofMillis(250))\n .build()\n val request = Request.Builder().url(server.url(\"/b\")).build()\n val response = client.newCall(request).execute()\n val bodySource = response.body.source()\n assertThat(bodySource.readByte()).isEqualTo('d'.code.toByte())\n\n // The second byte of this request will be delayed by 750ms so we should time out after 250ms.\n val startNanos = System.nanoTime()\n bodySource.use {\n assertFailsWith {\n bodySource.readByte()\n }.also { expected ->\n // Timed out as expected.\n val elapsedNanos = System.nanoTime() - startNanos\n val el"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":1029,"symbol":"tlsTimeoutsNotRetried","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/442","code":"@Test\n fun tlsTimeoutsNotRetried() {\n enableTls()\n server.enqueue(MockResponse.Builder().onResponseStart(Stall).build())\n server.enqueue(MockResponse(body = \"unreachable!\"))\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofMillis(100))\n .build()\n val request = Request.Builder().url(server.url(\"/\")).build()\n assertFailsWith {\n // If this succeeds, too many requests were made.\n client.newCall(request).execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":1050,"symbol":"connectTimeoutsAttemptsAlternateRoute","kind":"function","lang":"kotlin","doc":"Make a request with two routes. The first route will time out because it's connecting to a special address that never connects. The automatic retry will succeed.","code":"@Test\n fun connectTimeoutsAttemptsAlternateRoute() {\n val proxySelector = RecordingProxySelector()\n proxySelector.proxies.add(Proxy(Proxy.Type.HTTP, TestUtil.UNREACHABLE_ADDRESS_IPV4))\n proxySelector.proxies.add(server.proxyAddress)\n server.enqueue(MockResponse(body = \"success!\"))\n client =\n client\n .newBuilder()\n .proxySelector(proxySelector)\n .readTimeout(Duration.ofMillis(100))\n .connectTimeout(Duration.ofMillis(100))\n .build()\n val request = Request.Builder().url(\"http://android.com/\").build()\n executeSynchronously(request)\n .assertCode(200)\n .assertBody(\"success!\")\n\n assertThat(proxySelector.failures)\n .all {\n hasSize(1)\n index(0).matches(\".* Connect timed out\".toRegex(RegexOption.IGNORE_CASE))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":1076,"symbol":"interceptorRecoversWhenRoutesExhausted","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/4875","code":"@Test\n fun interceptorRecoversWhenRoutesExhausted() {\n server.enqueue(MockResponse.Builder().onRequestStart(CloseSocket()).build())\n server.enqueue(MockResponse())\n client =\n client\n .newBuilder()\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain ->\n try {\n chain.proceed(chain.request())\n throw AssertionError()\n } catch (expected: IOException) {\n chain.proceed(chain.request())\n }\n },\n ).build()\n val request = Request(server.url(\"/\"))\n executeSynchronously(request)\n .assertCode(200)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt","line":1099,"symbol":"interceptorCallsProceedWithoutClosingPriorResponse","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/4761","code":"@Test\n fun interceptorCallsProceedWithoutClosingPriorResponse() {\n server.enqueue(\n MockResponse(body = \"abc\"),\n )\n client =\n clientTestRule\n .newClientBuilder()\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain ->\n val response =\n chain.proceed(\n chain.request(),\n )\n assertFailsWith {\n chain.proceed(chain.request())\n }.also { expected ->\n assertThat(expected.message!!).contains(\"please call response.close()\")\n }\n response\n },\n ).build()\n val request = Request(server.url(\"/\"))\n executeSynchronously(request).assertBody(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":28,"symbol":"CertificateChainCleanerTest","kind":"class","lang":"kotlin","code":"class CertificateChainCleanerTest {\n @Test\n fun equalsFromCertificate() {\n val rootA =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .build()\n val rootB =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .build()\n assertThat(get(rootB.certificate, rootA.certificate))\n .isEqualTo(get(rootA.certificate, rootB.certificate))\n }\n\n @Test\n fun equalsFromTrustManager() {\n val handshakeCertificates = HandshakeCertificates.Builder().build()\n val x509TrustManager = handshakeCertificates.trustManager\n assertThat(get(x509TrustManager)).isEqualTo(get(x509TrustManager))\n }\n\n @Test\n fun normalizeSingleSelfSignedCertificate() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .build()\n val cleaner = get(root.certificate)\n assertThat(cleaner.clean(list(root), \"hostname\")).isEqualTo(list(root))\n }\n\n @Test\n fun normalizeUnknownSelfSignedCertificate() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .build()\n val cleaner = get()\n assertFailsWith {\n cleaner.clean(list(root), \"hostname\")\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":29,"symbol":"equalsFromCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun equalsFromCertificate() {\n val rootA =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .build()\n val rootB =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .build()\n assertThat(get(rootB.certificate, rootA.certificate))\n .isEqualTo(get(rootA.certificate, rootB.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":45,"symbol":"equalsFromTrustManager","kind":"function","lang":"kotlin","code":"@Test\n fun equalsFromTrustManager() {\n val handshakeCertificates = HandshakeCertificates.Builder().build()\n val x509TrustManager = handshakeCertificates.trustManager\n assertThat(get(x509TrustManager)).isEqualTo(get(x509TrustManager))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":52,"symbol":"normalizeSingleSelfSignedCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun normalizeSingleSelfSignedCertificate() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .build()\n val cleaner = get(root.certificate)\n assertThat(cleaner.clean(list(root), \"hostname\")).isEqualTo(list(root))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":63,"symbol":"normalizeUnknownSelfSignedCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun normalizeUnknownSelfSignedCertificate() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .build()\n val cleaner = get()\n assertFailsWith {\n cleaner.clean(list(root), \"hostname\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":76,"symbol":"orderedChainOfCertificatesWithRoot","kind":"function","lang":"kotlin","code":"@Test\n fun orderedChainOfCertificatesWithRoot() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .build()\n val certA =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .certificateAuthority(0)\n .signedBy(root)\n .build()\n val certB =\n HeldCertificate\n .Builder()\n .serialNumber(3L)\n .signedBy(certA)\n .build()\n val cleaner = get(root.certificate)\n assertThat(cleaner.clean(list(certB, certA, root), \"hostname\"))\n .isEqualTo(list(certB, certA, root))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":102,"symbol":"orderedChainOfCertificatesWithoutRoot","kind":"function","lang":"kotlin","code":"@Test\n fun orderedChainOfCertificatesWithoutRoot() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .build()\n val certA =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .certificateAuthority(0)\n .signedBy(root)\n .build()\n val certB =\n HeldCertificate\n .Builder()\n .serialNumber(3L)\n .signedBy(certA)\n .build()\n val cleaner = get(root.certificate)\n // Root is added!\n assertThat(cleaner.clean(list(certB, certA), \"hostname\")).isEqualTo(\n list(certB, certA, root),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":130,"symbol":"unorderedChainOfCertificatesWithRoot","kind":"function","lang":"kotlin","code":"@Test\n fun unorderedChainOfCertificatesWithRoot() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(2)\n .build()\n val certA =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .certificateAuthority(1)\n .signedBy(root)\n .build()\n val certB =\n HeldCertificate\n .Builder()\n .serialNumber(3L)\n .certificateAuthority(0)\n .signedBy(certA)\n .build()\n val certC =\n HeldCertificate\n .Builder()\n .serialNumber(4L)\n .signedBy(certB)\n .build()\n val cleaner = get(root.certificate)\n assertThat(cleaner.clean(list(certC, certA, root, certB), \"hostname\")).isEqualTo(\n list(certC, certB, certA, root),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":164,"symbol":"unorderedChainOfCertificatesWithoutRoot","kind":"function","lang":"kotlin","code":"@Test\n fun unorderedChainOfCertificatesWithoutRoot() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(2)\n .build()\n val certA =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .certificateAuthority(1)\n .signedBy(root)\n .build()\n val certB =\n HeldCertificate\n .Builder()\n .serialNumber(3L)\n .certificateAuthority(0)\n .signedBy(certA)\n .build()\n val certC =\n HeldCertificate\n .Builder()\n .serialNumber(4L)\n .signedBy(certB)\n .build()\n val cleaner = get(root.certificate)\n assertThat(cleaner.clean(list(certC, certA, certB), \"hostname\")).isEqualTo(\n list(certC, certB, certA, root),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":198,"symbol":"unrelatedCertificatesAreOmitted","kind":"function","lang":"kotlin","code":"@Test\n fun unrelatedCertificatesAreOmitted() {\n val root =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .build()\n val certA =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .certificateAuthority(0)\n .signedBy(root)\n .build()\n val certB =\n HeldCertificate\n .Builder()\n .serialNumber(3L)\n .signedBy(certA)\n .build()\n val certUnnecessary =\n HeldCertificate\n .Builder()\n .serialNumber(4L)\n .build()\n val cleaner = get(root.certificate)\n assertThat(cleaner.clean(list(certB, certUnnecessary, certA, root), \"hostname\"))\n .isEqualTo(\n list(certB, certA, root),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":231,"symbol":"chainGoesAllTheWayToSelfSignedRoot","kind":"function","lang":"kotlin","code":"@Test\n fun chainGoesAllTheWayToSelfSignedRoot() {\n val selfSigned =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(2)\n .build()\n val trusted =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .signedBy(selfSigned)\n .certificateAuthority(1)\n .build()\n val certA =\n HeldCertificate\n .Builder()\n .serialNumber(3L)\n .certificateAuthority(0)\n .signedBy(trusted)\n .build()\n val certB =\n HeldCertificate\n .Builder()\n .serialNumber(4L)\n .signedBy(certA)\n .build()\n val cleaner =\n get(\n selfSigned.certificate,\n trusted.certificate,\n )\n assertThat(cleaner.clean(list(certB, certA), \"hostname\")).isEqualTo(\n list(certB, certA, trusted, selfSigned),\n )\n assertThat(cleaner.clean(list(certB, certA, trusted), \"hostname\")).isEqualTo(\n list(certB, certA, trusted, selfSigned),\n )\n assertThat(cleaner.clean(list(certB, certA, trusted, selfSigned), \"hostname\"))\n .isEqualTo(\n list(certB, certA, trusted, selfSigned),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":276,"symbol":"trustedRootNotSelfSigned","kind":"function","lang":"kotlin","code":"@Test\n fun trustedRootNotSelfSigned() {\n val unknownSigner =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(2)\n .build()\n val trusted =\n HeldCertificate\n .Builder()\n .signedBy(unknownSigner)\n .certificateAuthority(1)\n .serialNumber(2L)\n .build()\n val intermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(trusted)\n .certificateAuthority(0)\n .serialNumber(3L)\n .build()\n val certificate =\n HeldCertificate\n .Builder()\n .signedBy(intermediateCa)\n .serialNumber(4L)\n .build()\n val cleaner = get(trusted.certificate)\n assertThat(cleaner.clean(list(certificate, intermediateCa), \"hostname\"))\n .isEqualTo(\n list(certificate, intermediateCa, trusted),\n )\n assertThat(cleaner.clean(list(certificate, intermediateCa, trusted), \"hostname\"))\n .isEqualTo(\n list(certificate, intermediateCa, trusted),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":315,"symbol":"chainMaxLength","kind":"function","lang":"kotlin","code":"@Test\n fun chainMaxLength() {\n val heldCertificates = chainOfLength(10)\n val certificates: MutableList = ArrayList()\n for (heldCertificate in heldCertificates) {\n certificates.add(heldCertificate.certificate)\n }\n val root = heldCertificates[heldCertificates.size - 1].certificate\n val cleaner = get(root)\n assertThat(cleaner.clean(certificates, \"hostname\")).isEqualTo(certificates)\n assertThat(cleaner.clean(certificates.subList(0, 9), \"hostname\")).isEqualTo(\n certificates,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":330,"symbol":"chainTooLong","kind":"function","lang":"kotlin","code":"@Test\n fun chainTooLong() {\n val heldCertificates = chainOfLength(11)\n val certificates: MutableList = ArrayList()\n for (heldCertificate in heldCertificates) {\n certificates.add(heldCertificate.certificate)\n }\n val root = heldCertificates[heldCertificates.size - 1].certificate\n val cleaner = get(root)\n assertFailsWith {\n cleaner.clean(certificates, \"hostname\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":345,"symbol":"chainOfLength","kind":"function","lang":"kotlin","doc":"Returns a chain starting at the leaf certificate and progressing to the root.","code":"private fun chainOfLength(length: Int): List {\n val result = mutableListOf()\n for (i in 1..length) {\n result.add(\n 0,\n HeldCertificate\n .Builder()\n .signedBy(if (result.isNotEmpty()) result[0] else null)\n .certificateAuthority(length - i)\n .serialNumber(i.toLong())\n .build(),\n )\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificateChainCleanerTest.kt","line":361,"symbol":"list","kind":"function","lang":"kotlin","code":"private fun list(vararg heldCertificates: HeldCertificate): List {\n val result: MutableList = ArrayList()\n for (heldCertificate in heldCertificates) {\n result.add(heldCertificate.certificate)\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":31,"symbol":"CertificatePinnerKotlinTest","kind":"class","lang":"kotlin","code":"class CertificatePinnerKotlinTest {\n @Test\n fun successfulCheckSha1Pin() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"example.com\", \"sha1/\" + certA1.certificate.sha1Hash().base64())\n .build()\n\n certificatePinner.check(\"example.com\", listOf(certA1.certificate))\n }\n\n @Test fun successfulFindMatchingPins() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"first.com\", certA1Sha256Pin, certB1Sha256Pin)\n .add(\"second.com\", certC1Sha256Pin)\n .build()\n\n val expectedPins =\n listOf(\n Pin(\"first.com\", certA1Sha256Pin),\n Pin(\"first.com\", certB1Sha256Pin),\n )\n assertThat(certificatePinner.findMatchingPins(\"first.com\")).isEqualTo(expectedPins)\n }\n\n @Test fun successfulFindMatchingPinsForWildcardAndDirectCertificates() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin)\n .add(\"a.example.com\", certB1Sha256Pin)\n .add(\"b.example.com\", certC1Sha256Pin)\n .build()\n\n val expectedPins =\n listOf(\n Pin(\"*.example.com\", certA1Sha256Pin),\n Pin(\"a.example.com\", ce"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":32,"symbol":"successfulCheckSha1Pin","kind":"function","lang":"kotlin","code":"@Test\n fun successfulCheckSha1Pin() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"example.com\", \"sha1/\" + certA1.certificate.sha1Hash().base64())\n .build()\n\n certificatePinner.check(\"example.com\", listOf(certA1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":43,"symbol":"successfulFindMatchingPins","kind":"function","lang":"kotlin","code":"@Test fun successfulFindMatchingPins() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"first.com\", certA1Sha256Pin, certB1Sha256Pin)\n .add(\"second.com\", certC1Sha256Pin)\n .build()\n\n val expectedPins =\n listOf(\n Pin(\"first.com\", certA1Sha256Pin),\n Pin(\"first.com\", certB1Sha256Pin),\n )\n assertThat(certificatePinner.findMatchingPins(\"first.com\")).isEqualTo(expectedPins)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":59,"symbol":"successfulFindMatchingPinsForWildcardAndDirectCertificates","kind":"function","lang":"kotlin","code":"@Test fun successfulFindMatchingPinsForWildcardAndDirectCertificates() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin)\n .add(\"a.example.com\", certB1Sha256Pin)\n .add(\"b.example.com\", certC1Sha256Pin)\n .build()\n\n val expectedPins =\n listOf(\n Pin(\"*.example.com\", certA1Sha256Pin),\n Pin(\"a.example.com\", certB1Sha256Pin),\n )\n assertThat(certificatePinner.findMatchingPins(\"a.example.com\")).isEqualTo(expectedPins)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":76,"symbol":"wildcardHostnameShouldNotMatchThroughDot","kind":"function","lang":"kotlin","code":"@Test\n fun wildcardHostnameShouldNotMatchThroughDot() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin)\n .build()\n\n assertThat(certificatePinner.findMatchingPins(\"example.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"..example.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"a..example.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"a.b.example.com\")).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":90,"symbol":"doubleWildcardHostnameShouldMatchThroughDot","kind":"function","lang":"kotlin","code":"@Test\n fun doubleWildcardHostnameShouldMatchThroughDot() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"**.example.com\", certA1Sha256Pin)\n .build()\n\n val expectedPin1 = listOf(Pin(\"**.example.com\", certA1Sha256Pin))\n assertThat(certificatePinner.findMatchingPins(\"example.com\")).isEqualTo(expectedPin1)\n assertThat(certificatePinner.findMatchingPins(\".example.com\")).isEqualTo(expectedPin1)\n assertThat(certificatePinner.findMatchingPins(\"..example.com\")).isEqualTo(expectedPin1)\n assertThat(certificatePinner.findMatchingPins(\"a..example.com\")).isEqualTo(expectedPin1)\n assertThat(certificatePinner.findMatchingPins(\"a.b.example.com\")).isEqualTo(expectedPin1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":106,"symbol":"doubleWildcardHostnameShouldNotMatchSuffix","kind":"function","lang":"kotlin","code":"@Test\n fun doubleWildcardHostnameShouldNotMatchSuffix() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"**.example.com\", certA1Sha256Pin)\n .build()\n\n assertThat(certificatePinner.findMatchingPins(\"xample.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"dexample.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"barnexample.com\")).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":119,"symbol":"successfulFindMatchingPinsIgnoresCase","kind":"function","lang":"kotlin","code":"@Test fun successfulFindMatchingPinsIgnoresCase() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"EXAMPLE.com\", certA1Sha256Pin)\n .add(\"*.MyExample.Com\", certB1Sha256Pin)\n .build()\n\n val expectedPin1 = listOf(Pin(\"EXAMPLE.com\", certA1Sha256Pin))\n assertThat(certificatePinner.findMatchingPins(\"example.com\")).isEqualTo(expectedPin1)\n\n val expectedPin2 = listOf(Pin(\"*.MyExample.Com\", certB1Sha256Pin))\n assertThat(certificatePinner.findMatchingPins(\"a.myexample.com\")).isEqualTo(expectedPin2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":134,"symbol":"successfulFindMatchingPinPunycode","kind":"function","lang":"kotlin","code":"@Test fun successfulFindMatchingPinPunycode() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"σkhttp.com\", certA1Sha256Pin)\n .build()\n\n val expectedPin = listOf(Pin(\"σkhttp.com\", certA1Sha256Pin))\n assertThat(certificatePinner.findMatchingPins(\"xn--khttp-fde.com\")).isEqualTo(expectedPin)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":146,"symbol":"checkSubstringMatch","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/3324","code":"@Test\n fun checkSubstringMatch() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin)\n .build()\n\n assertThat(certificatePinner.findMatchingPins(\"a.example.com.notexample.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"example.com.notexample.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"notexample.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"example.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"a.b.example.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"ple.com\")).isEmpty()\n assertThat(certificatePinner.findMatchingPins(\"com\")).isEmpty()\n\n val expectedPin = Pin(\"*.example.com\", certA1Sha256Pin)\n assertThat(certificatePinner.findMatchingPins(\"a.example.com\")).containsExactly(expectedPin)\n assertThat(certificatePinner.findMatchingPins(\".example.com\")).containsExactly(expectedPin)\n assertThat(certificatePinner.findMatchingPins(\"example.example.com\"))\n .containsExactly(expectedPin)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":169,"symbol":"testGoodPin","kind":"function","lang":"kotlin","code":"@Test fun testGoodPin() {\n val pin =\n Pin(\n \"**.example.co.uk\",\n \"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\",\n )\n assertEquals(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\".decodeBase64(), pin.hash)\n assertEquals(\"sha256\", pin.hashAlgorithm)\n assertEquals(\"**.example.co.uk\", pin.pattern)\n assertTrue(pin.matchesHostname(\"www.example.co.uk\"))\n assertTrue(pin.matchesHostname(\"gopher.example.co.uk\"))\n assertFalse(pin.matchesHostname(\"www.example.com\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":183,"symbol":"testMatchesSha256","kind":"function","lang":"kotlin","code":"@Test fun testMatchesSha256() {\n val pin = Pin(\"example.com\", certA1Sha256Pin)\n assertTrue(pin.matchesCertificate(certA1.certificate))\n assertFalse(pin.matchesCertificate(certB1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":189,"symbol":"testMatchesSha1","kind":"function","lang":"kotlin","code":"@Test fun testMatchesSha1() {\n val pin = Pin(\"example.com\", certC1Sha1Pin)\n assertTrue(pin.matchesCertificate(certC1.certificate))\n assertFalse(pin.matchesCertificate(certB1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerKotlinTest.kt","line":195,"symbol":"pinList","kind":"function","lang":"kotlin","code":"@Test fun pinList() {\n val builder =\n CertificatePinner\n .Builder()\n .add(\"example.com\", CertificatePinnerTest.certA1Sha256Pin)\n .add(\"www.example.com\", CertificatePinnerTest.certA1Sha256Pin)\n val certificatePinner = builder.build()\n\n val expectedPins =\n listOf(\n Pin(\"example.com\", CertificatePinnerTest.certA1Sha256Pin),\n Pin(\"www.example.com\", CertificatePinnerTest.certA1Sha256Pin),\n )\n\n assertEquals(expectedPins, builder.pins)\n assertEquals(expectedPins.toSet(), certificatePinner.pins)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":32,"symbol":"CertificatePinnerTest","kind":"class","lang":"kotlin","code":"class CertificatePinnerTest {\n @Test\n fun malformedPin() {\n val builder = CertificatePinner.Builder()\n assertFailsWith {\n builder.add(\"example.com\", \"md5/DmxUShsZuNiqPQsX2Oi9uv2sCnw=\")\n }\n }\n\n @Test\n fun malformedBase64() {\n val builder = CertificatePinner.Builder()\n assertFailsWith {\n builder.add(\"example.com\", \"sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw*\")\n }\n }\n\n /** Multiple certificates generated from the same keypair have the same pin. */\n @Test\n fun sameKeypairSamePin() {\n val heldCertificateA2 =\n HeldCertificate\n .Builder()\n .keyPair(certA1.keyPair)\n .serialNumber(101L)\n .build()\n val keypairACertificate2Pin = pin(heldCertificateA2.certificate)\n val heldCertificateB2 =\n HeldCertificate\n .Builder()\n .keyPair(certB1.keyPair)\n .serialNumber(201L)\n .build()\n val keypairBCertificate2Pin = pin(heldCertificateB2.certificate)\n assertThat(keypairACertificate2Pin).isEqualTo(certA1Sha256Pin)\n assertThat(keypairBCertificate2Pin).isEqualTo(certB1Sha256Pin)\n assertThat(certB1Sha256Pin).isNotEqualTo(certA1Sha256Pin)\n }\n\n @"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":33,"symbol":"malformedPin","kind":"function","lang":"kotlin","code":"@Test\n fun malformedPin() {\n val builder = CertificatePinner.Builder()\n assertFailsWith {\n builder.add(\"example.com\", \"md5/DmxUShsZuNiqPQsX2Oi9uv2sCnw=\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":41,"symbol":"malformedBase64","kind":"function","lang":"kotlin","code":"@Test\n fun malformedBase64() {\n val builder = CertificatePinner.Builder()\n assertFailsWith {\n builder.add(\"example.com\", \"sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw*\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":50,"symbol":"sameKeypairSamePin","kind":"function","lang":"kotlin","doc":"Multiple certificates generated from the same keypair have the same pin.","code":"@Test\n fun sameKeypairSamePin() {\n val heldCertificateA2 =\n HeldCertificate\n .Builder()\n .keyPair(certA1.keyPair)\n .serialNumber(101L)\n .build()\n val keypairACertificate2Pin = pin(heldCertificateA2.certificate)\n val heldCertificateB2 =\n HeldCertificate\n .Builder()\n .keyPair(certB1.keyPair)\n .serialNumber(201L)\n .build()\n val keypairBCertificate2Pin = pin(heldCertificateB2.certificate)\n assertThat(keypairACertificate2Pin).isEqualTo(certA1Sha256Pin)\n assertThat(keypairBCertificate2Pin).isEqualTo(certB1Sha256Pin)\n assertThat(certB1Sha256Pin).isNotEqualTo(certA1Sha256Pin)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":71,"symbol":"successfulCheck","kind":"function","lang":"kotlin","code":"@Test\n fun successfulCheck() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"example.com\", certA1Sha256Pin)\n .build()\n certificatePinner.check(\"example.com\", listOf(certA1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":81,"symbol":"successfulMatchAcceptsAnyMatchingCertificateOld","kind":"function","lang":"kotlin","code":"@Test\n fun successfulMatchAcceptsAnyMatchingCertificateOld() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"example.com\", certB1Sha256Pin)\n .build()\n certificatePinner.check(\"example.com\", certA1.certificate, certB1.certificate)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":91,"symbol":"successfulMatchAcceptsAnyMatchingCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun successfulMatchAcceptsAnyMatchingCertificate() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"example.com\", certB1Sha256Pin)\n .build()\n certificatePinner.check(\n \"example.com\",\n Arrays.asList(certA1.certificate, certB1.certificate),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":104,"symbol":"unsuccessfulCheck","kind":"function","lang":"kotlin","code":"@Test\n fun unsuccessfulCheck() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"example.com\", certA1Sha256Pin)\n .build()\n assertFailsWith {\n certificatePinner.check(\"example.com\", certB1.certificate)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":116,"symbol":"multipleCertificatesForOneHostname","kind":"function","lang":"kotlin","code":"@Test\n fun multipleCertificatesForOneHostname() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"example.com\", certA1Sha256Pin, certB1Sha256Pin)\n .build()\n certificatePinner.check(\"example.com\", listOf(certA1.certificate))\n certificatePinner.check(\"example.com\", listOf(certB1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":127,"symbol":"multipleHostnamesForOneCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun multipleHostnamesForOneCertificate() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"example.com\", certA1Sha256Pin)\n .add(\"www.example.com\", certA1Sha256Pin)\n .build()\n certificatePinner.check(\"example.com\", listOf(certA1.certificate))\n certificatePinner.check(\"www.example.com\", listOf(certA1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":139,"symbol":"absentHostnameMatches","kind":"function","lang":"kotlin","code":"@Test\n fun absentHostnameMatches() {\n val certificatePinner = CertificatePinner.Builder().build()\n certificatePinner.check(\"example.com\", listOf(certA1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":145,"symbol":"successfulCheckForWildcardHostname","kind":"function","lang":"kotlin","code":"@Test\n fun successfulCheckForWildcardHostname() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin)\n .build()\n certificatePinner.check(\"a.example.com\", listOf(certA1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":155,"symbol":"successfulMatchAcceptsAnyMatchingCertificateForWildcardHostname","kind":"function","lang":"kotlin","code":"@Test\n fun successfulMatchAcceptsAnyMatchingCertificateForWildcardHostname() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certB1Sha256Pin)\n .build()\n certificatePinner.check(\n \"a.example.com\",\n Arrays.asList(certA1.certificate, certB1.certificate),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":168,"symbol":"unsuccessfulCheckForWildcardHostname","kind":"function","lang":"kotlin","code":"@Test\n fun unsuccessfulCheckForWildcardHostname() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin)\n .build()\n assertFailsWith {\n certificatePinner.check(\"a.example.com\", listOf(certB1.certificate))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":180,"symbol":"multipleCertificatesForOneWildcardHostname","kind":"function","lang":"kotlin","code":"@Test\n fun multipleCertificatesForOneWildcardHostname() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin, certB1Sha256Pin)\n .build()\n certificatePinner.check(\"a.example.com\", listOf(certA1.certificate))\n certificatePinner.check(\"a.example.com\", listOf(certB1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":191,"symbol":"successfulCheckForOneHostnameWithWildcardAndDirectCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun successfulCheckForOneHostnameWithWildcardAndDirectCertificate() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin)\n .add(\"a.example.com\", certB1Sha256Pin)\n .build()\n certificatePinner.check(\"a.example.com\", listOf(certA1.certificate))\n certificatePinner.check(\"a.example.com\", listOf(certB1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":203,"symbol":"unsuccessfulCheckForOneHostnameWithWildcardAndDirectCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun unsuccessfulCheckForOneHostnameWithWildcardAndDirectCertificate() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"*.example.com\", certA1Sha256Pin)\n .add(\"a.example.com\", certB1Sha256Pin)\n .build()\n assertFailsWith {\n certificatePinner.check(\"a.example.com\", listOf(certC1.certificate))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":216,"symbol":"checkForHostnameWithDoubleAsterisk","kind":"function","lang":"kotlin","code":"@Test\n fun checkForHostnameWithDoubleAsterisk() {\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(\"**.example.co.uk\", certA1Sha256Pin)\n .build()\n\n // Should be pinned:\n assertFailsWith {\n certificatePinner.check(\"example.co.uk\", listOf(certB1.certificate))\n }\n assertFailsWith {\n certificatePinner.check(\"foo.example.co.uk\", listOf(certB1.certificate))\n }\n assertFailsWith {\n certificatePinner.check(\"foo.bar.example.co.uk\", listOf(certB1.certificate))\n }\n assertFailsWith {\n certificatePinner.check(\"foo.bar.baz.example.co.uk\", listOf(certB1.certificate))\n }\n\n // Should not be pinned:\n certificatePinner.check(\"uk\", listOf(certB1.certificate))\n certificatePinner.check(\"co.uk\", listOf(certB1.certificate))\n certificatePinner.check(\"anotherexample.co.uk\", listOf(certB1.certificate))\n certificatePinner.check(\"foo.anotherexample.co.uk\", listOf(certB1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":245,"symbol":"testBadPin","kind":"function","lang":"kotlin","code":"@Test\n fun testBadPin() {\n assertFailsWith {\n CertificatePinner.Pin(\n \"example.co.uk\",\n \"sha256/a\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":255,"symbol":"testBadAlgorithm","kind":"function","lang":"kotlin","code":"@Test\n fun testBadAlgorithm() {\n assertFailsWith {\n CertificatePinner.Pin(\n \"example.co.uk\",\n \"sha512/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":265,"symbol":"testBadHost","kind":"function","lang":"kotlin","code":"@Test\n fun testBadHost() {\n assertFailsWith {\n CertificatePinner.Pin(\n \"example.*\",\n \"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":275,"symbol":"testGoodPin","kind":"function","lang":"kotlin","code":"@Test\n fun testGoodPin() {\n val pin =\n CertificatePinner.Pin(\n \"**.example.co.uk\",\n \"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\",\n )\n assertEquals(\n \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\".decodeBase64(),\n pin.hash,\n )\n assertEquals(\"sha256\", pin.hashAlgorithm)\n assertEquals(\"**.example.co.uk\", pin.pattern)\n Assertions.assertTrue(pin.matchesHostname(\"www.example.co.uk\"))\n Assertions.assertTrue(pin.matchesHostname(\"gopher.example.co.uk\"))\n Assertions.assertFalse(pin.matchesHostname(\"www.example.com\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":293,"symbol":"testMatchesSha256","kind":"function","lang":"kotlin","code":"@Test\n fun testMatchesSha256() {\n val pin = CertificatePinner.Pin(\"example.com\", certA1Sha256Pin)\n Assertions.assertTrue(pin.matchesCertificate(certA1.certificate))\n Assertions.assertFalse(pin.matchesCertificate(certB1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":300,"symbol":"testMatchesSha1","kind":"function","lang":"kotlin","code":"@Test\n fun testMatchesSha1() {\n val pin = CertificatePinner.Pin(\"example.com\", certC1Sha1Pin)\n Assertions.assertTrue(pin.matchesCertificate(certC1.certificate))\n Assertions.assertFalse(pin.matchesCertificate(certB1.certificate))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CertificatePinnerTest.kt","line":307,"symbol":"pinList","kind":"function","lang":"kotlin","code":"@Test\n fun pinList() {\n val builder =\n CertificatePinner\n .Builder()\n .add(\"example.com\", certA1Sha256Pin)\n .add(\"www.example.com\", certA1Sha256Pin)\n val certificatePinner = builder.build()\n val expectedPins =\n Arrays.asList(\n CertificatePinner.Pin(\"example.com\", certA1Sha256Pin),\n CertificatePinner.Pin(\"www.example.com\", certA1Sha256Pin),\n )\n assertEquals(expectedPins, builder.pins)\n assertEquals(HashSet(expectedPins), certificatePinner.pins)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ChannelSocketFactory.kt","line":23,"symbol":"ChannelSocketFactory","kind":"class","lang":"kotlin","code":"class ChannelSocketFactory : SocketFactory() {\n override fun createSocket(): Socket = SocketChannel.open().socket()\n\n override fun createSocket(\n host: String,\n port: Int,\n ): Socket = TODO(\"Not yet implemented\")\n\n override fun createSocket(\n host: String,\n port: Int,\n localHost: InetAddress,\n localPort: Int,\n ): Socket = TODO(\"Not yet implemented\")\n\n override fun createSocket(\n host: InetAddress,\n port: Int,\n ): Socket = TODO(\"Not yet implemented\")\n\n override fun createSocket(\n address: InetAddress,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): Socket = TODO(\"Not yet implemented\")\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ChannelSocketFactory.kt","line":24,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(): Socket = SocketChannel.open().socket()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ChannelSocketFactory.kt","line":26,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: String,\n port: Int,\n ): Socket = TODO(\"Not yet implemented\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ChannelSocketFactory.kt","line":31,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: String,\n port: Int,\n localHost: InetAddress,\n localPort: Int,\n ): Socket = TODO(\"Not yet implemented\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ChannelSocketFactory.kt","line":38,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: InetAddress,\n port: Int,\n ): Socket = TODO(\"Not yet implemented\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ChannelSocketFactory.kt","line":43,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n address: InetAddress,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): Socket = TODO(\"Not yet implemented\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":28,"symbol":"CipherSuiteTest","kind":"class","lang":"kotlin","code":"class CipherSuiteTest {\n @Test\n fun hashCode_usesIdentityHashCode_legacyCase() {\n val cs = CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5 // This one's javaName starts with \"SSL_\".\n assertThat(cs.hashCode(), cs.toString())\n .isEqualTo(System.identityHashCode(cs))\n }\n\n @Test\n fun hashCode_usesIdentityHashCode_regularCase() {\n // This one's javaName matches the identifier.\n val cs = CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256\n assertThat(cs.hashCode(), cs.toString())\n .isEqualTo(System.identityHashCode(cs))\n }\n\n @Test\n fun instancesAreInterned() {\n assertThat(forJavaName(\"TestCipherSuite\"))\n .isSameInstanceAs(forJavaName(\"TestCipherSuite\"))\n assertThat(forJavaName(CipherSuite.TLS_KRB5_WITH_DES_CBC_MD5.javaName))\n .isSameInstanceAs(\n CipherSuite.TLS_KRB5_WITH_DES_CBC_MD5,\n )\n }\n\n /**\n * Tests that interned CipherSuite instances remain the case across garbage collections, even if\n * the String used to construct them is no longer strongly referenced outside of the CipherSuite.\n */\n @Test\n fun instancesAreInterned_survivesGarbageCollection() {\n // We're not holding onto a reference to this String instance outside of th"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":29,"symbol":"hashCode_usesIdentityHashCode_legacyCase","kind":"function","lang":"kotlin","code":"@Test\n fun hashCode_usesIdentityHashCode_legacyCase() {\n val cs = CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5 // This one's javaName starts with \"SSL_\".\n assertThat(cs.hashCode(), cs.toString())\n .isEqualTo(System.identityHashCode(cs))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":36,"symbol":"hashCode_usesIdentityHashCode_regularCase","kind":"function","lang":"kotlin","code":"@Test\n fun hashCode_usesIdentityHashCode_regularCase() {\n // This one's javaName matches the identifier.\n val cs = CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256\n assertThat(cs.hashCode(), cs.toString())\n .isEqualTo(System.identityHashCode(cs))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":44,"symbol":"instancesAreInterned","kind":"function","lang":"kotlin","code":"@Test\n fun instancesAreInterned() {\n assertThat(forJavaName(\"TestCipherSuite\"))\n .isSameInstanceAs(forJavaName(\"TestCipherSuite\"))\n assertThat(forJavaName(CipherSuite.TLS_KRB5_WITH_DES_CBC_MD5.javaName))\n .isSameInstanceAs(\n CipherSuite.TLS_KRB5_WITH_DES_CBC_MD5,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":58,"symbol":"instancesAreInterned_survivesGarbageCollection","kind":"function","lang":"kotlin","doc":"Tests that interned CipherSuite instances remain the case across garbage collections, even if the String used to construct them is no longer strongly referenced outside of the CipherSuite.","code":"@Test\n fun instancesAreInterned_survivesGarbageCollection() {\n // We're not holding onto a reference to this String instance outside of the CipherSuite...\n val cs = forJavaName(\"FakeCipherSuite_instancesAreInterned\")\n System.gc() // Unless cs references the String instance, it may now be garbage collected.\n assertThat(forJavaName(java.lang.String(cs.javaName) as String))\n .isSameInstanceAs(cs)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":67,"symbol":"equals","kind":"function","lang":"kotlin","code":"@Test\n fun equals() {\n assertThat(forJavaName(\"cipher\")).isEqualTo(forJavaName(\"cipher\"))\n assertThat(forJavaName(\"cipherB\")).isNotEqualTo(forJavaName(\"cipherA\"))\n assertThat(CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5)\n .isEqualTo(forJavaName(\"SSL_RSA_EXPORT_WITH_RC4_40_MD5\"))\n assertThat(CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256)\n .isNotEqualTo(CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":77,"symbol":"forJavaName_acceptsArbitraryStrings","kind":"function","lang":"kotlin","code":"@Test\n fun forJavaName_acceptsArbitraryStrings() {\n // Shouldn't throw.\n forJavaName(\"example CipherSuite name that is not in the whitelist\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":83,"symbol":"javaName_examples","kind":"function","lang":"kotlin","code":"@Test\n fun javaName_examples() {\n assertThat(CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName)\n .isEqualTo(\"SSL_RSA_EXPORT_WITH_RC4_40_MD5\")\n assertThat(CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256.javaName)\n .isEqualTo(\"TLS_RSA_WITH_AES_128_CBC_SHA256\")\n assertThat(forJavaName(\"TestCipherSuite\").javaName)\n .isEqualTo(\"TestCipherSuite\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":93,"symbol":"javaName_equalsToString","kind":"function","lang":"kotlin","code":"@Test\n fun javaName_equalsToString() {\n assertThat(CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5.toString())\n .isEqualTo(CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5.javaName)\n assertThat(CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256.toString())\n .isEqualTo(CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256.javaName)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":108,"symbol":"forJavaName_fromLegacyEnumName","kind":"function","lang":"kotlin","doc":"On the Oracle JVM some older cipher suites have the \"SSL_\" prefix and others have the \"TLS_\" prefix. On the IBM JVM all cipher suites have the \"SSL_\" prefix. Prior to OkHttp 3.3.1 we accepted either form and consider them equivalent. And since OkHttp 3.7.0 this is also true. But OkHttp 3.3.1 through 3.6.0 treated these as different.","code":"@Test\n fun forJavaName_fromLegacyEnumName() {\n // These would have been considered equal in OkHttp 3.3.1, but now aren't.\n assertThat(forJavaName(\"SSL_RSA_EXPORT_WITH_RC4_40_MD5\"))\n .isEqualTo(forJavaName(\"TLS_RSA_EXPORT_WITH_RC4_40_MD5\"))\n assertThat(forJavaName(\"SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA\"))\n .isEqualTo(forJavaName(\"TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA\"))\n assertThat(forJavaName(\"SSL_FAKE_NEW_CIPHER\"))\n .isEqualTo(forJavaName(\"TLS_FAKE_NEW_CIPHER\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":119,"symbol":"applyIntersectionRetainsTlsPrefixes","kind":"function","lang":"kotlin","code":"@Test\n fun applyIntersectionRetainsTlsPrefixes() {\n val socket =\n FakeSslSocket(\n enabledProtocols = listOf(\"TLSv1\"),\n supportedCipherSuites = listOf(\"SSL_A\", \"SSL_B\", \"SSL_C\", \"SSL_D\", \"SSL_E\"),\n enabledCipherSuites = listOf(\"SSL_A\", \"SSL_B\", \"SSL_C\"),\n )\n val connectionSpec =\n ConnectionSpec\n .Builder(true)\n .tlsVersions(TlsVersion.TLS_1_0)\n .cipherSuites(\"TLS_A\", \"TLS_C\", \"TLS_E\")\n .build()\n applyConnectionSpec(connectionSpec, socket, false)\n assertThat(socket.enabledCipherSuites).containsExactly(\"TLS_A\", \"TLS_C\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":137,"symbol":"applyIntersectionRetainsSslPrefixes","kind":"function","lang":"kotlin","code":"@Test\n fun applyIntersectionRetainsSslPrefixes() {\n val socket =\n FakeSslSocket(\n enabledProtocols = listOf(\"TLSv1\"),\n supportedCipherSuites = listOf(\"TLS_A\", \"TLS_B\", \"TLS_C\", \"TLS_D\", \"TLS_E\"),\n enabledCipherSuites = listOf(\"TLS_A\", \"TLS_B\", \"TLS_C\"),\n )\n val connectionSpec =\n ConnectionSpec\n .Builder(true)\n .tlsVersions(TlsVersion.TLS_1_0)\n .cipherSuites(\"SSL_A\", \"SSL_C\", \"SSL_E\")\n .build()\n applyConnectionSpec(connectionSpec, socket, false)\n assertThat(socket.enabledCipherSuites).containsExactly(\"SSL_A\", \"SSL_C\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":155,"symbol":"applyIntersectionAddsSslScsvForFallback","kind":"function","lang":"kotlin","code":"@Test\n fun applyIntersectionAddsSslScsvForFallback() {\n val socket =\n FakeSslSocket(\n enabledProtocols = listOf(\"TLSv1\"),\n supportedCipherSuites = listOf(\"SSL_A\", \"SSL_FALLBACK_SCSV\"),\n enabledCipherSuites = listOf(\"SSL_A\"),\n )\n val connectionSpec =\n ConnectionSpec\n .Builder(true)\n .tlsVersions(TlsVersion.TLS_1_0)\n .cipherSuites(\"SSL_A\")\n .build()\n applyConnectionSpec(connectionSpec, socket, true)\n assertThat(socket.enabledCipherSuites).containsExactly(\"SSL_A\", \"SSL_FALLBACK_SCSV\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":173,"symbol":"applyIntersectionAddsTlsScsvForFallback","kind":"function","lang":"kotlin","code":"@Test\n fun applyIntersectionAddsTlsScsvForFallback() {\n val socket =\n FakeSslSocket(\n enabledProtocols = listOf(\"TLSv1\"),\n supportedCipherSuites = listOf(\"TLS_A\", \"TLS_FALLBACK_SCSV\"),\n enabledCipherSuites = listOf(\"TLS_A\"),\n )\n val connectionSpec =\n ConnectionSpec\n .Builder(true)\n .tlsVersions(TlsVersion.TLS_1_0)\n .cipherSuites(\"TLS_A\")\n .build()\n applyConnectionSpec(connectionSpec, socket, true)\n assertThat(socket.enabledCipherSuites).containsExactly(\"TLS_A\", \"TLS_FALLBACK_SCSV\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":191,"symbol":"applyIntersectionToProtocolVersion","kind":"function","lang":"kotlin","code":"@Test\n fun applyIntersectionToProtocolVersion() {\n val socket =\n FakeSslSocket(\n enabledProtocols = listOf(\"TLSv1\", \"TLSv1.1\", \"TLSv1.2\"),\n supportedCipherSuites = listOf(\"TLS_A\"),\n enabledCipherSuites = listOf(\"TLS_A\"),\n )\n val connectionSpec =\n ConnectionSpec\n .Builder(true)\n .tlsVersions(TlsVersion.TLS_1_1, TlsVersion.TLS_1_2, TlsVersion.TLS_1_3)\n .cipherSuites(\"TLS_A\")\n .build()\n applyConnectionSpec(connectionSpec, socket, false)\n assertThat(socket.enabledProtocols).containsExactly(\"TLSv1.1\", \"TLSv1.2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":209,"symbol":"FakeSslSocket","kind":"class","lang":"kotlin","code":"class FakeSslSocket(\n var enabledProtocols: List = listOf(TlsVersion.TLS_1_3.javaName),\n var supportedCipherSuites: List =\n listOf(\n CipherSuite.TLS_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_AES_256_GCM_SHA384.javaName,\n CipherSuite.TLS_CHACHA20_POLY1305_SHA256.javaName,\n ),\n var enabledCipherSuites: List = supportedCipherSuites,\n ) : DelegatingSSLSocket(null) {\n override fun getEnabledProtocols() = enabledProtocols.toTypedArray()\n\n override fun setEnabledProtocols(protocols: Array) {\n this.enabledProtocols = protocols.toList()\n }\n\n override fun getSupportedCipherSuites() = supportedCipherSuites.toTypedArray()\n\n override fun getEnabledCipherSuites() = enabledCipherSuites.toTypedArray()\n\n override fun setEnabledCipherSuites(suites: Array) {\n this.enabledCipherSuites = suites.toList()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":219,"symbol":"getEnabledProtocols","kind":"function","lang":"kotlin","code":"override fun getEnabledProtocols() = enabledProtocols.toTypedArray()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":221,"symbol":"setEnabledProtocols","kind":"function","lang":"kotlin","code":"override fun setEnabledProtocols(protocols: Array) {\n this.enabledProtocols = protocols.toList()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":225,"symbol":"getSupportedCipherSuites","kind":"function","lang":"kotlin","code":"override fun getSupportedCipherSuites() = supportedCipherSuites.toTypedArray()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":227,"symbol":"getEnabledCipherSuites","kind":"function","lang":"kotlin","code":"override fun getEnabledCipherSuites() = enabledCipherSuites.toTypedArray()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CipherSuiteTest.kt","line":229,"symbol":"setEnabledCipherSuites","kind":"function","lang":"kotlin","code":"override fun setEnabledCipherSuites(suites: Array) {\n this.enabledCipherSuites = suites.toList()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CommonRequestBodyTest.kt","line":23,"symbol":"CommonRequestBodyTest","kind":"class","lang":"kotlin","code":"class CommonRequestBodyTest {\n @Test\n fun correctContentType() {\n val body = \"Body\"\n val requestBody = body.toRequestBody(MediaType(\"text/plain\", \"text\", \"plain\", arrayOf()))\n\n val contentType = requestBody.contentType()!!\n\n assertThat(contentType.mediaType).isEqualTo(\"text/plain; charset=utf-8\")\n assertThat(contentType.parameter(\"charset\")).isEqualTo(\"utf-8\")\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CommonRequestBodyTest.kt","line":24,"symbol":"correctContentType","kind":"function","lang":"kotlin","code":"@Test\n fun correctContentType() {\n val body = \"Body\"\n val requestBody = body.toRequestBody(MediaType(\"text/plain\", \"text\", \"plain\", arrayOf()))\n\n val contentType = requestBody.contentType()!!\n\n assertThat(contentType.mediaType).isEqualTo(\"text/plain; charset=utf-8\")\n assertThat(contentType.parameter(\"charset\")).isEqualTo(\"utf-8\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":48,"symbol":"ConnectionCoalescingTest","kind":"class","lang":"kotlin","code":"class ConnectionCoalescingTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private lateinit var client: OkHttpClient\n private lateinit var rootCa: HeldCertificate\n private lateinit var certificate: HeldCertificate\n private val dns = FakeDns()\n private lateinit var url: HttpUrl\n private lateinit var serverIps: List\n\n @BeforeEach\n fun setUp() {\n platform.assumeHttp2Support()\n platform.assumeNotBouncyCastle()\n rootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(0)\n .commonName(\"root\")\n .build()\n certificate =\n HeldCertificate\n .Builder()\n .signedBy(rootCa)\n .serialNumber(2L)\n .commonName(server.hostName)\n .addSubjectAlternativeName(server.hostName)\n .addSubjectAlternativeName(\"san.com\")\n .addSubjectAlternativeName(\"*.wildcard.com\")\n .addSubjectAlternativeName(\"differentdns.com\")\n .build()\n serverIps = listOf(server.socketAddress.address)\n dns[server.hostName] = serverIps\n dns[\"s"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":65,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeHttp2Support()\n platform.assumeNotBouncyCastle()\n rootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(0)\n .commonName(\"root\")\n .build()\n certificate =\n HeldCertificate\n .Builder()\n .signedBy(rootCa)\n .serialNumber(2L)\n .commonName(server.hostName)\n .addSubjectAlternativeName(server.hostName)\n .addSubjectAlternativeName(\"san.com\")\n .addSubjectAlternativeName(\"*.wildcard.com\")\n .addSubjectAlternativeName(\"differentdns.com\")\n .build()\n serverIps = listOf(server.socketAddress.address)\n dns[server.hostName] = serverIps\n dns[\"san.com\"] = serverIps\n dns[\"nonsan.com\"] = serverIps\n dns[\"www.wildcard.com\"] = serverIps\n dns[\"differentdns.com\"] = listOf()\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(rootCa.certificate)\n .build()\n client =\n clientTestRule\n .newClientBuilder()\n .fastFallback(false) // Avoid data races.\n .dns(dns)\n .sslSocketFactory(\n handshakeCe"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":120,"symbol":"commonThenAlternative","kind":"function","lang":"kotlin","doc":"Test connecting to the main host then an alternative, although only subject alternative names are used if present no special consideration of common name.","code":"@Test\n fun commonThenAlternative() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n assert200Http2Response(execute(sanUrl), \"san.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":134,"symbol":"alternativeThenCommon","kind":"function","lang":"kotlin","doc":"Test connecting to an alternative host then common name, although only subject alternative names are used if present no special consideration of common name.","code":"@Test\n fun alternativeThenCommon() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n assert200Http2Response(execute(sanUrl), \"san.com\")\n assert200Http2Response(execute(url), server.hostName)\n assertThat(client.connectionPool.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":145,"symbol":"staleCoalescedConnection","kind":"function","lang":"kotlin","doc":"Test a previously coalesced connection that's no longer healthy.","code":"@Test\n fun staleCoalescedConnection() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n val connection = AtomicReference()\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(\n Interceptor { chain: Interceptor.Chain? ->\n connection.set(chain!!.connection())\n chain.proceed(chain.request())\n },\n ).build()\n dns[\"san.com\"] = Dns.SYSTEM.lookup(server.hostName).subList(0, 1)\n assert200Http2Response(execute(url), server.hostName)\n\n // Simulate a stale connection in the pool.\n connection.get()!!.socket().close()\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n assert200Http2Response(execute(sanUrl), \"san.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":179,"symbol":"coalescedConnectionDestroyedAfterAcquire","kind":"function","lang":"kotlin","doc":"- The first request \"wins the race\". - The second request discovers it \"lost the race\" and closes the connection it just opened. - The second request uses the coalesced connection from request1. - The coalesced connection is violently closed after servicing the first request. - The second request discovers the coalesced connection is unhealthy just after acquiring it.","code":"@Test\n fun coalescedConnectionDestroyedAfterAcquire() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n dns[\"san.com\"] = Dns.SYSTEM.lookup(server.hostName).subList(0, 1)\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n val latch1 = CountDownLatch(1)\n val latch2 = CountDownLatch(1)\n val latch3 = CountDownLatch(1)\n val latch4 = CountDownLatch(1)\n val listener1: EventListener =\n object : EventListener() {\n override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n try {\n // Wait for request2 to guarantee we make 2 separate connections to the server.\n latch1.await()\n } catch (e: InterruptedException) {\n throw AssertionError(e)\n }\n }\n\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n // We have the connection and it's in the pool. Let request2 proceed to make a connection.\n latch2.countDown()\n }\n }\n val request2Listener: EventListener =\n object : EventListener() {\n override fun con"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":191,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n try {\n // Wait for request2 to guarantee we make 2 separate connections to the server.\n latch1.await()\n } catch (e: InterruptedException) {\n throw AssertionError(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":204,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n // We have the connection and it's in the pool. Let request2 proceed to make a connection.\n latch2.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":214,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n // Let request1 proceed to make a connection.\n latch1.countDown()\n try {\n // Wait until request1 makes the connection and puts it in the connection pool.\n latch2.await()\n } catch (e: InterruptedException) {\n throw AssertionError(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":229,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n // We obtained the coalesced connection. Let request1 violently destroy it.\n latch3.countDown()\n try {\n latch4.await()\n } catch (e: InterruptedException) {\n throw AssertionError(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":259,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n try {\n // Wait until request2 acquires the connection before we destroy it violently.\n latch3.await()\n } catch (e: InterruptedException) {\n throw AssertionError(e)\n }\n assert200Http2Response(response, \"san.com\")\n connection.get()!!.socket().close()\n latch4.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":275,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":294,"symbol":"skipsWhenDnsDontMatch","kind":"function","lang":"kotlin","doc":"If the existing connection matches a SAN but not a match for DNS then skip.","code":"@Test\n fun skipsWhenDnsDontMatch() {\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val differentDnsUrl = url.newBuilder().host(\"differentdns.com\").build()\n assertFailsWith {\n execute(differentDnsUrl)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":304,"symbol":"skipsOnRedirectWhenDnsDontMatch","kind":"function","lang":"kotlin","code":"@Test\n fun skipsOnRedirectWhenDnsDontMatch() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .addHeader(\"Location\", url.newBuilder().host(\"differentdns.com\").build())\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"unexpected call\")\n .build(),\n )\n assertFailsWith {\n val response = execute(url)\n response.close()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":326,"symbol":"skipsWhenNotSubjectAltName","kind":"function","lang":"kotlin","doc":"Not in the certificate SAN.","code":"@Test\n fun skipsWhenNotSubjectAltName() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val nonsanUrl = url.newBuilder().host(\"nonsan.com\").build()\n assertFailsWith {\n execute(nonsanUrl)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":337,"symbol":"skipsOnRedirectWhenNotSubjectAltName","kind":"function","lang":"kotlin","code":"@Test\n fun skipsOnRedirectWhenNotSubjectAltName() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .addHeader(\"Location\", url.newBuilder().host(\"nonsan.com\").build())\n .build(),\n )\n server.enqueue(MockResponse())\n assertFailsWith {\n val response = execute(url)\n response.close()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":354,"symbol":"coalescesWhenCertificatePinsMatch","kind":"function","lang":"kotlin","doc":"Can still coalesce when pinning is used if pins match.","code":"@Test\n fun coalescesWhenCertificatePinsMatch() {\n val pinner =\n CertificatePinner\n .Builder()\n .add(\"san.com\", pin(certificate.certificate))\n .build()\n client = client.newBuilder().certificatePinner(pinner).build()\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n assert200Http2Response(execute(sanUrl), \"san.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":371,"symbol":"skipsWhenCertificatePinningFails","kind":"function","lang":"kotlin","doc":"Certificate pinning used and not a match will avoid coalescing and try to connect.","code":"@Test\n fun skipsWhenCertificatePinningFails() {\n val pinner =\n CertificatePinner\n .Builder()\n .add(\"san.com\", \"sha1/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=\")\n .build()\n client = client.newBuilder().certificatePinner(pinner).build()\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n assertFailsWith {\n execute(sanUrl)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":387,"symbol":"skipsOnRedirectWhenCertificatePinningFails","kind":"function","lang":"kotlin","code":"@Test\n fun skipsOnRedirectWhenCertificatePinningFails() {\n val pinner =\n CertificatePinner\n .Builder()\n .add(\"san.com\", \"sha1/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=\")\n .build()\n client = client.newBuilder().certificatePinner(pinner).build()\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .addHeader(\"Location\", url.newBuilder().host(\"san.com\").build())\n .build(),\n )\n server.enqueue(MockResponse())\n assertFailsWith {\n execute(url)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":412,"symbol":"skipsWhenHostnameVerifierUsed","kind":"function","lang":"kotlin","doc":"Skips coalescing when hostname verifier is overridden since the intention of the hostname verification is a black box.","code":"@Test\n fun skipsWhenHostnameVerifierUsed() {\n val verifier = HostnameVerifier { name: String?, session: SSLSession? -> true }\n client = client.newBuilder().hostnameVerifier(verifier).build()\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n assert200Http2Response(execute(sanUrl), \"san.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":424,"symbol":"skipsOnRedirectWhenHostnameVerifierUsed","kind":"function","lang":"kotlin","code":"@Test\n fun skipsOnRedirectWhenHostnameVerifierUsed() {\n val verifier = HostnameVerifier { name: String?, session: SSLSession? -> true }\n client = client.newBuilder().hostnameVerifier(verifier).build()\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .addHeader(\"Location\", url.newBuilder().host(\"san.com\").build())\n .build(),\n )\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), \"san.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(2)\n val c0e0 = server.takeRequest()\n assertThat(c0e0.connectionIndex).isEqualTo(0) // Fresh connection.\n val c1e0 = server.takeRequest()\n assertThat(c1e0.connectionIndex).isEqualTo(1) // Fresh connection.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":448,"symbol":"prefersExistingCompatible","kind":"function","lang":"kotlin","doc":"Check we would use an existing connection to a later DNS result instead of connecting to the first DNS result for the first time.","code":"@Test\n fun prefersExistingCompatible() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n val connectCount = AtomicInteger()\n val listener: EventListener =\n object : EventListener() {\n override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n connectCount.getAndIncrement()\n }\n }\n client =\n client\n .newBuilder()\n .eventListenerFactory(clientTestRule.wrap(listener))\n .build()\n assert200Http2Response(execute(url), server.hostName)\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n dns[\"san.com\"] =\n Arrays.asList(\n InetAddress.getByAddress(\"san.com\", byteArrayOf(0, 0, 0, 0)),\n serverIps[0],\n )\n assert200Http2Response(execute(sanUrl), \"san.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(1)\n assertThat(connectCount.get()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":455,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n connectCount.getAndIncrement()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":481,"symbol":"commonThenWildcard","kind":"function","lang":"kotlin","doc":"Check that wildcard SANs are supported.","code":"@Test\n fun commonThenWildcard() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val sanUrl = url.newBuilder().host(\"www.wildcard.com\").build()\n assert200Http2Response(execute(sanUrl), \"www.wildcard.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":492,"symbol":"worksWithNetworkInterceptors","kind":"function","lang":"kotlin","doc":"Network interceptors check for changes to target.","code":"@Test\n fun worksWithNetworkInterceptors() {\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(\n Interceptor { chain: Interceptor.Chain? ->\n chain!!.proceed(\n chain.request(),\n )\n },\n ).build()\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n assert200Http2Response(execute(sanUrl), \"san.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":512,"symbol":"misdirectedRequestResponseCode","kind":"function","lang":"kotlin","code":"@Test\n fun misdirectedRequestResponseCode() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"seed connection\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .code(421)\n .body(\"misdirected!\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"after misdirect\")\n .build(),\n )\n\n // Seed the connection pool.\n assert200Http2Response(execute(url), server.hostName)\n\n // Use the coalesced connection which should retry on a fresh connection.\n val sanUrl =\n url\n .newBuilder()\n .host(\"san.com\")\n .build()\n execute(sanUrl).use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.priorResponse!!.code).isEqualTo(421)\n assertThat(response.body.string()).isEqualTo(\"after misdirect\")\n }\n val c0e0 = server.takeRequest()\n assertThat(c0e0.connectionIndex).isEqualTo(0)\n assertThat(c0e0.exchangeIndex).isEqualTo(0)\n val c0e1 = server.takeRequest()\n assertThat(c0e1.connectionIndex).isEqualTo(0)\n assertThat(c0e1.exchangeIndex).isEqualTo(1)\n val c1e0 = server.takeRequest()\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":563,"symbol":"redirectWithDevSetup","kind":"function","lang":"kotlin","doc":"Won't coalesce if we can't clean certs e.g. a dev setup.","code":"@Test\n fun redirectWithDevSetup() {\n val trustManager: X509TrustManager =\n object : X509TrustManager {\n override fun checkClientTrusted(\n x509Certificates: Array,\n s: String,\n ) {\n }\n\n override fun checkServerTrusted(\n x509Certificates: Array,\n s: String,\n ) {\n }\n\n override fun getAcceptedIssuers(): Array = arrayOf()\n }\n client =\n client\n .newBuilder()\n .sslSocketFactory(client.sslSocketFactory, trustManager)\n .build()\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n assert200Http2Response(execute(url), server.hostName)\n val sanUrl = url.newBuilder().host(\"san.com\").build()\n assert200Http2Response(execute(sanUrl), \"san.com\")\n assertThat(client.connectionPool.connectionCount()).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":567,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n x509Certificates: Array,\n s: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":573,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n x509Certificates: Array,\n s: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":579,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = arrayOf()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":594,"symbol":"execute","kind":"function","lang":"kotlin","code":"private fun execute(url: HttpUrl) = client.newCall(Request(url = url)).execute()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionCoalescingTest.kt","line":596,"symbol":"assert200Http2Response","kind":"function","lang":"kotlin","code":"private fun assert200Http2Response(\n response: Response,\n expectedHost: String,\n ) {\n assertThat(response.code).isEqualTo(200)\n assertThat(response.request.url.host).isEqualTo(expectedHost)\n assertThat(response.protocol).isEqualTo(Protocol.HTTP_2)\n response.body.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":51,"symbol":"ConnectionListenerTest","kind":"class","lang":"kotlin","code":"@Flaky // STDOUT logging enabled for test\n@Timeout(30)\n@Tag(\"Slow\")\nopen class ConnectionListenerTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private val listener = RecordingConnectionListener()\n private val handshakeCertificates = localhost()\n\n open val fastFallback: Boolean get() = true\n\n private var client: OkHttpClient =\n clientTestRule\n .newClientBuilder()\n .connectionPool(ConnectionPool(connectionListener = listener))\n .fastFallback(fastFallback)\n .build()\n\n @BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n platform.assumeNotBouncyCastle()\n listener.forbidLock(get(client.connectionPool))\n listener.forbidLock(client.dispatcher)\n }\n\n @Test\n fun successfulCallEventSequence() {\n server.enqueue(MockResponse(body = \"abc\"))\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"abc\")\n r"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":76,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n platform.assumeNotBouncyCastle()\n listener.forbidLock(get(client.connectionPool))\n listener.forbidLock(client.dispatcher)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":84,"symbol":"successfulCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun successfulCallEventSequence() {\n server.enqueue(MockResponse(body = \"abc\"))\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"abc\")\n response.body.close()\n assertThat(listener.recordedEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":106,"symbol":"failedCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun failedCallEventSequence() {\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(2, TimeUnit.SECONDS)\n .build(),\n )\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofMillis(250))\n .build()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isIn(\"timeout\", \"Read timed out\")\n }\n assertThat(listener.recordedEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"NoNewExchanges\",\n \"ConnectionReleased\",\n \"ConnectionClosed\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":141,"symbol":"assertSuccessfulEventOrder","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun assertSuccessfulEventOrder() {\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.string()\n response.body.close()\n assertThat(listener.recordedEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":162,"symbol":"secondCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun secondCallEventSequence() {\n enableTls()\n server.protocols = listOf(Protocol.HTTP_2, Protocol.HTTP_1_1)\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n\n client\n .newCall(Request(server.url(\"/\")))\n .execute()\n .close()\n\n client\n .newCall(Request(server.url(\"/\")))\n .execute()\n .close()\n\n assertThat(listener.recordedEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":190,"symbol":"successfulEmptyH2CallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun successfulEmptyH2CallEventSequence() {\n enableTls()\n server.protocols = Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)\n server.enqueue(MockResponse())\n assertSuccessfulEventOrder()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":199,"symbol":"multipleDnsLookupsForSingleCall","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun multipleDnsLookupsForSingleCall() {\n server.enqueue(\n MockResponse(\n code = 301,\n headers = headersOf(\"Location\", \"http://www.fakeurl:\" + server.port),\n ),\n )\n server.enqueue(MockResponse())\n val dns = FakeDns()\n dns[\"fakeurl\"] = client.dns.lookup(server.hostName)\n dns[\"www.fakeurl\"] = client.dns.lookup(server.hostName)\n client =\n client\n .newBuilder()\n .dns(dns)\n .build()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(\"http://fakeurl:\" + server.port)\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n listener.removeUpToEvent(ConnectionEvent.ConnectEnd::class.java)\n listener.removeUpToEvent(ConnectionEvent.ConnectionReleased::class.java)\n listener.removeUpToEvent(ConnectionEvent.ConnectionAcquired::class.java)\n listener.removeUpToEvent(ConnectionEvent.ConnectionReleased::class.java)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":233,"symbol":"successfulConnect","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun successfulConnect() {\n server.enqueue(MockResponse())\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val address = client.dns.lookup(server.hostName)[0]\n val expectedAddress = InetSocketAddress(address, server.port)\n val event = listener.removeUpToEvent(ConnectionEvent.ConnectStart::class.java)\n assertThat(event.route.socketAddress).isEqualTo(expectedAddress)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":253,"symbol":"failedConnect","kind":"function","lang":"kotlin","code":"@Test\n @Throws(UnknownHostException::class)\n fun failedConnect() {\n enableTls()\n server.enqueue(MockResponse.Builder().failHandshake().build())\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n assertFailsWith {\n call.execute()\n }\n val address = client.dns.lookup(server.hostName)[0]\n val expectedAddress = InetSocketAddress(address, server.port)\n val event = listener.removeUpToEvent(ConnectionEvent.ConnectFailed::class.java)\n assertThat(event.route.socketAddress).isEqualTo(expectedAddress)\n\n // Read error: ssl=0x7fd1d8d0fee8: Failure in SSL library, usually a protocol error\n if (!platform.isConscrypt()) {\n assertThat(event.exception.message).isIn(\n \"Unexpected handshake message: client_hello\",\n \"(unexpected_message) Unexpected handshake message: client_hello\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":282,"symbol":"multipleConnectsForSingleCall","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun multipleConnectsForSingleCall() {\n enableTls()\n server.enqueue(MockResponse.Builder().failHandshake().build())\n server.enqueue(MockResponse())\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns())\n .build()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n assertThat(listener.recordedEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectFailed\",\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":313,"symbol":"successfulHttpProxyConnect","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun successfulHttpProxyConnect() {\n server.enqueue(MockResponse())\n val proxy = server.proxyAddress\n client =\n client\n .newBuilder()\n .proxy(proxy)\n .build()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(\"http://www.fakeurl\")\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n assertThat(listener.recordedEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n val event = listener.removeUpToEvent(ConnectionEvent.ConnectEnd::class.java)\n assertThat(event.connection.route().proxy).isEqualTo(proxy)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":343,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionListenerTest.kt","line":356,"symbol":"ConnectionListenerLegacyTest","kind":"class","lang":"kotlin","code":"@Flaky // STDOUT logging enabled for test\n@Timeout(30)\n@Tag(\"Slow\")\nclass ConnectionListenerLegacyTest : ConnectionListenerTest() {\n override val fastFallback get() = false\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":42,"symbol":"ConnectionReuseTest","kind":"class","lang":"kotlin","code":"@Timeout(30)\n@Tag(\"Slowish\")\nclass ConnectionReuseTest {\n @RegisterExtension\n val platform: PlatformRule = PlatformRule()\n\n @RegisterExtension\n val clientTestRule: OkHttpClientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private var client: OkHttpClient = clientTestRule.newClient()\n\n @Test\n fun connectionsAreReused() {\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n assertConnectionReused(request, request)\n }\n\n @Test\n fun connectionsAreReusedForPosts() {\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val request =\n Request(\n url = server.url(\"/\"),\n body = \"request body\".toRequestBody(\"text/plain\".toMediaType()),\n )\n assertConnectionReused(request, request)\n }\n\n @Test\n fun connectionsAreReusedWithHttp2() {\n enableHttp2()\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n assertConnectionReused(request"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":57,"symbol":"connectionsAreReused","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreReused() {\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n assertConnectionReused(request, request)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":65,"symbol":"connectionsAreReusedForPosts","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreReusedForPosts() {\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val request =\n Request(\n url = server.url(\"/\"),\n body = \"request body\".toRequestBody(\"text/plain\".toMediaType()),\n )\n assertConnectionReused(request, request)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":77,"symbol":"connectionsAreReusedWithHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreReusedWithHttp2() {\n enableHttp2()\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n assertConnectionReused(request, request)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":86,"symbol":"connectionsAreNotReusedWithRequestConnectionClose","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreNotReusedWithRequestConnectionClose() {\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val requestA =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"Connection\", \"close\")\n .build()\n val requestB = Request(server.url(\"/\"))\n assertConnectionNotReused(requestA, requestB)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":100,"symbol":"connectionsAreNotReusedWithResponseConnectionClose","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreNotReusedWithResponseConnectionClose() {\n server.enqueue(\n MockResponse(\n headers = headersOf(\"Connection\", \"close\"),\n body = \"a\",\n ),\n )\n server.enqueue(MockResponse(body = \"b\"))\n val requestA = Request(server.url(\"/\"))\n val requestB = Request(server.url(\"/\"))\n assertConnectionNotReused(requestA, requestB)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":114,"symbol":"connectionsAreNotReusedWithUnknownLengthResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreNotReusedWithUnknownLengthResponseBody() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"a\")\n .clearHeaders()\n .onResponseEnd(ShutdownConnection)\n .build(),\n )\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n assertConnectionNotReused(request, request)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":129,"symbol":"connectionsAreNotReusedIfPoolIsSizeZero","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreNotReusedIfPoolIsSizeZero() {\n client =\n client\n .newBuilder()\n .connectionPool(ConnectionPool(0, 5, TimeUnit.SECONDS))\n .build()\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n assertConnectionNotReused(request, request)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":142,"symbol":"connectionsReusedWithRedirectEvenIfPoolIsSizeZero","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsReusedWithRedirectEvenIfPoolIsSizeZero() {\n client =\n client\n .newBuilder()\n .connectionPool(ConnectionPool(0, 5, TimeUnit.SECONDS))\n .build()\n server.enqueue(\n MockResponse(\n code = 301,\n headers = headersOf(\"Location\", \"/b\"),\n body = \"a\",\n ),\n )\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n val response = client.newCall(request).execute()\n assertThat(response.body.string()).isEqualTo(\"b\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":164,"symbol":"connectionsNotReusedWithRedirectIfDiscardingResponseIsSlow","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsNotReusedWithRedirectIfDiscardingResponseIsSlow() {\n client =\n client\n .newBuilder()\n .connectionPool(ConnectionPool(0, 5, TimeUnit.SECONDS))\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .addHeader(\"Location: /b\")\n .bodyDelay(1, TimeUnit.SECONDS)\n .body(\"a\")\n .build(),\n )\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n val response = client.newCall(request).execute()\n assertThat(response.body.string()).isEqualTo(\"b\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":188,"symbol":"silentRetryWhenIdempotentRequestFailsOnReusedConnection","kind":"function","lang":"kotlin","code":"@Test\n fun silentRetryWhenIdempotentRequestFailsOnReusedConnection() {\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse.Builder().onResponseStart(CloseSocket()).build())\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n val responseA = client.newCall(request).execute()\n assertThat(responseA.body.string()).isEqualTo(\"a\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n val responseB = client.newCall(request).execute()\n assertThat(responseB.body.string()).isEqualTo(\"b\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":203,"symbol":"http2ConnectionsAreSharedBeforeResponseIsConsumed","kind":"function","lang":"kotlin","code":"@Test\n fun http2ConnectionsAreSharedBeforeResponseIsConsumed() {\n enableHttp2()\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n val request = Request(server.url(\"/\"))\n val response1 = client.newCall(request).execute()\n val response2 = client.newCall(request).execute()\n response1.body.string() // Discard the response body.\n response2.body.string() // Discard the response body.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":217,"symbol":"connectionsAreEvicted","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreEvicted() {\n server.enqueue(MockResponse(body = \"a\"))\n server.enqueue(MockResponse(body = \"b\"))\n client =\n client\n .newBuilder()\n .connectionPool(ConnectionPool(5, 250, TimeUnit.MILLISECONDS))\n .build()\n val request = Request(server.url(\"/\"))\n val response1 = client.newCall(request).execute()\n assertThat(response1.body.string()).isEqualTo(\"a\")\n\n // Give the thread pool a chance to evict.\n Thread.sleep(500)\n val response2 = client.newCall(request).execute()\n assertThat(response2.body.string()).isEqualTo(\"b\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":238,"symbol":"connectionsAreNotReusedIfSslSocketFactoryChanges","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreNotReusedIfSslSocketFactoryChanges() {\n enableHttps()\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n val request = Request(server.url(\"/\"))\n val response = client.newCall(request).execute()\n response.body.close()\n\n // This client shares a connection pool but has a different SSL socket factory.\n val handshakeCertificates2 = HandshakeCertificates.Builder().build()\n val anotherClient =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates2.sslSocketFactory(),\n handshakeCertificates2.trustManager,\n ).build()\n\n // This client fails to connect because the new SSL socket factory refuses.\n assertFailsWith {\n anotherClient.newCall(request).execute()\n }.also { expected ->\n when (expected) {\n is SSLException, is TlsFatalAlert -> {}\n\n else -> {\n throw expected\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":271,"symbol":"connectionsAreNotReusedIfHostnameVerifierChanges","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsAreNotReusedIfHostnameVerifierChanges() {\n enableHttps()\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n val request = Request(server.url(\"/\"))\n val response1 = client.newCall(request).execute()\n response1.body.close()\n\n // This client shares a connection pool but has a different SSL socket factory.\n val anotherClient =\n client\n .newBuilder()\n .hostnameVerifier(RecordingHostnameVerifier())\n .build()\n val response2 = anotherClient.newCall(request).execute()\n response2.body.close()\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":303,"symbol":"connectionsAreNotReusedIfNetworkInterceptorInterferes","kind":"function","lang":"kotlin","doc":"This test leaks a response body by not closing it. https://github.com/lysine-dev/okhttp/issues/2409","code":"@Test\n fun connectionsAreNotReusedIfNetworkInterceptorInterferes() {\n val responsesNotClosed: MutableList = ArrayList()\n client =\n client\n .newBuilder()\n // Since this test knowingly leaks a connection, avoid using the default shared connection\n // pool, which should remain clean for subsequent tests.\n .connectionPool(ConnectionPool())\n .addNetworkInterceptor(\n Interceptor { chain: Interceptor.Chain? ->\n val response =\n chain!!.proceed(\n chain.request(),\n )\n responsesNotClosed.add(response)\n response\n .newBuilder()\n .body(\"unrelated response body!\".toResponseBody(null))\n .build()\n },\n ).build()\n server.enqueue(\n MockResponse(\n code = 301,\n headers = headersOf(\"Location\", \"/b\"),\n body = \"/a has moved!\",\n ),\n )\n server.enqueue(\n MockResponse(body = \"/b is here\"),\n )\n val request = Request(server.url(\"/\"))\n val call = client.newCall(request)\n call.execute().use { response ->\n assertThat(\n response.body.string(),\n ).isEq"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":350,"symbol":"enableHttps","kind":"function","lang":"kotlin","code":"private fun enableHttps() {\n enableHttpsAndAlpn(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":354,"symbol":"enableHttp2","kind":"function","lang":"kotlin","code":"private fun enableHttp2() {\n platform.assumeHttp2Support()\n enableHttpsAndAlpn(Protocol.HTTP_2, Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":359,"symbol":"enableHttpsAndAlpn","kind":"function","lang":"kotlin","code":"private fun enableHttpsAndAlpn(vararg protocols: Protocol) {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .protocols(protocols.toList())\n .build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.protocols = client.protocols\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":373,"symbol":"assertConnectionReused","kind":"function","lang":"kotlin","code":"private fun assertConnectionReused(vararg requests: Request?) {\n for (i in requests.indices) {\n val response = client.newCall(requests[i]!!).execute()\n response.body.string() // Discard the response body.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(i)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionReuseTest.kt","line":381,"symbol":"assertConnectionNotReused","kind":"function","lang":"kotlin","code":"private fun assertConnectionNotReused(vararg requests: Request?) {\n for (request in requests) {\n val response = client.newCall(request!!).execute()\n response.body.string() // Discard the response body.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":37,"symbol":"ConnectionSpecTest","kind":"class","lang":"kotlin","code":"class ConnectionSpecTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @Test\n fun noTlsVersions() {\n assertFailsWith {\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .tlsVersions(*arrayOf())\n .build()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"At least one TLS version is required\")\n }\n }\n\n @Test\n fun noCipherSuites() {\n assertFailsWith {\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .cipherSuites(*arrayOf())\n .build()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"At least one cipher suite is required\")\n }\n }\n\n @Test\n fun cleartextBuilder() {\n val cleartextSpec = ConnectionSpec.Builder(false).build()\n assertThat(cleartextSpec.isTls).isFalse()\n }\n\n @Test\n fun tlsBuilder_explicitCiphers() {\n val tlsSpec =\n ConnectionSpec\n .Builder(true)\n .cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)\n .tlsVersions(TlsVersion.TLS_1_2)\n .supportsTlsExtensions(true)\n .build()\n assertThat(tlsSpec.cipherSuites"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":41,"symbol":"noTlsVersions","kind":"function","lang":"kotlin","code":"@Test\n fun noTlsVersions() {\n assertFailsWith {\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .tlsVersions(*arrayOf())\n .build()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"At least one TLS version is required\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":54,"symbol":"noCipherSuites","kind":"function","lang":"kotlin","code":"@Test\n fun noCipherSuites() {\n assertFailsWith {\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .cipherSuites(*arrayOf())\n .build()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"At least one cipher suite is required\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":67,"symbol":"cleartextBuilder","kind":"function","lang":"kotlin","code":"@Test\n fun cleartextBuilder() {\n val cleartextSpec = ConnectionSpec.Builder(false).build()\n assertThat(cleartextSpec.isTls).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":73,"symbol":"tlsBuilder_explicitCiphers","kind":"function","lang":"kotlin","code":"@Test\n fun tlsBuilder_explicitCiphers() {\n val tlsSpec =\n ConnectionSpec\n .Builder(true)\n .cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)\n .tlsVersions(TlsVersion.TLS_1_2)\n .supportsTlsExtensions(true)\n .build()\n assertThat(tlsSpec.cipherSuites!!.toList())\n .containsExactly(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)\n assertThat(tlsSpec.tlsVersions!!.toList())\n .containsExactly(TlsVersion.TLS_1_2)\n assertThat(tlsSpec.supportsTlsExtensions).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":89,"symbol":"tlsBuilder_defaultCiphers","kind":"function","lang":"kotlin","code":"@Test\n fun tlsBuilder_defaultCiphers() {\n val tlsSpec =\n ConnectionSpec\n .Builder(true)\n .tlsVersions(TlsVersion.TLS_1_2)\n .supportsTlsExtensions(true)\n .build()\n assertThat(tlsSpec.cipherSuites).isNull()\n assertThat(tlsSpec.tlsVersions!!.toList())\n .containsExactly(TlsVersion.TLS_1_2)\n assertThat(tlsSpec.supportsTlsExtensions).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":103,"symbol":"tls_defaultCiphers_noFallbackIndicator","kind":"function","lang":"kotlin","code":"@Test\n fun tls_defaultCiphers_noFallbackIndicator() {\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n val tlsSpec =\n ConnectionSpec\n .Builder(true)\n .tlsVersions(TlsVersion.TLS_1_2)\n .supportsTlsExtensions(false)\n .build()\n val socket = SSLSocketFactory.getDefault().createSocket() as SSLSocket\n socket.enabledCipherSuites =\n arrayOf(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA.javaName,\n )\n socket.enabledProtocols =\n arrayOf(\n TlsVersion.TLS_1_2.javaName,\n TlsVersion.TLS_1_1.javaName,\n )\n assertThat(tlsSpec.isCompatible(socket)).isTrue()\n applyConnectionSpec(tlsSpec, socket, isFallback = false)\n assertThat(socket.enabledProtocols).containsExactly(\n TlsVersion.TLS_1_2.javaName,\n )\n assertThat(socket.enabledCipherSuites.toList())\n .containsExactlyInAnyOrder(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA.javaName,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":136,"symbol":"tls_defaultCiphers_withFallbackIndicator","kind":"function","lang":"kotlin","code":"@Test\n fun tls_defaultCiphers_withFallbackIndicator() {\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n val tlsSpec =\n ConnectionSpec\n .Builder(true)\n .tlsVersions(TlsVersion.TLS_1_2)\n .supportsTlsExtensions(false)\n .build()\n val socket = SSLSocketFactory.getDefault().createSocket() as SSLSocket\n socket.enabledCipherSuites =\n arrayOf(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA.javaName,\n )\n socket.enabledProtocols =\n arrayOf(\n TlsVersion.TLS_1_2.javaName,\n TlsVersion.TLS_1_1.javaName,\n )\n assertThat(tlsSpec.isCompatible(socket)).isTrue()\n applyConnectionSpec(tlsSpec, socket, isFallback = true)\n assertThat(socket.enabledProtocols).containsExactly(\n TlsVersion.TLS_1_2.javaName,\n )\n val expectedCipherSuites: MutableList = ArrayList()\n expectedCipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName)\n expectedCipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA.javaName)\n if (listOf(*socket.supportedCipherSuites).contains(\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":172,"symbol":"tls_explicitCiphers","kind":"function","lang":"kotlin","code":"@Test\n fun tls_explicitCiphers() {\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n val tlsSpec =\n ConnectionSpec\n .Builder(true)\n .cipherSuites(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)\n .tlsVersions(TlsVersion.TLS_1_2)\n .supportsTlsExtensions(false)\n .build()\n val socket = SSLSocketFactory.getDefault().createSocket() as SSLSocket\n socket.enabledCipherSuites =\n arrayOf(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA.javaName,\n )\n socket.enabledProtocols =\n arrayOf(\n TlsVersion.TLS_1_2.javaName,\n TlsVersion.TLS_1_1.javaName,\n )\n assertThat(tlsSpec.isCompatible(socket)).isTrue()\n applyConnectionSpec(tlsSpec, socket, isFallback = true)\n assertThat(socket.enabledProtocols).containsExactly(\n TlsVersion.TLS_1_2.javaName,\n )\n val expectedCipherSuites: MutableList = ArrayList()\n expectedCipherSuites.add(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName)\n if (listOf(*socket.supportedCipherSuites).contains(\"TLS_FALLBACK_SCSV\")) {\n expec"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":208,"symbol":"tls_stringCiphersAndVersions","kind":"function","lang":"kotlin","code":"@Test\n fun tls_stringCiphersAndVersions() {\n // Supporting arbitrary input strings allows users to enable suites and versions that are not\n // yet known to the library, but are supported by the platform.\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .cipherSuites(\"MAGIC-CIPHER\")\n .tlsVersions(\"TLS9k\")\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":219,"symbol":"tls_missingRequiredCipher","kind":"function","lang":"kotlin","code":"@Test\n fun tls_missingRequiredCipher() {\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n val tlsSpec =\n ConnectionSpec\n .Builder(true)\n .cipherSuites(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)\n .tlsVersions(TlsVersion.TLS_1_2)\n .supportsTlsExtensions(false)\n .build()\n val socket = SSLSocketFactory.getDefault().createSocket() as SSLSocket\n socket.enabledProtocols =\n arrayOf(\n TlsVersion.TLS_1_2.javaName,\n TlsVersion.TLS_1_1.javaName,\n )\n socket.enabledCipherSuites =\n arrayOf(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA.javaName,\n )\n assertThat(tlsSpec.isCompatible(socket)).isTrue()\n socket.enabledCipherSuites =\n arrayOf(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA.javaName,\n )\n assertThat(tlsSpec.isCompatible(socket)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":249,"symbol":"allEnabledCipherSuites","kind":"function","lang":"kotlin","code":"@Test\n fun allEnabledCipherSuites() {\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n val tlsSpec =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .allEnabledCipherSuites()\n .build()\n assertThat(tlsSpec.cipherSuites).isNull()\n val sslSocket = SSLSocketFactory.getDefault().createSocket() as SSLSocket\n sslSocket.enabledCipherSuites =\n arrayOf(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA.javaName,\n )\n applyConnectionSpec(tlsSpec, sslSocket, false)\n if (platform.isAndroid) {\n // https://developer.android.com/reference/javax/net/ssl/SSLSocket\n val sdkVersion = platform.androidSdkVersion()\n if (sdkVersion != null && sdkVersion >= 29) {\n assertThat(sslSocket.enabledCipherSuites)\n .containsExactly(\n CipherSuite.TLS_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_AES_256_GCM_SHA384.javaName,\n CipherSuite.TLS_CHACHA20_POLY1305_SHA256.javaName,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":294,"symbol":"allEnabledTlsVersions","kind":"function","lang":"kotlin","code":"@Test\n fun allEnabledTlsVersions() {\n platform.assumeNotConscrypt()\n val tlsSpec =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .allEnabledTlsVersions()\n .build()\n assertThat(tlsSpec.tlsVersions).isNull()\n val sslSocket = SSLSocketFactory.getDefault().createSocket() as SSLSocket\n if (majorVersion > 11) {\n sslSocket.enabledProtocols =\n arrayOf(\n TlsVersion.SSL_3_0.javaName,\n TlsVersion.TLS_1_1.javaName,\n TlsVersion.TLS_1_2.javaName,\n TlsVersion.TLS_1_3.javaName,\n )\n } else {\n sslSocket.enabledProtocols =\n arrayOf(\n TlsVersion.SSL_3_0.javaName,\n TlsVersion.TLS_1_1.javaName,\n TlsVersion.TLS_1_2.javaName,\n )\n }\n applyConnectionSpec(tlsSpec, sslSocket, false)\n if (isAndroid) {\n val sdkVersion = platform.androidSdkVersion()\n // https://developer.android.com/reference/javax/net/ssl/SSLSocket\n if (sdkVersion != null && sdkVersion >= 29) {\n assertThat(sslSocket.enabledProtocols)\n .containsExactly(\n TlsVersion.TLS_1_1.javaName,\n TlsVersion.TLS_1_2.javaName,\n TlsVersio"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":365,"symbol":"tls_missingTlsVersion","kind":"function","lang":"kotlin","code":"@Test\n fun tls_missingTlsVersion() {\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n val tlsSpec =\n ConnectionSpec\n .Builder(true)\n .cipherSuites(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)\n .tlsVersions(TlsVersion.TLS_1_2)\n .supportsTlsExtensions(false)\n .build()\n val socket = SSLSocketFactory.getDefault().createSocket() as SSLSocket\n socket.enabledCipherSuites =\n arrayOf(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.javaName,\n )\n socket.enabledProtocols =\n arrayOf(\n TlsVersion.TLS_1_2.javaName,\n TlsVersion.TLS_1_1.javaName,\n )\n assertThat(tlsSpec.isCompatible(socket)).isTrue()\n socket.enabledProtocols = arrayOf(TlsVersion.TLS_1_1.javaName)\n assertThat(tlsSpec.isCompatible(socket)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":391,"symbol":"equalsAndHashCode","kind":"function","lang":"kotlin","code":"@Test\n fun equalsAndHashCode() {\n val allCipherSuites =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .allEnabledCipherSuites()\n .build()\n val allTlsVersions =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .allEnabledTlsVersions()\n .build()\n val set: MutableSet = CopyOnWriteArraySet()\n assertThat(set.add(ConnectionSpec.MODERN_TLS)).isTrue()\n assertThat(set.add(ConnectionSpec.COMPATIBLE_TLS)).isTrue()\n assertThat(set.add(ConnectionSpec.CLEARTEXT)).isTrue()\n assertThat(set.add(allTlsVersions)).isTrue()\n assertThat(set.add(allCipherSuites)).isTrue()\n allCipherSuites.hashCode()\n assertThat(allCipherSuites.equals(null)).isFalse()\n assertThat(set.remove(ConnectionSpec.MODERN_TLS)).isTrue()\n assertThat(set.remove(ConnectionSpec.COMPATIBLE_TLS))\n .isTrue()\n assertThat(set.remove(ConnectionSpec.CLEARTEXT)).isTrue()\n assertThat(set.remove(allTlsVersions)).isTrue()\n assertThat(set.remove(allCipherSuites)).isTrue()\n assertThat(set).isEmpty()\n allTlsVersions.hashCode()\n assertThat(allTlsVersions.equals(null)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":422,"symbol":"allEnabledToString","kind":"function","lang":"kotlin","code":"@Test\n fun allEnabledToString() {\n val connectionSpec =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .allEnabledTlsVersions()\n .allEnabledCipherSuites()\n .build()\n assertThat(connectionSpec.toString()).isEqualTo(\n \"ConnectionSpec(cipherSuites=[all enabled], tlsVersions=[all enabled], \" +\n \"supportsTlsExtensions=true)\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConnectionSpecTest.kt","line":436,"symbol":"simpleToString","kind":"function","lang":"kotlin","code":"@Test\n fun simpleToString() {\n val connectionSpec =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .tlsVersions(TlsVersion.TLS_1_2)\n .cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)\n .build()\n assertThat(connectionSpec.toString()).isEqualTo(\n \"ConnectionSpec(cipherSuites=[SSL_RSA_WITH_RC4_128_MD5], tlsVersions=[TLS_1_2], \" +\n \"supportsTlsExtensions=true)\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConscryptTest.kt","line":34,"symbol":"ConscryptTest","kind":"class","lang":"kotlin","code":"class ConscryptTest {\n @JvmField @RegisterExtension\n val platform = PlatformRule()\n\n @JvmField @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private val client = clientTestRule.newClient()\n\n @BeforeEach fun setUp() {\n platform.assumeConscrypt()\n }\n\n @Test\n fun testTrustManager() {\n assertThat(Conscrypt.isConscrypt(Platform.get().platformTrustManager())).isTrue()\n }\n\n @Test\n @Disabled\n fun testMozilla() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://mozilla.org/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }\n\n @Test\n @Disabled\n fun testGoogle() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://google.com/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n if (it.handshake!!.tlsVersion != TlsVersion.TLS_1_3) {\n System.err.println(\"Flaky TLSv1.3 with google\")\n// assertThat(it.handshake()!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }\n }\n\n @Tes"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConscryptTest.kt","line":43,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach fun setUp() {\n platform.assumeConscrypt()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConscryptTest.kt","line":47,"symbol":"testTrustManager","kind":"function","lang":"kotlin","code":"@Test\n fun testTrustManager() {\n assertThat(Conscrypt.isConscrypt(Platform.get().platformTrustManager())).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConscryptTest.kt","line":52,"symbol":"testMozilla","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun testMozilla() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://mozilla.org/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConscryptTest.kt","line":65,"symbol":"testGoogle","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun testGoogle() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://google.com/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n if (it.handshake!!.tlsVersion != TlsVersion.TLS_1_3) {\n System.err.println(\"Flaky TLSv1.3 with google\")\n// assertThat(it.handshake()!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConscryptTest.kt","line":81,"symbol":"testBuildIfSupported","kind":"function","lang":"kotlin","code":"@Test\n fun testBuildIfSupported() {\n val actual = ConscryptPlatform.buildIfSupported()\n assertThat(actual).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ConscryptTest.kt","line":87,"symbol":"testVersion","kind":"function","lang":"kotlin","code":"@Test\n fun testVersion() {\n val version = Conscrypt.version()\n\n assertTrue(ConscryptPlatform.atLeastVersion(1, 4, 9))\n assertTrue(ConscryptPlatform.atLeastVersion(version.major()))\n assertTrue(ConscryptPlatform.atLeastVersion(version.major(), version.minor()))\n assertTrue(ConscryptPlatform.atLeastVersion(version.major(), version.minor(), version.patch()))\n assertFalse(ConscryptPlatform.atLeastVersion(version.major(), version.minor(), version.patch() + 1))\n assertFalse(ConscryptPlatform.atLeastVersion(version.major(), version.minor() + 1))\n assertFalse(ConscryptPlatform.atLeastVersion(version.major() + 1))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":41,"symbol":"CookieTest","kind":"class","lang":"kotlin","code":"@Burst\nclass CookieTest {\n val url = \"https://example.com/\".toHttpUrl()\n\n @Test fun simpleCookie() {\n val cookie = parse(url, \"SID=31d4d96e407aad42\")\n assertThat(cookie.toString()).isEqualTo(\"SID=31d4d96e407aad42; path=/\")\n }\n\n @Test fun noEqualsSign() {\n assertThat(parse(url, \"foo\")).isNull()\n assertThat(parse(url, \"foo; Path=/\")).isNull()\n }\n\n @Test fun emptyName() {\n assertThat(parse(url, \"=b\")).isNull()\n assertThat(parse(url, \" =b\")).isNull()\n assertThat(parse(url, \"\\r\\t \\n=b\")).isNull()\n }\n\n @Test fun spaceInName() {\n assertThat(parse(url, \"a b=cd\")!!.name).isEqualTo(\"a b\")\n }\n\n @Test fun spaceInValue() {\n assertThat(parse(url, \"ab=c d\")!!.value).isEqualTo(\"c d\")\n }\n\n @Test fun trimLeadingAndTrailingWhitespaceFromName() {\n assertThat(parse(url, \" a=b\")!!.name).isEqualTo(\"a\")\n assertThat(parse(url, \"a =b\")!!.name).isEqualTo(\"a\")\n assertThat(parse(url, \"\\r\\t \\na\\n\\t \\n=b\")!!.name).isEqualTo(\"a\")\n }\n\n @Test fun emptyValue() {\n assertThat(parse(url, \"a=\")!!.value).isEqualTo(\"\")\n assertThat(parse(url, \"a= \")!!.value).isEqualTo(\"\")\n assertThat(parse(url, \"a=\\r\\t \\n\")!!.value).isEqualTo(\"\")\n }\n\n @Test fun trimLeadingAndTrai"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":45,"symbol":"simpleCookie","kind":"function","lang":"kotlin","code":"@Test fun simpleCookie() {\n val cookie = parse(url, \"SID=31d4d96e407aad42\")\n assertThat(cookie.toString()).isEqualTo(\"SID=31d4d96e407aad42; path=/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":50,"symbol":"noEqualsSign","kind":"function","lang":"kotlin","code":"@Test fun noEqualsSign() {\n assertThat(parse(url, \"foo\")).isNull()\n assertThat(parse(url, \"foo; Path=/\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":55,"symbol":"emptyName","kind":"function","lang":"kotlin","code":"@Test fun emptyName() {\n assertThat(parse(url, \"=b\")).isNull()\n assertThat(parse(url, \" =b\")).isNull()\n assertThat(parse(url, \"\\r\\t \\n=b\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":61,"symbol":"spaceInName","kind":"function","lang":"kotlin","code":"@Test fun spaceInName() {\n assertThat(parse(url, \"a b=cd\")!!.name).isEqualTo(\"a b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":65,"symbol":"spaceInValue","kind":"function","lang":"kotlin","code":"@Test fun spaceInValue() {\n assertThat(parse(url, \"ab=c d\")!!.value).isEqualTo(\"c d\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":69,"symbol":"trimLeadingAndTrailingWhitespaceFromName","kind":"function","lang":"kotlin","code":"@Test fun trimLeadingAndTrailingWhitespaceFromName() {\n assertThat(parse(url, \" a=b\")!!.name).isEqualTo(\"a\")\n assertThat(parse(url, \"a =b\")!!.name).isEqualTo(\"a\")\n assertThat(parse(url, \"\\r\\t \\na\\n\\t \\n=b\")!!.name).isEqualTo(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":75,"symbol":"emptyValue","kind":"function","lang":"kotlin","code":"@Test fun emptyValue() {\n assertThat(parse(url, \"a=\")!!.value).isEqualTo(\"\")\n assertThat(parse(url, \"a= \")!!.value).isEqualTo(\"\")\n assertThat(parse(url, \"a=\\r\\t \\n\")!!.value).isEqualTo(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":81,"symbol":"trimLeadingAndTrailingWhitespaceFromValue","kind":"function","lang":"kotlin","code":"@Test fun trimLeadingAndTrailingWhitespaceFromValue() {\n assertThat(parse(url, \"a= \")!!.value).isEqualTo(\"\")\n assertThat(parse(url, \"a= b\")!!.value).isEqualTo(\"b\")\n assertThat(parse(url, \"a=b \")!!.value).isEqualTo(\"b\")\n assertThat(parse(url, \"a=\\r\\t \\nb\\n\\t \\n\")!!.value).isEqualTo(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":88,"symbol":"invalidCharacters","kind":"function","lang":"kotlin","code":"@Test fun invalidCharacters() {\n assertThat(parse(url, \"a\\u0000b=cd\")).isNull()\n assertThat(parse(url, \"ab=c\\u0000d\")).isNull()\n assertThat(parse(url, \"a\\u0001b=cd\")).isNull()\n assertThat(parse(url, \"ab=c\\u0001d\")).isNull()\n assertThat(parse(url, \"a\\u0009b=cd\")).isNull()\n assertThat(parse(url, \"ab=c\\u0009d\")).isNull()\n assertThat(parse(url, \"a\\u001fb=cd\")).isNull()\n assertThat(parse(url, \"ab=c\\u001fd\")).isNull()\n assertThat(parse(url, \"a\\u007fb=cd\")).isNull()\n assertThat(parse(url, \"ab=c\\u007fd\")).isNull()\n assertThat(parse(url, \"a\\u0080b=cd\")).isNull()\n assertThat(parse(url, \"ab=c\\u0080d\")).isNull()\n assertThat(parse(url, \"a\\u00ffb=cd\")).isNull()\n assertThat(parse(url, \"ab=c\\u00ffd\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":105,"symbol":"maxAge","kind":"function","lang":"kotlin","code":"@Test fun maxAge() {\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=1\")!!.expiresAt).isEqualTo(51000L)\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=9223372036854724\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=9223372036854725\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=9223372036854726\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parseCookie(9223372036854773807L, url, \"a=b; Max-Age=1\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parseCookie(9223372036854773807L, url, \"a=b; Max-Age=2\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parseCookie(9223372036854773807L, url, \"a=b; Max-Age=3\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=10000000000000000000\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":123,"symbol":"maxAgeNonPositive","kind":"function","lang":"kotlin","code":"@Test fun maxAgeNonPositive() {\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=-1\")!!.expiresAt)\n .isEqualTo(Long.MIN_VALUE)\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=0\")!!.expiresAt)\n .isEqualTo(Long.MIN_VALUE)\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=-9223372036854775808\")!!.expiresAt)\n .isEqualTo(Long.MIN_VALUE)\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=-9223372036854775809\")!!.expiresAt)\n .isEqualTo(Long.MIN_VALUE)\n assertThat(parseCookie(50000L, url, \"a=b; Max-Age=-10000000000000000000\")!!.expiresAt)\n .isEqualTo(Long.MIN_VALUE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":136,"symbol":"domainAndPath","kind":"function","lang":"kotlin","code":"@Test fun domainAndPath() {\n val cookie = parse(url, \"SID=31d4d96e407aad42; Path=/; Domain=example.com\")\n assertThat(cookie!!.domain).isEqualTo(\"example.com\")\n assertThat(cookie.path).isEqualTo(\"/\")\n assertThat(cookie.hostOnly).isFalse()\n assertThat(cookie.toString()).isEqualTo(\"SID=31d4d96e407aad42; domain=example.com; path=/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":144,"symbol":"secureAndHttpOnly","kind":"function","lang":"kotlin","code":"@Test fun secureAndHttpOnly() {\n val cookie = parse(url, \"SID=31d4d96e407aad42; Path=/; Secure; HttpOnly\")\n assertThat(cookie!!.secure).isTrue()\n assertThat(cookie.httpOnly).isTrue()\n assertThat(cookie.toString()).isEqualTo(\"SID=31d4d96e407aad42; path=/; secure; httponly\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":151,"symbol":"expiresDate","kind":"function","lang":"kotlin","code":"@Test fun expiresDate() {\n assertThat(Date(parse(url, \"a=b; Expires=Thu, 01 Jan 1970 00:00:00 GMT\")!!.expiresAt))\n .isEqualTo(date(\"1970-01-01T00:00:00.000+0000\"))\n assertThat(Date(parse(url, \"a=b; Expires=Wed, 09 Jun 2021 10:18:14 GMT\")!!.expiresAt))\n .isEqualTo(date(\"2021-06-09T10:18:14.000+0000\"))\n assertThat(Date(parse(url, \"a=b; Expires=Sun, 06 Nov 1994 08:49:37 GMT\")!!.expiresAt))\n .isEqualTo(date(\"1994-11-06T08:49:37.000+0000\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":160,"symbol":"awkwardDates","kind":"function","lang":"kotlin","code":"@Test fun awkwardDates() {\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 70 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 January 1970 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Janucember 1970 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=Thu, 1 Jan 1970 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 1970 0:00:00 GMT\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 1970 00:0:00 GMT\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 1970 00:00:0 GMT\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=00:00:00 Thu, 01 Jan 1970 GMT\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=00:00:00 1970 Jan 01\")!!.expiresAt)\n .isEqualTo(0L)\n assertThat(parse(url, \"a=b; Expires=00:00:00 1970 Jan 1\")!!.expiresAt)\n .isEqualTo(0L)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":183,"symbol":"invalidYear","kind":"function","lang":"kotlin","code":"@Test fun invalidYear() {\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 1600 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 19999 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":192,"symbol":"invalidMonth","kind":"function","lang":"kotlin","code":"@Test fun invalidMonth() {\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Foo 1970 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Foocember 1970 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parse(url, \"a=b; Expires=Thu, 01 1970 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":201,"symbol":"invalidDayOfMonth","kind":"function","lang":"kotlin","code":"@Test fun invalidDayOfMonth() {\n assertThat(parse(url, \"a=b; Expires=Thu, 32 Jan 1970 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n assertThat(parse(url, \"a=b; Expires=Thu, Jan 1970 00:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":208,"symbol":"invalidHour","kind":"function","lang":"kotlin","code":"@Test fun invalidHour() {\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 1970 24:00:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":213,"symbol":"invalidMinute","kind":"function","lang":"kotlin","code":"@Test fun invalidMinute() {\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 1970 00:60:00 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":218,"symbol":"invalidSecond","kind":"function","lang":"kotlin","code":"@Test fun invalidSecond() {\n assertThat(parse(url, \"a=b; Expires=Thu, 01 Jan 1970 00:00:60 GMT\")!!.expiresAt)\n .isEqualTo(MAX_DATE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":223,"symbol":"domainMatches","kind":"function","lang":"kotlin","code":"@Test fun domainMatches() {\n val cookie = parse(url, \"a=b; domain=example.com\")\n assertThat(cookie!!.matches(\"http://example.com\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://www.example.com\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://square.com\".toHttpUrl())).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":231,"symbol":"domainMatchesNoDomain","kind":"function","lang":"kotlin","doc":"If no domain is present, match only the origin domain.","code":"@Test fun domainMatchesNoDomain() {\n val cookie = parse(url, \"a=b\")\n assertThat(cookie!!.matches(\"http://example.com\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://www.example.com\".toHttpUrl())).isFalse()\n assertThat(cookie.matches(\"http://square.com\".toHttpUrl())).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":239,"symbol":"domainMatchesIgnoresLeadingDot","kind":"function","lang":"kotlin","doc":"Ignore an optional leading `.` in the domain.","code":"@Test fun domainMatchesIgnoresLeadingDot() {\n val cookie = parse(url, \"a=b; domain=.example.com\")\n assertThat(cookie!!.matches(\"http://example.com\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://www.example.com\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://square.com\".toHttpUrl())).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":247,"symbol":"domainIgnoredWithTrailingDot","kind":"function","lang":"kotlin","doc":"Ignore the entire attribute if the domain ends with `.`.","code":"@Test fun domainIgnoredWithTrailingDot() {\n val cookie = parse(url, \"a=b; domain=example.com.\")\n assertThat(cookie!!.matches(\"http://example.com\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://www.example.com\".toHttpUrl())).isFalse()\n assertThat(cookie.matches(\"http://square.com\".toHttpUrl())).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":254,"symbol":"idnDomainMatches","kind":"function","lang":"kotlin","code":"@Test fun idnDomainMatches() {\n val cookie = parse(\"http://☃.net/\".toHttpUrl(), \"a=b; domain=☃.net\")\n assertThat(cookie!!.matches(\"http://☃.net/\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://xn--n3h.net/\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://www.☃.net/\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://www.xn--n3h.net/\".toHttpUrl())).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":262,"symbol":"punycodeDomainMatches","kind":"function","lang":"kotlin","code":"@Test fun punycodeDomainMatches() {\n val cookie = parse(\"http://xn--n3h.net/\".toHttpUrl(), \"a=b; domain=xn--n3h.net\")\n assertThat(cookie!!.matches(\"http://☃.net/\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://xn--n3h.net/\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://www.☃.net/\".toHttpUrl())).isTrue()\n assertThat(cookie.matches(\"http://www.xn--n3h.net/\".toHttpUrl())).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":270,"symbol":"domainMatchesIpAddress","kind":"function","lang":"kotlin","code":"@Test fun domainMatchesIpAddress() {\n val urlWithIp = \"http://123.45.234.56/\".toHttpUrl()\n assertThat(parse(urlWithIp, \"a=b; domain=234.56\")).isNull()\n assertThat(parse(urlWithIp, \"a=b; domain=123.45.234.56\")!!.domain).isEqualTo(\"123.45.234.56\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":276,"symbol":"domainMatchesIpv6Address","kind":"function","lang":"kotlin","code":"@Test fun domainMatchesIpv6Address() {\n val cookie = parse(\"http://[::1]/\".toHttpUrl(), \"a=b; domain=::1\")\n assertThat(cookie!!.domain).isEqualTo(\"::1\")\n assertThat(cookie.matches(\"http://[::1]/\".toHttpUrl())).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":282,"symbol":"domainMatchesIpv6AddressWithCompression","kind":"function","lang":"kotlin","code":"@Test fun domainMatchesIpv6AddressWithCompression() {\n val cookie = parse(\"http://[0001:0000::]/\".toHttpUrl(), \"a=b; domain=0001:0000::\")\n assertThat(cookie!!.domain).isEqualTo(\"1::\")\n assertThat(cookie.matches(\"http://[1::]/\".toHttpUrl())).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":288,"symbol":"domainMatchesIpv6AddressWithIpv4Suffix","kind":"function","lang":"kotlin","code":"@Test fun domainMatchesIpv6AddressWithIpv4Suffix() {\n val cookie =\n parse(\n \"http://[::1:ffff:ffff]/\".toHttpUrl(),\n \"a=b; domain=::1:255.255.255.255\",\n )\n assertThat(cookie!!.domain).isEqualTo(\"::1:ffff:ffff\")\n assertThat(cookie.matches(\"http://[::1:ffff:ffff]/\".toHttpUrl())).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":298,"symbol":"ipv6AddressDoesntMatch","kind":"function","lang":"kotlin","code":"@Test fun ipv6AddressDoesntMatch() {\n val cookie = parse(\"http://[::1]/\".toHttpUrl(), \"a=b; domain=::2\")\n assertThat(cookie).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":303,"symbol":"ipv6AddressMalformed","kind":"function","lang":"kotlin","code":"@Test fun ipv6AddressMalformed() {\n val cookie = parse(\"http://[::1]/\".toHttpUrl(), \"a=b; domain=::2::2\")\n assertThat(cookie!!.domain).isEqualTo(\"::1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":313,"symbol":"domainIsPublicSuffix","kind":"function","lang":"kotlin","doc":"These public suffixes were selected by inspecting the publicsuffix.org list. It's possible they may change in the future. If this test begins to fail, please double check they are still present in the public suffix list.","code":"@Test fun domainIsPublicSuffix() {\n val ascii = \"https://foo1.foo.bar.elb.amazonaws.com\".toHttpUrl()\n assertThat(parse(ascii, \"a=b; domain=foo.bar.elb.amazonaws.com\")).isNotNull()\n assertThat(parse(ascii, \"a=b; domain=bar.elb.amazonaws.com\")).isNull()\n assertThat(parse(ascii, \"a=b; domain=com\")).isNull()\n val unicode = \"https://長.長.長崎.jp\".toHttpUrl()\n assertThat(parse(unicode, \"a=b; domain=長.長崎.jp\")).isNotNull()\n assertThat(parse(unicode, \"a=b; domain=長崎.jp\")).isNull()\n val punycode = \"https://xn--ue5a.xn--ue5a.xn--8ltr62k.jp\".toHttpUrl()\n assertThat(parse(punycode, \"a=b; domain=xn--ue5a.xn--8ltr62k.jp\")).isNotNull()\n assertThat(parse(punycode, \"a=b; domain=xn--8ltr62k.jp\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":326,"symbol":"hostOnly","kind":"function","lang":"kotlin","code":"@Test fun hostOnly() {\n assertThat(parse(url, \"a=b\")!!.hostOnly).isTrue()\n assertThat(\n parse(url, \"a=b; domain=example.com\")!!.hostOnly,\n ).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":333,"symbol":"defaultPath","kind":"function","lang":"kotlin","code":"@Test fun defaultPath() {\n assertThat(parse(\"http://example.com/foo/bar\".toHttpUrl(), \"a=b\")!!.path).isEqualTo(\"/foo\")\n assertThat(parse(\"http://example.com/foo/\".toHttpUrl(), \"a=b\")!!.path).isEqualTo(\"/foo\")\n assertThat(parse(\"http://example.com/foo\".toHttpUrl(), \"a=b\")!!.path).isEqualTo(\"/\")\n assertThat(parse(\"http://example.com/\".toHttpUrl(), \"a=b\")!!.path).isEqualTo(\"/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":340,"symbol":"defaultPathIsUsedIfPathDoesntHaveLeadingSlash","kind":"function","lang":"kotlin","code":"@Test fun defaultPathIsUsedIfPathDoesntHaveLeadingSlash() {\n assertThat(\n parse(\"http://example.com/foo/bar\".toHttpUrl(), \"a=b; path=quux\")!!.path,\n ).isEqualTo(\"/foo\")\n assertThat(parse(\"http://example.com/foo/bar\".toHttpUrl(), \"a=b; path=\")!!.path)\n .isEqualTo(\"/foo\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":348,"symbol":"pathAttributeDoesntNeedToMatch","kind":"function","lang":"kotlin","code":"@Test fun pathAttributeDoesntNeedToMatch() {\n assertThat(parse(\"http://example.com/\".toHttpUrl(), \"a=b; path=/quux\")!!.path)\n .isEqualTo(\"/quux\")\n assertThat(parse(\"http://example.com/foo/bar\".toHttpUrl(), \"a=b; path=/quux\")!!.path)\n .isEqualTo(\"/quux\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":355,"symbol":"httpOnly","kind":"function","lang":"kotlin","code":"@Test fun httpOnly() {\n assertThat(parse(url, \"a=b\")!!.httpOnly).isFalse()\n assertThat(parse(url, \"a=b; HttpOnly\")!!.httpOnly).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":360,"symbol":"secure","kind":"function","lang":"kotlin","code":"@Test fun secure() {\n assertThat(parse(url, \"a=b\")!!.secure).isFalse()\n assertThat(parse(url, \"a=b; Secure\")!!.secure).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":365,"symbol":"maxAgeTakesPrecedenceOverExpires","kind":"function","lang":"kotlin","code":"@Test fun maxAgeTakesPrecedenceOverExpires() {\n // Max-Age = 1, Expires = 2. In either order.\n assertThat(parseCookie(0L, url, \"a=b; Max-Age=1; Expires=Thu, 01 Jan 1970 00:00:02 GMT\")!!.expiresAt)\n .isEqualTo(1000L)\n assertThat(parseCookie(0L, url, \"a=b; Expires=Thu, 01 Jan 1970 00:00:02 GMT; Max-Age=1\")!!.expiresAt)\n .isEqualTo(1000L)\n // Max-Age = 2, Expires = 1. In either order.\n assertThat(parseCookie(0L, url, \"a=b; Max-Age=2; Expires=Thu, 01 Jan 1970 00:00:01 GMT\")!!.expiresAt)\n .isEqualTo(2000L)\n assertThat(parseCookie(0L, url, \"a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=2\")!!.expiresAt)\n .isEqualTo(2000L)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":379,"symbol":"lastMaxAgeWins","kind":"function","lang":"kotlin","doc":"If a cookie incorrectly defines multiple 'Max-Age' attributes, the last one defined wins.","code":"@Test fun lastMaxAgeWins() {\n assertThat(parseCookie(0L, url, \"a=b; Max-Age=2; Max-Age=4; Max-Age=1; Max-Age=3\")!!.expiresAt)\n .isEqualTo(3000L)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":385,"symbol":"lastExpiresAtWins","kind":"function","lang":"kotlin","doc":"If a cookie incorrectly defines multiple 'Expires' attributes, the last one defined wins.","code":"@Test fun lastExpiresAtWins() {\n assertThat(\n parseCookie(\n 0L,\n url,\n \"a=b; \" +\n \"Expires=Thu, 01 Jan 1970 00:00:02 GMT; \" +\n \"Expires=Thu, 01 Jan 1970 00:00:04 GMT; \" +\n \"Expires=Thu, 01 Jan 1970 00:00:01 GMT; \" +\n \"Expires=Thu, 01 Jan 1970 00:00:03 GMT\",\n )!!.expiresAt,\n ).isEqualTo(3000L)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":399,"symbol":"maxAgeOrExpiresMakesCookiePersistent","kind":"function","lang":"kotlin","code":"@Test fun maxAgeOrExpiresMakesCookiePersistent() {\n assertThat(parseCookie(0L, url, \"a=b\")!!.persistent).isFalse()\n assertThat(parseCookie(0L, url, \"a=b; Max-Age=1\")!!.persistent).isTrue()\n assertThat(parseCookie(0L, url, \"a=b; Expires=Thu, 01 Jan 1970 00:00:01 GMT\")!!.persistent)\n .isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":406,"symbol":"parseAll","kind":"function","lang":"kotlin","code":"@Test fun parseAll() {\n val headers =\n Headers\n .Builder()\n .add(\"Set-Cookie: a=b\")\n .add(\"Set-Cookie: c=d\")\n .build()\n val cookies = parseAll(url, headers)\n assertThat(cookies.size).isEqualTo(2)\n assertThat(cookies[0].toString()).isEqualTo(\"a=b; path=/\")\n assertThat(cookies[1].toString()).isEqualTo(\"c=d; path=/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":419,"symbol":"builder","kind":"function","lang":"kotlin","code":"@Test fun builder() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .domain(\"example.com\")\n .build()\n assertThat(cookie.name).isEqualTo(\"a\")\n assertThat(cookie.value).isEqualTo(\"b\")\n assertThat(cookie.expiresAt).isEqualTo(MAX_DATE)\n assertThat(cookie.domain).isEqualTo(\"example.com\")\n assertThat(cookie.path).isEqualTo(\"/\")\n assertThat(cookie.secure).isFalse()\n assertThat(cookie.httpOnly).isFalse()\n assertThat(cookie.persistent).isFalse()\n assertThat(cookie.hostOnly).isFalse()\n assertThat(cookie.sameSite).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":439,"symbol":"newBuilder","kind":"function","lang":"kotlin","code":"@Test fun newBuilder() {\n val cookie =\n parseCookie(0L, url, \"c=d; Max-Age=1\")!!\n .newBuilder()\n .name(\"a\")\n .value(\"b\")\n .domain(\"example.com\")\n .expiresAt(MAX_DATE)\n .build()\n assertThat(cookie.name).isEqualTo(\"a\")\n assertThat(cookie.value).isEqualTo(\"b\")\n assertThat(cookie.expiresAt).isEqualTo(MAX_DATE)\n assertThat(cookie.domain).isEqualTo(\"example.com\")\n assertThat(cookie.path).isEqualTo(\"/\")\n assertThat(cookie.secure).isFalse()\n assertThat(cookie.httpOnly).isFalse()\n // can't be unset\n assertThat(cookie.persistent).isTrue()\n assertThat(cookie.hostOnly).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":460,"symbol":"builderNameValidation","kind":"function","lang":"kotlin","code":"@Test fun builderNameValidation() {\n assertFailsWith {\n Cookie.Builder().name(\" a \")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":466,"symbol":"builderValueValidation","kind":"function","lang":"kotlin","code":"@Test fun builderValueValidation() {\n assertFailsWith {\n Cookie.Builder().value(\" b \")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":472,"symbol":"builderClampsMaxDate","kind":"function","lang":"kotlin","code":"@Test fun builderClampsMaxDate() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .hostOnlyDomain(\"example.com\")\n .expiresAt(Long.MAX_VALUE)\n .build()\n assertThat(cookie.toString()).isEqualTo(\"a=b; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":484,"symbol":"builderExpiresAt","kind":"function","lang":"kotlin","code":"@Test fun builderExpiresAt() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .hostOnlyDomain(\"example.com\")\n .expiresAt(date(\"1970-01-01T00:00:01.000+0000\").time)\n .build()\n assertThat(cookie.toString()).isEqualTo(\"a=b; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":496,"symbol":"builderClampsMinDate","kind":"function","lang":"kotlin","code":"@Test fun builderClampsMinDate() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .hostOnlyDomain(\"example.com\")\n .expiresAt(date(\"1970-01-01T00:00:00.000+0000\").time)\n .build()\n assertThat(cookie.toString()).isEqualTo(\"a=b; max-age=0; path=/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":508,"symbol":"builderDomainValidation","kind":"function","lang":"kotlin","code":"@Test fun builderDomainValidation() {\n assertFailsWith {\n Cookie.Builder().hostOnlyDomain(\"a/b\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":514,"symbol":"builderDomain","kind":"function","lang":"kotlin","code":"@Test fun builderDomain() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .hostOnlyDomain(\"squareup.com\")\n .build()\n assertThat(cookie.domain).isEqualTo(\"squareup.com\")\n assertThat(cookie.hostOnly).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":526,"symbol":"builderPath","kind":"function","lang":"kotlin","code":"@Test fun builderPath() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .hostOnlyDomain(\"example.com\")\n .path(\"/foo\")\n .build()\n assertThat(cookie.path).isEqualTo(\"/foo\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":538,"symbol":"builderPathValidation","kind":"function","lang":"kotlin","code":"@Test fun builderPathValidation() {\n assertFailsWith {\n Cookie.Builder().path(\"foo\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":544,"symbol":"builderSecure","kind":"function","lang":"kotlin","code":"@Test fun builderSecure() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .hostOnlyDomain(\"example.com\")\n .secure()\n .build()\n assertThat(cookie.secure).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":556,"symbol":"builderHttpOnly","kind":"function","lang":"kotlin","code":"@Test fun builderHttpOnly() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .hostOnlyDomain(\"example.com\")\n .httpOnly()\n .build()\n assertThat(cookie.httpOnly).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookieTest.kt","line":568,"symbol":"builderIpv6","kind":"function","lang":"kotlin","code":"@Test fun builderIpv6() {\n val cookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .domain(\"0:0:0:0:0:0:0:1\")\n .build()\n assertThat(cookie.domain).isEqualTo(\"::1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookiesTest.kt","line":55,"symbol":"testNetscapeResponse","kind":"function","lang":"kotlin","code":"@Test\n fun testNetscapeResponse() {\n val cookieManager = CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)\n client =\n client\n .newBuilder()\n .cookieJar(JavaNetCookieJar(cookieManager))\n .build()\n val urlWithIpAddress = urlWithIpAddress(server, \"/path/foo\")\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\n \"Set-Cookie: a=android; \" +\n \"expires=Fri, 31-Dec-9999 23:59:59 GMT; \" +\n \"path=/path; \" +\n \"domain=${urlWithIpAddress.host}; \" +\n \"secure\",\n ).build(),\n )\n get(urlWithIpAddress)\n val cookies = cookieManager.cookieStore.cookies\n assertThat(cookies.size).isEqualTo(1)\n val cookie = cookies[0]\n assertThat(cookie.name).isEqualTo(\"a\")\n assertThat(cookie.value).isEqualTo(\"android\")\n assertThat(cookie.comment).isNull()\n assertThat(cookie.commentURL).isNull()\n assertThat(cookie.discard).isFalse()\n assertThat(cookie.maxAge).isGreaterThan(100000000000L)\n assertThat(cookie.path).isEqualTo(\"/path\")\n assertThat(cookie.secure).isTrue()\n assertThat(cookie.version).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookiesTest.kt","line":90,"symbol":"testRfc2109Response","kind":"function","lang":"kotlin","code":"@Test\n fun testRfc2109Response() {\n val cookieManager = CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)\n client =\n client\n .newBuilder()\n .cookieJar(JavaNetCookieJar(cookieManager))\n .build()\n val urlWithIpAddress = urlWithIpAddress(server, \"/path/foo\")\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\n \"Set-Cookie: a=android; \" +\n \"Comment=this cookie is delicious; \" +\n \"Domain=${urlWithIpAddress.host}; \" +\n \"Max-Age=60; \" +\n \"Path=/path; \" +\n \"Secure; \" +\n \"Version=1\",\n ).build(),\n )\n get(urlWithIpAddress)\n val cookies = cookieManager.cookieStore.cookies\n assertThat(cookies.size).isEqualTo(1)\n val cookie = cookies[0]\n assertThat(cookie.name).isEqualTo(\"a\")\n assertThat(cookie.value).isEqualTo(\"android\")\n assertThat(cookie.commentURL).isNull()\n assertThat(cookie.discard).isFalse()\n // Converting to a fixed date can cause rounding!\n assertThat(cookie.maxAge.toDouble()).isCloseTo(60.0, 5.0)\n assertThat(cookie.path).isEqualTo(\"/path\")\n assertThat(cookie.secure).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookiesTest.kt","line":126,"symbol":"testQuotedAttributeValues","kind":"function","lang":"kotlin","code":"@Test\n fun testQuotedAttributeValues() {\n val cookieManager = CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)\n client =\n client\n .newBuilder()\n .cookieJar(JavaNetCookieJar(cookieManager))\n .build()\n val urlWithIpAddress = urlWithIpAddress(server, \"/path/foo\")\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\n \"Set-Cookie: a=\\\"android\\\"; \" +\n \"Comment=\\\"this cookie is delicious\\\"; \" +\n \"CommentURL=\\\"http://google.com/\\\"; \" +\n \"Discard; \" +\n \"Domain=${urlWithIpAddress.host}; \" +\n \"Max-Age=60; \" +\n \"Path=\\\"/path\\\"; \" +\n \"Port=\\\"80,443,${server.port}\\\"; \" +\n \"Secure; \" +\n \"Version=\\\"1\\\"\",\n ).build(),\n )\n get(urlWithIpAddress)\n val cookies = cookieManager.cookieStore.cookies\n assertThat(cookies.size).isEqualTo(1)\n val cookie = cookies[0]\n assertThat(cookie.name).isEqualTo(\"a\")\n assertThat(cookie.value).isEqualTo(\"android\")\n // Converting to a fixed date can cause rounding!\n assertThat(cookie.maxAge.toDouble()).isCloseTo(60.0, 1.0)\n assertThat(cookie.path).isEqualTo(\"/path\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookiesTest.kt","line":163,"symbol":"testSendingCookiesFromStore","kind":"function","lang":"kotlin","code":"@Test\n fun testSendingCookiesFromStore() {\n server.enqueue(MockResponse())\n val serverUrl = urlWithIpAddress(server, \"/\")\n val cookieManager = CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)\n val cookieA = HttpCookie(\"a\", \"android\")\n cookieA.domain = serverUrl.host\n cookieA.path = \"/\"\n cookieManager.cookieStore.add(serverUrl.toUri(), cookieA)\n val cookieB = HttpCookie(\"b\", \"banana\")\n cookieB.domain = serverUrl.host\n cookieB.path = \"/\"\n cookieManager.cookieStore.add(serverUrl.toUri(), cookieB)\n client =\n client\n .newBuilder()\n .cookieJar(JavaNetCookieJar(cookieManager))\n .build()\n get(serverUrl)\n val request = server.takeRequest()\n assertThat(request.headers[\"Cookie\"]).isEqualTo(\"a=android; b=banana\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CookiesTest.kt","line":290,"symbol":"get","kind":"function","lang":"kotlin","code":"override fun get(\n uri: URI,\n requestHeaders: Map>,\n ) = mapOf(\n \"COOKIE\" to listOf(\"Bar=bar\"),\n \"cooKIE2\" to listOf(\"Baz=baz\"),\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CorrettoTest.kt","line":28,"symbol":"CorrettoTest","kind":"class","lang":"kotlin","code":"class CorrettoTest {\n @JvmField @RegisterExtension\n val platform = PlatformRule()\n\n @JvmField @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private val client = clientTestRule.newClient()\n\n @BeforeEach fun setUp() {\n platform.assumeCorretto()\n }\n\n @Test\n @Disabled\n fun testMozilla() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://mozilla.org/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }\n\n @Test\n @Disabled\n fun testGoogle() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://google.com/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n if (it.handshake!!.tlsVersion != TlsVersion.TLS_1_3) {\n System.err.println(\"Flaky TLSv1.3 with google\")\n// assertThat(it.handshake()!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }\n }\n\n @Test\n fun testIfSupported() {\n assertThat(PlatformRule.isCorrettoSupported).isTrue()\n assertThat(PlatformRule.isCorrettoInst"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CorrettoTest.kt","line":37,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach fun setUp() {\n platform.assumeCorretto()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CorrettoTest.kt","line":41,"symbol":"testMozilla","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun testMozilla() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://mozilla.org/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CorrettoTest.kt","line":54,"symbol":"testGoogle","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun testGoogle() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://google.com/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n if (it.handshake!!.tlsVersion != TlsVersion.TLS_1_3) {\n System.err.println(\"Flaky TLSv1.3 with google\")\n// assertThat(it.handshake()!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/CorrettoTest.kt","line":70,"symbol":"testIfSupported","kind":"function","lang":"kotlin","code":"@Test\n fun testIfSupported() {\n assertThat(PlatformRule.isCorrettoSupported).isTrue()\n assertThat(PlatformRule.isCorrettoInstalled).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherCleanupTest.kt","line":23,"symbol":"DispatcherCleanupTest","kind":"class","lang":"kotlin","code":"class DispatcherCleanupTest {\n @StartStop\n private val server = MockWebServer()\n\n @Test\n fun testFinish() {\n val okhttp = OkHttpClient()\n val callback =\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {}\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n }\n }\n repeat(10_000) {\n okhttp.newCall(Request.Builder().url(server.url(\"/\")).build()).enqueue(callback)\n }\n okhttp.dispatcher.executorService.shutdown()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherCleanupTest.kt","line":27,"symbol":"testFinish","kind":"function","lang":"kotlin","code":"@Test\n fun testFinish() {\n val okhttp = OkHttpClient()\n val callback =\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {}\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n }\n }\n repeat(10_000) {\n okhttp.newCall(Request.Builder().url(server.url(\"/\")).build()).enqueue(callback)\n }\n okhttp.dispatcher.executorService.shutdown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherCleanupTest.kt","line":32,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherCleanupTest.kt","line":37,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":44,"symbol":"DispatcherTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass DispatcherTest {\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n private val executor = RecordingExecutor(this)\n val callback = RecordingCallback()\n val webSocketListener =\n object : WebSocketListener() {\n }\n val dispatcher = Dispatcher(executor)\n val eventRecorder = EventRecorder()\n var client =\n clientTestRule\n .newClientBuilder()\n .dns { throw UnknownHostException() }\n .dispatcher(dispatcher)\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n\n @BeforeEach\n fun setUp() {\n dispatcher.maxRequests = 20\n dispatcher.maxRequestsPerHost = 10\n eventRecorder.forbidLock(dispatcher)\n }\n\n @Test\n fun maxRequestsZero() {\n assertFailsWith {\n dispatcher.maxRequests = 0\n }\n }\n\n @Test\n fun maxPerHostZero() {\n assertFailsWith {\n dispatcher.maxRequestsPerHost = 0\n }\n }\n\n @Test\n fun enqueuedJobsRunImmediately() {\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n executor.assertJobs(\"http://a/1\")\n\n assertThat(eventRecorder.eventSequence).none { it.isInstanceOf() }\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":63,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n dispatcher.maxRequests = 20\n dispatcher.maxRequestsPerHost = 10\n eventRecorder.forbidLock(dispatcher)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":70,"symbol":"maxRequestsZero","kind":"function","lang":"kotlin","code":"@Test\n fun maxRequestsZero() {\n assertFailsWith {\n dispatcher.maxRequests = 0\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":77,"symbol":"maxPerHostZero","kind":"function","lang":"kotlin","code":"@Test\n fun maxPerHostZero() {\n assertFailsWith {\n dispatcher.maxRequestsPerHost = 0\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":84,"symbol":"enqueuedJobsRunImmediately","kind":"function","lang":"kotlin","code":"@Test\n fun enqueuedJobsRunImmediately() {\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n executor.assertJobs(\"http://a/1\")\n\n assertThat(eventRecorder.eventSequence).none { it.isInstanceOf() }\n assertThat(eventRecorder.eventSequence).none { it.isInstanceOf() }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":93,"symbol":"maxRequestsEnforced","kind":"function","lang":"kotlin","code":"@Test\n fun maxRequestsEnforced() {\n dispatcher.maxRequests = 3\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/2\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/2\")).enqueue(callback)\n executor.assertJobs(\"http://a/1\", \"http://a/2\", \"http://b/1\")\n\n val dispatcherQueueStart = eventRecorder.removeUpToEvent()\n assertThat(dispatcherQueueStart.call.request().url).isEqualTo(\"http://b/2\".toHttpUrl())\n assertThat(eventRecorder.eventSequence).none { it.isInstanceOf() }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":107,"symbol":"maxPerHostEnforced","kind":"function","lang":"kotlin","code":"@Test\n fun maxPerHostEnforced() {\n dispatcher.maxRequestsPerHost = 2\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/2\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/3\")).enqueue(callback)\n executor.assertJobs(\"http://a/1\", \"http://a/2\")\n\n val dispatcherQueueStart = eventRecorder.removeUpToEvent()\n assertThat(dispatcherQueueStart.call.request().url).isEqualTo(\"http://a/3\".toHttpUrl())\n assertThat(eventRecorder.eventSequence).none { it.isInstanceOf() }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":120,"symbol":"maxPerHostNotEnforcedForWebSockets","kind":"function","lang":"kotlin","code":"@Test\n fun maxPerHostNotEnforcedForWebSockets() {\n dispatcher.maxRequestsPerHost = 2\n client.newWebSocket(newRequest(\"http://a/1\"), webSocketListener)\n client.newWebSocket(newRequest(\"http://a/2\"), webSocketListener)\n client.newWebSocket(newRequest(\"http://a/3\"), webSocketListener)\n executor.assertJobs(\"http://a/1\", \"http://a/2\", \"http://a/3\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":129,"symbol":"increasingMaxRequestsPromotesJobsImmediately","kind":"function","lang":"kotlin","code":"@Test\n fun increasingMaxRequestsPromotesJobsImmediately() {\n dispatcher.maxRequests = 2\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://c/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/2\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/2\")).enqueue(callback)\n\n val dispatcherQueueStartC1 = eventRecorder.removeUpToEvent()\n assertThat(dispatcherQueueStartC1.call.request().url).isEqualTo(\"http://c/1\".toHttpUrl())\n val dispatcherQueueStartA2 = eventRecorder.removeUpToEvent()\n assertThat(dispatcherQueueStartA2.call.request().url).isEqualTo(\"http://a/2\".toHttpUrl())\n val dispatcherQueueStartB2 = eventRecorder.removeUpToEvent()\n assertThat(dispatcherQueueStartB2.call.request().url).isEqualTo(\"http://b/2\".toHttpUrl())\n assertThat(eventRecorder.eventSequence).none { it.isInstanceOf() }\n\n dispatcher.maxRequests = 4\n executor.assertJobs(\"http://a/1\", \"http://b/1\", \"http://c/1\", \"http://a/2\")\n\n val dispatcherQueueEndC1 = eventRecorder."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":156,"symbol":"increasingMaxPerHostPromotesJobsImmediately","kind":"function","lang":"kotlin","code":"@Test\n fun increasingMaxPerHostPromotesJobsImmediately() {\n dispatcher.maxRequestsPerHost = 2\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/2\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/3\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/4\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/5\")).enqueue(callback)\n\n val dispatcherQueueStartA3 = eventRecorder.removeUpToEvent()\n assertThat(dispatcherQueueStartA3.call.request().url).isEqualTo(\"http://a/3\".toHttpUrl())\n val dispatcherQueueStartA4 = eventRecorder.removeUpToEvent()\n assertThat(dispatcherQueueStartA4.call.request().url).isEqualTo(\"http://a/4\".toHttpUrl())\n val dispatcherQueueStartA5 = eventRecorder.removeUpToEvent()\n assertThat(dispatcherQueueStartA5.call.request().url).isEqualTo(\"http://a/5\".toHttpUrl())\n assertThat(eventRecorder.eventSequence).none { it.isInstanceOf() }\n\n dispatcher.maxRequestsPerHost = 4\n executor.assertJobs(\"http://a/1\", \"http://a/2\", \"http://a/3\", \"http://a/4\")\n\n val dispatcherQueueEndA3 = e"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":183,"symbol":"oldJobFinishesNewJobCanRunDifferentHost","kind":"function","lang":"kotlin","code":"@Test\n fun oldJobFinishesNewJobCanRunDifferentHost() {\n dispatcher.maxRequests = 1\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/1\")).enqueue(callback)\n executor.finishJob(\"http://a/1\")\n executor.assertJobs(\"http://b/1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":192,"symbol":"oldJobFinishesNewJobWithSameHostStarts","kind":"function","lang":"kotlin","code":"@Test\n fun oldJobFinishesNewJobWithSameHostStarts() {\n dispatcher.maxRequests = 2\n dispatcher.maxRequestsPerHost = 1\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/2\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/2\")).enqueue(callback)\n executor.finishJob(\"http://a/1\")\n executor.assertJobs(\"http://b/1\", \"http://a/2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":204,"symbol":"oldJobFinishesNewJobCantRunDueToHostLimit","kind":"function","lang":"kotlin","code":"@Test\n fun oldJobFinishesNewJobCantRunDueToHostLimit() {\n dispatcher.maxRequestsPerHost = 1\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/2\")).enqueue(callback)\n executor.finishJob(\"http://b/1\")\n executor.assertJobs(\"http://a/1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":214,"symbol":"enqueuedCallsStillRespectMaxCallsPerHost","kind":"function","lang":"kotlin","code":"@Test\n fun enqueuedCallsStillRespectMaxCallsPerHost() {\n dispatcher.maxRequests = 1\n dispatcher.maxRequestsPerHost = 1\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/2\")).enqueue(callback)\n client.newCall(newRequest(\"http://b/3\")).enqueue(callback)\n dispatcher.maxRequests = 3\n executor.finishJob(\"http://a/1\")\n executor.assertJobs(\"http://b/1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":227,"symbol":"cancelingRunningJobTakesNoEffectUntilJobFinishes","kind":"function","lang":"kotlin","code":"@Test\n fun cancelingRunningJobTakesNoEffectUntilJobFinishes() {\n dispatcher.maxRequests = 1\n val c1 = client.newCall(newRequest(\"http://a/1\", \"tag1\"))\n val c2 = client.newCall(newRequest(\"http://a/2\"))\n c1.enqueue(callback)\n c2.enqueue(callback)\n c1.cancel()\n executor.assertJobs(\"http://a/1\")\n executor.finishJob(\"http://a/1\")\n executor.assertJobs(\"http://a/2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":240,"symbol":"asyncCallAccessors","kind":"function","lang":"kotlin","code":"@Test\n fun asyncCallAccessors() {\n dispatcher.maxRequests = 3\n val a1 = client.newCall(newRequest(\"http://a/1\"))\n val a2 = client.newCall(newRequest(\"http://a/2\"))\n val a3 = client.newCall(newRequest(\"http://a/3\"))\n val a4 = client.newCall(newRequest(\"http://a/4\"))\n val a5 = client.newCall(newRequest(\"http://a/5\"))\n a1.enqueue(callback)\n a2.enqueue(callback)\n a3.enqueue(callback)\n a4.enqueue(callback)\n a5.enqueue(callback)\n assertThat(dispatcher.runningCallsCount()).isEqualTo(3)\n assertThat(dispatcher.queuedCallsCount()).isEqualTo(2)\n assertThat(dispatcher.runningCalls())\n .containsExactlyInAnyOrder(a1, a2, a3)\n assertThat(dispatcher.queuedCalls())\n .containsExactlyInAnyOrder(a4, a5)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":261,"symbol":"synchronousCallAccessors","kind":"function","lang":"kotlin","code":"@Test\n fun synchronousCallAccessors() {\n val ready = CountDownLatch(2)\n val waiting = CountDownLatch(1)\n client =\n client\n .newBuilder()\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain? ->\n try {\n ready.countDown()\n waiting.await()\n } catch (e: InterruptedException) {\n throw AssertionError()\n }\n throw IOException()\n },\n ).build()\n val a1 = client.newCall(newRequest(\"http://a/1\"))\n val a2 = client.newCall(newRequest(\"http://a/2\"))\n val a3 = client.newCall(newRequest(\"http://a/3\"))\n val a4 = client.newCall(newRequest(\"http://a/4\"))\n val t1 = makeSynchronousCall(a1)\n val t2 = makeSynchronousCall(a2)\n\n // We created 4 calls and started 2 of them. That's 2 running calls and 0 queued.\n ready.await()\n assertThat(dispatcher.runningCallsCount()).isEqualTo(2)\n assertThat(dispatcher.queuedCallsCount()).isEqualTo(0)\n assertThat(dispatcher.runningCalls())\n .containsExactlyInAnyOrder(a1, a2)\n assertThat(dispatcher.queuedCalls()).isEmpty()\n\n // Cancel some calls. That doesn't impact running or queued.\n a2."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":321,"symbol":"idleCallbackInvokedWhenIdle","kind":"function","lang":"kotlin","code":"@Test\n fun idleCallbackInvokedWhenIdle() {\n val idle = AtomicBoolean()\n dispatcher.idleCallback = Runnable { idle.set(true) }\n client.newCall(newRequest(\"http://a/1\")).enqueue(callback)\n client.newCall(newRequest(\"http://a/2\")).enqueue(callback)\n executor.finishJob(\"http://a/1\")\n assertThat(idle.get()).isFalse()\n val ready = CountDownLatch(1)\n val proceed = CountDownLatch(1)\n client =\n client\n .newBuilder()\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain ->\n ready.countDown()\n try {\n proceed.await(5, TimeUnit.SECONDS)\n } catch (e: InterruptedException) {\n throw RuntimeException(e)\n }\n chain.proceed(chain.request())\n },\n ).build()\n val t1 = makeSynchronousCall(client.newCall(newRequest(\"http://a/3\")))\n ready.await(5, TimeUnit.SECONDS)\n executor.finishJob(\"http://a/2\")\n assertThat(idle.get()).isFalse()\n proceed.countDown()\n t1.join()\n assertThat(idle.get()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":354,"symbol":"executionRejectedImmediately","kind":"function","lang":"kotlin","code":"@Test\n fun executionRejectedImmediately() {\n val request = newRequest(\"http://a/1\")\n executor.shutdown()\n client.newCall(request).enqueue(callback)\n callback.await(request.url).assertFailure(InterruptedIOException::class.java)\n assertThat(eventRecorder.recordedEventTypes())\n .containsExactly(CallStart::class, CallFailed::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":364,"symbol":"executionRejectedAfterMaxRequestsChange","kind":"function","lang":"kotlin","code":"@Test\n fun executionRejectedAfterMaxRequestsChange() {\n val request1 = newRequest(\"http://a/1\")\n val request2 = newRequest(\"http://a/2\")\n dispatcher.maxRequests = 1\n client.newCall(request1).enqueue(callback)\n executor.shutdown()\n client.newCall(request2).enqueue(callback)\n dispatcher.maxRequests = 2 // Trigger promotion.\n callback.await(request2.url).assertFailure(InterruptedIOException::class.java)\n assertThat(eventRecorder.recordedEventTypes())\n .containsExactly(CallStart::class, CallStart::class, CallFailed::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":378,"symbol":"executionRejectedAfterMaxRequestsPerHostChange","kind":"function","lang":"kotlin","code":"@Test\n fun executionRejectedAfterMaxRequestsPerHostChange() {\n val request1 = newRequest(\"http://a/1\")\n val request2 = newRequest(\"http://a/2\")\n dispatcher.maxRequestsPerHost = 1\n client.newCall(request1).enqueue(callback)\n executor.shutdown()\n client.newCall(request2).enqueue(callback)\n dispatcher.maxRequestsPerHost = 2 // Trigger promotion.\n callback.await(request2.url).assertFailure(InterruptedIOException::class.java)\n assertThat(eventRecorder.recordedEventTypes())\n .containsExactly(CallStart::class, CallStart::class, CallFailed::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":392,"symbol":"executionRejectedAfterPrecedingCallFinishes","kind":"function","lang":"kotlin","code":"@Test\n fun executionRejectedAfterPrecedingCallFinishes() {\n val request1 = newRequest(\"http://a/1\")\n val request2 = newRequest(\"http://a/2\")\n dispatcher.maxRequests = 1\n client.newCall(request1).enqueue(callback)\n executor.shutdown()\n client.newCall(request2).enqueue(callback)\n executor.finishJob(\"http://a/1\") // Trigger promotion.\n callback.await(request2.url).assertFailure(InterruptedIOException::class.java)\n assertThat(eventRecorder.recordedEventTypes())\n .containsExactly(CallStart::class, CallStart::class, CallFailed::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":406,"symbol":"makeSynchronousCall","kind":"function","lang":"kotlin","code":"private fun makeSynchronousCall(call: Call): Thread {\n val thread =\n Thread {\n try {\n call.execute()\n throw AssertionError()\n } catch (expected: IOException) {\n }\n }\n thread.start()\n return thread\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":419,"symbol":"newRequest","kind":"function","lang":"kotlin","code":"private fun newRequest(url: String): Request = Request.Builder().url(url).build()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DispatcherTest.kt","line":421,"symbol":"newRequest","kind":"function","lang":"kotlin","code":"private fun newRequest(\n url: String,\n tag: String,\n ): Request =\n Request\n .Builder()\n .url(url)\n .tag(tag)\n .build()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":79,"symbol":"DuplexTest","kind":"class","lang":"kotlin","code":"@Timeout(30)\n@Tag(\"Slowish\")\nclass DuplexTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n var clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private var eventRecorder = EventRecorder()\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private var client =\n clientTestRule\n .newClientBuilder()\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n private val executorService = Executors.newScheduledThreadPool(1)\n\n @BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n platform.assumeHttp2Support()\n }\n\n @AfterEach\n fun tearDown() {\n executorService.shutdown()\n }\n\n @Test\n @Throws(IOException::class)\n fun http1DoesntSupportDuplex() {\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build(),\n )\n assertFailsWith {\n call.execute()\n }\n }\n\n @Test\n fun trueDuplexClientWritesFirst() {\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .receiveRequest(\"r"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":100,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n platform.assumeHttp2Support()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":106,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n executorService.shutdown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":111,"symbol":"http1DoesntSupportDuplex","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun http1DoesntSupportDuplex() {\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build(),\n )\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":127,"symbol":"trueDuplexClientWritesFirst","kind":"function","lang":"kotlin","code":"@Test\n fun trueDuplexClientWritesFirst() {\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .receiveRequest(\"request A\\n\")\n .sendResponse(\"response B\\n\")\n .receiveRequest(\"request C\\n\")\n .sendResponse(\"response D\\n\")\n .receiveRequest(\"request E\\n\")\n .sendResponse(\"response F\\n\")\n .exhaustRequest()\n .exhaustResponse()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .socketHandler(body)\n .build(),\n )\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build(),\n )\n call.execute().use { response ->\n val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink()\n requestBody.writeUtf8(\"request A\\n\")\n requestBody.flush()\n val responseBody = response.body.source()\n assertThat(responseBody.readUtf8Line())\n .isEqualTo(\"response B\")\n requestBody.writeUtf8(\"request C\\n\")\n requestBody.flush()\n assertThat(responseBody.readUtf8Line())\n .isEqualTo(\"response D\")\n requestBody.writeUtf8(\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":176,"symbol":"trueDuplexServerWritesFirst","kind":"function","lang":"kotlin","code":"@Test\n fun trueDuplexServerWritesFirst() {\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .sendResponse(\"response A\\n\")\n .receiveRequest(\"request B\\n\")\n .sendResponse(\"response C\\n\")\n .receiveRequest(\"request D\\n\")\n .sendResponse(\"response E\\n\")\n .receiveRequest(\"request F\\n\")\n .exhaustResponse()\n .exhaustRequest()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .socketHandler(body)\n .build(),\n )\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build(),\n )\n call.execute().use { response ->\n val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink()\n val responseBody = response.body.source()\n assertThat(responseBody.readUtf8Line())\n .isEqualTo(\"response A\")\n requestBody.writeUtf8(\"request B\\n\")\n requestBody.flush()\n assertThat(responseBody.readUtf8Line())\n .isEqualTo(\"response C\")\n requestBody.writeUtf8(\"request D\\n\")\n requestBody.flush()\n assertThat(responseBody"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":225,"symbol":"clientReadsHeadersDataTrailers","kind":"function","lang":"kotlin","code":"@Test\n fun clientReadsHeadersDataTrailers() {\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .sendResponse(\"ok\")\n .exhaustResponse()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .addHeader(\"h1\", \"v1\")\n .addHeader(\"h2\", \"v2\")\n .trailers(headersOf(\"trailers\", \"boom\"))\n .socketHandler(body)\n .build(),\n )\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n call.execute().use { response ->\n assertThat(response.headers)\n .isEqualTo(headersOf(\"h1\", \"v1\", \"h2\", \"v2\"))\n val responseBody = response.body.source()\n assertThat(responseBody.readUtf8(2)).isEqualTo(\"ok\")\n assertThat(responseBody.exhausted()).isTrue()\n assertThat(response.trailers()).isEqualTo(headersOf(\"trailers\", \"boom\"))\n }\n body.awaitSuccess()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":260,"symbol":"serverReadsHeadersData","kind":"function","lang":"kotlin","code":"@Test\n fun serverReadsHeadersData() {\n assumeNotWindows()\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .exhaustResponse()\n .receiveRequest(\"hey\\n\")\n .receiveRequest(\"whats going on\\n\")\n .exhaustRequest()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .addHeader(\"h1\", \"v1\")\n .addHeader(\"h2\", \"v2\")\n .socketHandler(body)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .method(\"POST\", AsyncRequestBody())\n .build()\n val call = client.newCall(request)\n call.execute().use { response ->\n val sink = (request.body as AsyncRequestBody?)!!.takeSink()\n sink.writeUtf8(\"hey\\n\")\n sink.writeUtf8(\"whats going on\\n\")\n sink.close()\n }\n body.awaitSuccess()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":295,"symbol":"requestBodyEndsAfterResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun requestBodyEndsAfterResponseBody() {\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .exhaustResponse()\n .receiveRequest(\"request A\\n\")\n .exhaustRequest()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .socketHandler(body)\n .build(),\n )\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build(),\n )\n call.execute().use { response ->\n val responseBody = response.body.source()\n assertTrue(responseBody.exhausted())\n val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink()\n requestBody.writeUtf8(\"request A\\n\")\n requestBody.close()\n }\n body.awaitSuccess()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n SecureConnectStart::class,\n SecureConnectEnd::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":351,"symbol":"duplexWith100Continue","kind":"function","lang":"kotlin","code":"@Test\n fun duplexWith100Continue() {\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .receiveRequest(\"request body\\n\")\n .sendResponse(\"response body\\n\")\n .exhaustRequest()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .add100Continue()\n .socketHandler(body)\n .build(),\n )\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"Expect\", \"100-continue\")\n .post(AsyncRequestBody())\n .build(),\n )\n call.execute().use { response ->\n val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink()\n requestBody.writeUtf8(\"request body\\n\")\n requestBody.flush()\n val responseBody = response.body.source()\n assertThat(responseBody.readUtf8Line())\n .isEqualTo(\"response body\")\n requestBody.close()\n assertThat(responseBody.readUtf8Line()).isNull()\n }\n body.awaitSuccess()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":394,"symbol":"duplexWithRedirect","kind":"function","lang":"kotlin","doc":"Duplex calls that have follow-ups are weird. By the time we know there's a follow-up we've already split off another thread to stream the request body. Because we permit at most one exchange at a time we break the request stream out from under that writer.","code":"@Test\n fun duplexWithRedirect() {\n enableProtocol(Protocol.HTTP_2)\n val duplexResponseSent = CountDownLatch(1)\n val requestHeadersEndListener =\n object : EventListener() {\n override fun requestHeadersEnd(\n call: Call,\n request: Request,\n ) {\n // Wait for the server to send the duplex response before acting on the 301 response\n // and resetting the stream.\n duplexResponseSent.await()\n }\n }\n client =\n client\n .newBuilder()\n .eventListener(eventRecorder.eventListener + requestHeadersEndListener)\n .build()\n val body =\n MockSocketHandler()\n .sendResponse(\"/a has moved!\\n\", duplexResponseSent)\n .requestIOException()\n .exhaustResponse()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .code(HttpURLConnection.HTTP_MOVED_PERM)\n .addHeader(\"Location: /b\")\n .socketHandler(body)\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"this is /b\")\n .build(),\n )\n val call =\n client.newCall(\n Request\n .Builder()\n .url("} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":400,"symbol":"requestHeadersEnd","kind":"function","lang":"kotlin","code":"override fun requestHeadersEnd(\n call: Call,\n request: Request,\n ) {\n // Wait for the server to send the duplex response before acting on the 301 response\n // and resetting the stream.\n duplexResponseSent.await()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":495,"symbol":"duplexWithAuthChallenge","kind":"function","lang":"kotlin","doc":"Auth requires follow-ups. Unlike redirects, the auth follow-up also has a request body. This test makes a single call with two duplex requests!","code":"@Test\n fun duplexWithAuthChallenge() {\n enableProtocol(Protocol.HTTP_2)\n val credential = basic(\"jesse\", \"secret\")\n client =\n client\n .newBuilder()\n .authenticator(RecordingOkAuthenticator(credential, null))\n .build()\n val body1 =\n MockSocketHandler()\n .sendResponse(\"please authenticate!\\n\")\n .requestIOException()\n .exhaustResponse()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .code(HttpURLConnection.HTTP_UNAUTHORIZED)\n .socketHandler(body1)\n .build(),\n )\n val body =\n MockSocketHandler()\n .sendResponse(\"response body\\n\")\n .exhaustResponse()\n .receiveRequest(\"request body\\n\")\n .exhaustRequest()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .socketHandler(body)\n .build(),\n )\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build(),\n )\n val response2 = call.execute()\n\n // First duplex request is detached with violence.\n val requestBody1 = (call.request()."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":565,"symbol":"fullCallTimeoutAppliesToSetup","kind":"function","lang":"kotlin","code":"@Test\n fun fullCallTimeoutAppliesToSetup() {\n enableProtocol(Protocol.HTTP_2)\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(500, TimeUnit.MILLISECONDS)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n assertTrue(call.isCanceled())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":590,"symbol":"fullCallTimeoutDoesNotApplyOnceConnected","kind":"function","lang":"kotlin","code":"@Test\n fun fullCallTimeoutDoesNotApplyOnceConnected() {\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .sendResponse(\"response A\\n\")\n .sleep(750, TimeUnit.MILLISECONDS)\n .sendResponse(\"response B\\n\")\n .receiveRequest(\"request C\\n\")\n .exhaustResponse()\n .exhaustRequest()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .socketHandler(body)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build()\n val call = client.newCall(request)\n call\n .timeout()\n .timeout(500, TimeUnit.MILLISECONDS) // Long enough for the first TLS handshake.\n call.execute().use { response ->\n val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink()\n val responseBody = response.body.source()\n assertThat(responseBody.readUtf8Line())\n .isEqualTo(\"response A\")\n assertThat(responseBody.readUtf8Line())\n .isEqualTo(\"response B\")\n requestBody.writeUtf8(\"request C\\n\")\n requestBody.close()\n assertThat(responseBody.readUtf8Line()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":632,"symbol":"duplexWithRewriteInterceptors","kind":"function","lang":"kotlin","code":"@Test\n fun duplexWithRewriteInterceptors() {\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .receiveRequest(\"REQUEST A\\n\")\n .sendResponse(\"response B\\n\")\n .exhaustRequest()\n .exhaustResponse()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .socketHandler(body)\n .build(),\n )\n client =\n client\n .newBuilder()\n .addInterceptor(UppercaseRequestInterceptor())\n .addInterceptor(UppercaseResponseInterceptor())\n .build()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(AsyncRequestBody())\n .build(),\n )\n call.execute().use { response ->\n val requestBody = (call.request().body as AsyncRequestBody?)!!.takeSink()\n requestBody.writeUtf8(\"request A\\n\")\n requestBody.flush()\n val responseBody = response.body.source()\n assertThat(responseBody.readUtf8Line())\n .isEqualTo(\"RESPONSE B\")\n requestBody.close()\n assertThat(responseBody.readUtf8Line()).isNull()\n }\n body.awaitSuccess()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":683,"symbol":"serverCancelsRequestBodyAndSendsResponseBody","kind":"function","lang":"kotlin","doc":"corresponding response body stream. This is necessary if we want servers to be able to stop inbound data and send an early 400 before the request body completes. This test sends a slow request that is canceled by the server. It expects the response to still be readable after the request stream is canceled.","code":"@Disabled\n @Test\n fun serverCancelsRequestBodyAndSendsResponseBody() {\n client =\n client\n .newBuilder()\n .retryOnConnectionFailure(false)\n .build()\n val log: BlockingQueue = LinkedBlockingQueue()\n enableProtocol(Protocol.HTTP_2)\n val body =\n MockSocketHandler()\n .sendResponse(\"success!\")\n .exhaustResponse()\n .cancelStream()\n server.enqueue(\n MockResponse\n .Builder()\n .clearHeaders()\n .socketHandler(body)\n .build(),\n )\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(\n object : RequestBody() {\n override fun contentType(): MediaType? = null\n\n override fun writeTo(sink: BufferedSink) {\n try {\n for (i in 0..9) {\n sink.writeUtf8(\".\")\n sink.flush()\n Thread.sleep(100)\n }\n } catch (e: IOException) {\n log.add(e.toString())\n throw e\n } catch (e: Exception) {\n log.add(e.toString())\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":712,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":714,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n try {\n for (i in 0..9) {\n sink.writeUtf8(\".\")\n sink.flush()\n Thread.sleep(100)\n }\n } catch (e: IOException) {\n log.add(e.toString())\n throw e\n } catch (e: Exception) {\n log.add(e.toString())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":743,"symbol":"headersReadTimeoutDoesNotStartUntilLastRequestBodyByteFire","kind":"function","lang":"kotlin","doc":"We delay sending the last byte of the request body 1500 ms. The 1000 ms read timeout should only elapse 1000 ms after the request body is sent.","code":"@Test\n fun headersReadTimeoutDoesNotStartUntilLastRequestBodyByteFire() {\n enableProtocol(Protocol.HTTP_2)\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(1500, TimeUnit.MILLISECONDS)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(DelayedRequestBody(\"hello\".toRequestBody(null), 1500, TimeUnit.MILLISECONDS))\n .build()\n client =\n client\n .newBuilder()\n .readTimeout(1000, TimeUnit.MILLISECONDS)\n .build()\n val call = client.newCall(request)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":772,"symbol":"bodyReadTimeoutDoesNotStartUntilLastRequestBodyByteFire","kind":"function","lang":"kotlin","doc":"Same as the previous test, but the server stalls sending the response body.","code":"@Test\n fun bodyReadTimeoutDoesNotStartUntilLastRequestBodyByteFire() {\n enableProtocol(Protocol.HTTP_2)\n server.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(1500, TimeUnit.MILLISECONDS)\n .body(\"this should never be received\")\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(DelayedRequestBody(\"hello\".toRequestBody(null), 1500, TimeUnit.MILLISECONDS))\n .build()\n client =\n client\n .newBuilder()\n .readTimeout(1000, TimeUnit.MILLISECONDS)\n .build()\n val call = client.newCall(request)\n val response = call.execute()\n assertFailsWith {\n response.body.string()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":806,"symbol":"headersReadTimeoutDoesNotStartUntilLastRequestBodyByteNoFire","kind":"function","lang":"kotlin","doc":"We delay sending the last byte of the request body 1500 ms. The 1000 ms read timeout shouldn't elapse because it shouldn't start until the request body is sent.","code":"@Test\n fun headersReadTimeoutDoesNotStartUntilLastRequestBodyByteNoFire() {\n enableProtocol(Protocol.HTTP_2)\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(500, TimeUnit.MILLISECONDS)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(DelayedRequestBody(\"hello\".toRequestBody(null), 1500, TimeUnit.MILLISECONDS))\n .build()\n client =\n client\n .newBuilder()\n .readTimeout(1000, TimeUnit.MILLISECONDS)\n .build()\n val call = client.newCall(request)\n val response = call.execute()\n assertThat(response.isSuccessful).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":835,"symbol":"bodyReadTimeoutDoesNotStartUntilLastRequestBodyByteNoFire","kind":"function","lang":"kotlin","doc":"We delay sending the last byte of the request body 1500 ms. The 1000 ms read timeout shouldn't elapse because it shouldn't start until the request body is sent.","code":"@Test\n fun bodyReadTimeoutDoesNotStartUntilLastRequestBodyByteNoFire() {\n enableProtocol(Protocol.HTTP_2)\n server.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(500, TimeUnit.MILLISECONDS)\n .body(\"success\")\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(DelayedRequestBody(\"hello\".toRequestBody(null), 1500, TimeUnit.MILLISECONDS))\n .build()\n client =\n client\n .newBuilder()\n .readTimeout(1000, TimeUnit.MILLISECONDS)\n .build()\n val call = client.newCall(request)\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"success\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":864,"symbol":"enableProtocol","kind":"function","lang":"kotlin","doc":"Tests that use this will fail unless boot classpath is set. Ex. `-Xbootclasspath/p:/tmp/alpn-boot-8.0.0.v20140317`","code":"private fun enableProtocol(protocol: Protocol) {\n enableTls()\n client =\n client\n .newBuilder()\n .protocols(listOf(protocol, Protocol.HTTP_1_1))\n .build()\n server.protocols = client.protocols\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":874,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":886,"symbol":"DelayedRequestBody","kind":"class","lang":"kotlin","code":"private inner class DelayedRequestBody(\n private val delegate: RequestBody,\n delay: Long,\n timeUnit: TimeUnit,\n ) : RequestBody() {\n private val delayMillis = timeUnit.toMillis(delay)\n\n override fun contentType() = delegate.contentType()\n\n override fun isDuplex() = true\n\n override fun writeTo(sink: BufferedSink) {\n executorService.schedule({\n try {\n delegate.writeTo(sink)\n sink.close()\n } catch (e: IOException) {\n throw RuntimeException(e)\n }\n }, delayMillis, TimeUnit.MILLISECONDS)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":893,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = delegate.contentType()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":895,"symbol":"isDuplex","kind":"function","lang":"kotlin","code":"override fun isDuplex() = true"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/DuplexTest.kt","line":897,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n executorService.schedule({\n try {\n delegate.writeTo(sink)\n sink.close()\n } catch (e: IOException) {\n throw RuntimeException(e)\n }\n }, delayMillis, TimeUnit.MILLISECONDS)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":51,"symbol":"EchOnFakeNetworkTest","kind":"class","lang":"kotlin","doc":"There's no support for Encrypted Client Hello (ECH) in any of our server-side SSL libraries, so we fake it with [FakeNetworkPlatform].","code":"@Burst\nclass EchOnFakeNetworkTest {\n private val platform = FakeNetworkPlatform()\n\n @RegisterExtension\n val platformRule =\n PlatformRule(\n platform = platform,\n )\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private val certificateAuthority =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .build()\n\n private val publicServerCertificate =\n HeldCertificate\n .Builder()\n .signedBy(certificateAuthority)\n .addSubjectAlternativeName(\"public.ech.example.com\")\n .build()\n private val publicServerCertificates =\n HandshakeCertificates\n .Builder()\n .heldCertificate(publicServerCertificate)\n .build()\n\n private val privateServerCertificate =\n HeldCertificate\n .Builder()\n .signedBy(certificateAuthority)\n .addSubjectAlternativeName(\"private.ech.example.com\")\n .build()\n private val privateServerCertificates =\n HandshakeCertificates\n .Builder()\n .heldCertificate(privateServerCertificate)\n .build()\n\n private val untrustedServerCertificate =\n HeldCertificate\n .Builder()\n .addSubjectAlternativeName(\"untrusted.ech.example.com\")\n .build("} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":158,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n server =\n MockWebServer()\n .apply {\n useHttps(privateServerCertificates.sslSocketFactory())\n }\n\n client =\n clientTestRule\n .newClientBuilder()\n .dns(dns)\n .sslSocketFactory(\n clientCertificates.sslSocketFactory(),\n clientCertificates.trustManager,\n ).build()\n\n server.start(serverIpAddress, 443)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":178,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n server.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":183,"symbol":"`server accepts ech`","kind":"function","lang":"kotlin","code":"@Test\n fun `server accepts ech`() {\n platform.handshaker = handshakerAcceptingEch()\n\n executeHttpExchange()\n\n assertThat(events.take())\n .isEqualTo(\"handshake hostname=private.ech.example.com echConfigList=$echConfigList\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":198,"symbol":"`ech is not used with proxy`","kind":"function","lang":"kotlin","doc":"When we do an HTTP `CONNECT` call, the proxy server is the computer that does a DNS lookup for the origin server (and not the client). Confirm that we don't use the proxy server's HTTPS record to handshake with the origin.","code":"@Test\n fun `ech is not used with proxy`() {\n platform.handshaker = handshakerAcceptingEch()\n\n client =\n client\n .newBuilder()\n .proxy(serverProxyAddress)\n .build()\n\n server.enqueue(\n MockResponse\n .Builder()\n .inTunnel()\n .build(),\n )\n\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n\n val request =\n Request(\n url = \"https://private.ech.example.com/\".toHttpUrl(),\n )\n\n val call = client.newCall(request)\n\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"abc\")\n\n val connectRequest = server.takeRequest()\n assertThat(connectRequest.method).isEqualTo(\"CONNECT\")\n assertThat(connectRequest.body).isNull()\n\n val getRequest = server.takeRequest()\n assertThat(getRequest.method).isEqualTo(\"GET\")\n assertThat(getRequest.body).isNull()\n\n assertThat(events.take())\n .isEqualTo(\"handshake hostname=private.ech.example.com echConfigList=null\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":252,"symbol":"`no fallback after ech failure`","kind":"function","lang":"kotlin","doc":"Unlike all other TLS failures, when ECH fails we don't fall back to another [ConnectionSpec] or [Route]. This is intended to prevent downgrade attacks. This runs with [fastFallback] enabled and disabled, because that mechanism is what decides whether a retry is attempted.","code":"@Test\n fun `no fallback after ech failure`(fastFallback: Boolean = false) {\n platform.handshaker = handshakerWithUnverifiedPublicName(attemptLimit = 1)\n\n // Configure multiple proxies so there's a route to fall back to. (But we won't use it, because\n // the purpose of this test is to confirm we don't fall back when doing so is insecure.)\n val proxySelector =\n RecordingProxySelector().apply {\n proxies += Proxy.NO_PROXY\n proxies += server.proxyAddress\n }\n\n client =\n client\n .newBuilder()\n .proxySelector(proxySelector)\n .fastFallback(fastFallback)\n .build()\n\n val e = failHttpExchange()\n assertThat(e).hasMessage(\"public_name 'public.ech.example.com' not verified\")\n\n assertThat(events.take())\n .isEqualTo(\"handshake hostname=private.ech.example.com echConfigList=$echConfigList\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":290,"symbol":"`server securely disables ech`","kind":"function","lang":"kotlin","doc":"The server responds with valid certificates for `ClientHelloOuter`, so the client retries the call without ECH. The SSL socket library uses an exception as the mechanism to indicate that ECH wasn't used.","code":"@Test\n fun `server securely disables ech`() {\n platform.handshaker =\n handshakerWithUpdatedEchConfigList(\n updatedEchConfigList = null,\n attemptLimit = 2,\n )\n\n executeHttpExchange()\n\n assertThat(events.take())\n .isEqualTo(\"handshake hostname=private.ech.example.com echConfigList=$echConfigList\")\n assertThat(events.take())\n .isEqualTo(\"handshake hostname=private.ech.example.com echConfigList=null\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":310,"symbol":"`server updates ech config for retry`","kind":"function","lang":"kotlin","doc":"This runs with [OkHttpClient.retryOnConnectionFailure] enabled and disabled. (We always want ECH retries, regardless of what this setting is.)","code":"@Test\n fun `server updates ech config for retry`(retryOnConnectionFailure: Boolean) {\n val updatedEchConfigList = \"new key to encrypt 'private.ech.example.com'\".encodeUtf8()\n platform.handshaker =\n handshakerWithUpdatedEchConfigList(\n updatedEchConfigList = updatedEchConfigList,\n attemptLimit = 2,\n )\n\n client =\n client\n .newBuilder()\n .retryOnConnectionFailure(retryOnConnectionFailure)\n .build()\n\n executeHttpExchange()\n\n assertThat(events.take())\n .isEqualTo(\"handshake hostname=private.ech.example.com echConfigList=$echConfigList\")\n assertThat(events.take())\n .isEqualTo(\"handshake hostname=private.ech.example.com echConfigList=$updatedEchConfigList\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":333,"symbol":"`server rejected because public name is not verified`","kind":"function","lang":"kotlin","code":"@Test\n fun `server rejected because public name is not verified`() {\n platform.handshaker = handshakerWithUnverifiedPublicName(attemptLimit = 1)\n\n val e = failHttpExchange()\n assertThat(e).hasMessage(\"public_name 'public.ech.example.com' not verified\")\n\n assertThat(events.take())\n .isEqualTo(\"handshake hostname=private.ech.example.com echConfigList=$echConfigList\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":344,"symbol":"`only two attempts are made`","kind":"function","lang":"kotlin","code":"@Test\n fun `only two attempts are made`() {\n val echConfigList2 = \"key #2 to encrypt 'private.ech.example.com'\".encodeUtf8()\n val echConfigList3 = \"key #3 to encrypt 'private.ech.example.com'\".encodeUtf8()\n platform.handshaker =\n object : Handshaker {\n val delegate = InsecureHandshaker()\n var handshakeCount = 0\n\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = publicServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"public.ech.example.com\",\n nextEchConfigList =\n when (handshakeCount++) {\n 0 -> echConfig"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":353,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = publicServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"public.ech.example.com\",\n nextEchConfigList =\n when (handshakeCount++) {\n 0 -> echConfigList2\n 1 -> echConfigList3\n else -> error(\"unexpected handshake\")\n },\n ),\n clientHandshake = publicNameHandshake.clientHandshake,\n serverHandshake = publicNameHandshake.serverHandshake,\n selectedProtocol = publicNameHandshake.selectedProtocol,\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":395,"symbol":"`only two attempts are made even if third attempt would disable ech`","kind":"function","lang":"kotlin","code":"@Test\n fun `only two attempts are made even if third attempt would disable ech`() {\n val echConfigList2 = \"key #2 to encrypt 'private.ech.example.com'\".encodeUtf8()\n platform.handshaker =\n object : Handshaker {\n val delegate = InsecureHandshaker()\n var handshakeCount = 0\n\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = publicServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"public.ech.example.com\",\n nextEchConfigList =\n when (handshakeCount++) {\n 0 -> echConfigList2\n 1 -> null\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":403,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = publicServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"public.ech.example.com\",\n nextEchConfigList =\n when (handshakeCount++) {\n 0 -> echConfigList2\n 1 -> null\n else -> error(\"unexpected handshake\")\n },\n ),\n clientHandshake = publicNameHandshake.clientHandshake,\n serverHandshake = publicNameHandshake.serverHandshake,\n selectedProtocol = publicNameHandshake.selectedProtocol,\n )\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":445,"symbol":"`no retry if public name is not a DNS hostname`","kind":"function","lang":"kotlin","code":"@Test\n fun `no retry if public name is not a DNS hostname`() {\n platform.handshaker =\n object : Handshaker {\n val delegate = InsecureHandshaker()\n var handshakeCount = 0\n\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n check(handshakeCount++ == 0)\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = ipAddressServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"10.20.30.40\",\n nextEchConfigList = null,\n ),\n clientHandshake = publicNameHandshake.clientHandshake,\n serverHandshake = publicNameHandshake.serverHandshake,\n selectedProtocol = publicNa"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":452,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n check(handshakeCount++ == 0)\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = ipAddressServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"10.20.30.40\",\n nextEchConfigList = null,\n ),\n clientHandshake = publicNameHandshake.clientHandshake,\n serverHandshake = publicNameHandshake.serverHandshake,\n selectedProtocol = publicNameHandshake.selectedProtocol,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":488,"symbol":"handshakerAcceptingEch","kind":"function","lang":"kotlin","code":"private fun handshakerAcceptingEch() =\n object : Handshaker {\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n return InsecureHandshaker().handshake(client, server)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":490,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n return InsecureHandshaker().handshake(client, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":499,"symbol":"handshakerWithUpdatedEchConfigList","kind":"function","lang":"kotlin","code":"private fun handshakerWithUpdatedEchConfigList(\n updatedEchConfigList: ByteString?,\n attemptLimit: Int,\n ) = object : Handshaker {\n val delegate = InsecureHandshaker()\n var handshakeCount = 0\n\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n val attempt = handshakeCount++\n check(attempt <= attemptLimit) { \"exceeded attempt limit\" }\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n when (attempt) {\n 0 -> {\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = publicServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"public.ech.example.com\",\n nextEchConfigList = updatedEchConfigList,\n ),\n clientHandshake = publicNameHandshake.clien"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":506,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n val attempt = handshakeCount++\n check(attempt <= attemptLimit) { \"exceeded attempt limit\" }\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n when (attempt) {\n 0 -> {\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = publicServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"public.ech.example.com\",\n nextEchConfigList = updatedEchConfigList,\n ),\n clientHandshake = publicNameHandshake.clientHandshake,\n serverHandshake = publicNameHandshake.serverHandshake,\n selectedProtocol = publicNameHandshake.selectedProtocol,\n )\n }\n\n 1 -> {\n return delegat"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":548,"symbol":"handshakerWithUnverifiedPublicName","kind":"function","lang":"kotlin","code":"private fun handshakerWithUnverifiedPublicName(attemptLimit: Int) =\n object : Handshaker {\n val delegate = InsecureHandshaker()\n var handshakeCount = 0\n\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n val attempt = handshakeCount++\n check(attempt <= attemptLimit) { \"exceeded attempt limit\" }\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = untrustedServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"public.ech.example.com\",\n nextEchConfigList = null,\n ),\n clientHandshake = publicNameHandshake.clientHandshake,\n serverHandshake = publicNameHandshake.serverHandshake,\n selectedProtocol = pub"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":553,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n val attempt = handshakeCount++\n check(attempt <= attemptLimit) { \"exceeded attempt limit\" }\n events.put(\"handshake hostname=${client.hostname} echConfigList=${client.echConfigList}\")\n\n val publicClient =\n client.copy(\n hostname = \"public.ech.example.com\",\n )\n val publicServer =\n server.copy(\n keyManager = untrustedServerCertificates.keyManager,\n )\n val publicNameHandshake = delegate.handshake(publicClient, publicServer)\n return Handshaker.Result.Failure(\n exception =\n EchRejectedException(\n publicName = \"public.ech.example.com\",\n nextEchConfigList = null,\n ),\n clientHandshake = publicNameHandshake.clientHandshake,\n serverHandshake = publicNameHandshake.serverHandshake,\n selectedProtocol = publicNameHandshake.selectedProtocol,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":583,"symbol":"executeHttpExchange","kind":"function","lang":"kotlin","code":"private fun executeHttpExchange() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n\n val request =\n Request(\n url = \"https://private.ech.example.com/\".toHttpUrl(),\n )\n\n val call = client.newCall(request)\n\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"abc\")\n\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"GET\")\n assertThat(recordedRequest.body).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EchOnFakeNetworkTest.kt","line":607,"symbol":"failHttpExchange","kind":"function","lang":"kotlin","code":"private fun failHttpExchange(): SSLException {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n\n val request =\n Request(\n url = \"https://private.ech.example.com/\".toHttpUrl(),\n )\n\n val call = client.newCall(request)\n\n return assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":108,"symbol":"EventListenerTest","kind":"class","lang":"kotlin","code":"@Flaky // STDOUT logging enabled for test\n@Timeout(30)\n@Tag(\"Slow\")\n@Burst\nclass EventListenerTest(\n val listenerInstalledOn: ListenerInstalledOn = ListenerInstalledOn.Client,\n) {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private val eventRecorder = EventRecorder()\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private var client =\n clientTestRule\n .newClientBuilder()\n .apply {\n if (listenerInstalledOn == ListenerInstalledOn.Client) {\n eventListenerFactory(clientTestRule.wrap(eventRecorder))\n }\n }.build()\n private var socksProxy: SocksProxy? = null\n private var cache: Cache? = null\n\n @BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n eventRecorder.forbidLock(get(client.connectionPool))\n eventRecorder.forbidLock(client.dispatcher)\n }\n\n @AfterEach\n fun tearDown() {\n if (socksProxy != null) {\n socksProxy!!.shutdown()\n }\n if (cache != null) {\n cache!!.delete()\n }\n }\n\n @Test\n fun successfulCallEventSequence() {\n server.enqueue(\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":137,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n eventRecorder.forbidLock(get(client.connectionPool))\n eventRecorder.forbidLock(client.dispatcher)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":144,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n if (socksProxy != null) {\n socksProxy!!.shutdown()\n }\n if (cache != null) {\n cache!!.delete()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":154,"symbol":"successfulCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun successfulCallEventSequence() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"abc\")\n response.body.close()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":194,"symbol":"successfulCallEventSequenceForIpAddress","kind":"function","lang":"kotlin","code":"@Test\n fun successfulCallEventSequenceForIpAddress() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val ipAddress = InetAddress.getLoopbackAddress().hostAddress\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(\n server\n .url(\"/\")\n .newBuilder()\n .host(ipAddress!!)\n .build(),\n ).build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"abc\")\n response.body.close()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":238,"symbol":"successfulCallEventSequenceForEnqueue","kind":"function","lang":"kotlin","code":"@Test\n fun successfulCallEventSequenceForEnqueue() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val completionLatch = CountDownLatch(1)\n val callback: Callback =\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n completionLatch.countDown()\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n completionLatch.countDown()\n }\n }\n call.enqueue(callback)\n completionLatch.await()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n F"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":256,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n completionLatch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":263,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n completionLatch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":294,"symbol":"failedCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun failedCallEventSequence() {\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(2, TimeUnit.SECONDS)\n .build(),\n )\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofMillis(250))\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isIn(\"timeout\", \"Read timed out\")\n }\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseFailed::class,\n RetryDecision::class,\n ConnectionReleased::class,\n CallFailed::class,\n )\n assertThat(eventRecorder.findEvent()).all {\n prop(RetryDecision::retry).isFalse()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":340,"symbol":"failedDribbledCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun failedDribbledCallEventSequence() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"0123456789\")\n .throttleBody(2, 100, TimeUnit.MILLISECONDS)\n .onResponseBody(CloseSocket())\n .build(),\n )\n client =\n client\n .newBuilder()\n .protocols(listOf(Protocol.HTTP_1_1))\n .readTimeout(Duration.ofMillis(250))\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertFailsWith {\n response.body.string()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"unexpected end of stream\")\n }\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecisio"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":392,"symbol":"canceledCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun canceledCallEventSequence() {\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n call.cancel()\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Canceled\")\n }\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n Canceled::class,\n CallStart::class,\n CallFailed::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":414,"symbol":"cancelAsyncCall","kind":"function","lang":"kotlin","code":"@Test\n fun cancelAsyncCall() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n call.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n }\n },\n )\n call.cancel()\n assertThat(eventRecorder.recordedEventTypes()).contains(Canceled::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":431,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":437,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":449,"symbol":"multipleCancelsEmitsOnlyOneEvent","kind":"function","lang":"kotlin","code":"@Test\n fun multipleCancelsEmitsOnlyOneEvent() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n call.cancel()\n call.cancel()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(Canceled::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":469,"symbol":"assertSuccessfulEventOrder","kind":"function","lang":"kotlin","code":"private fun assertSuccessfulEventOrder(\n responseMatcher: Matcher?,\n emptyBody: Boolean = false,\n ) {\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.string()\n response.body.close()\n assumeThat(response, responseMatcher)\n var expectedEventTypes =\n listOf(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n SecureConnectStart::class,\n SecureConnectEnd::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n )\n expectedEventTypes +=\n when {\n emptyBody -> {\n listOf(\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n FollowUpDecision::class,\n )\n }\n\n else -> {\n listOf(\n FollowUp"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":528,"symbol":"secondCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun secondCallEventSequence() {\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n client\n .newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n ).execute()\n .close()\n eventRecorder.removeUpToEvent()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n response.close()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n FollowUpDecision::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":567,"symbol":"assertBytesReadWritten","kind":"function","lang":"kotlin","code":"private fun assertBytesReadWritten(\n listener: EventRecorder,\n requestHeaderLength: Matcher?,\n requestBodyBytes: Matcher?,\n responseHeaderLength: Matcher?,\n responseBodyBytes: Matcher?,\n ) {\n if (requestHeaderLength != null) {\n val responseHeadersEnd = listener.removeUpToEvent()\n MatcherAssert.assertThat(\n \"request header length\",\n responseHeadersEnd.headerLength,\n requestHeaderLength,\n )\n } else {\n assertThat(listener.recordedEventTypes())\n .doesNotContain(RequestHeadersEnd::class)\n }\n if (requestBodyBytes != null) {\n val responseBodyEnd: RequestBodyEnd = listener.removeUpToEvent()\n MatcherAssert.assertThat(\n \"request body bytes\",\n responseBodyEnd.bytesWritten,\n requestBodyBytes,\n )\n } else {\n assertThat(listener.recordedEventTypes()).doesNotContain(RequestBodyEnd::class)\n }\n if (responseHeaderLength != null) {\n val responseHeadersEnd: ResponseHeadersEnd =\n listener.removeUpToEvent()\n MatcherAssert.assertThat(\n \"response header length\",\n respons"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":619,"symbol":"greaterThan","kind":"function","lang":"kotlin","code":"private fun greaterThan(value: Long): Matcher =\n object : BaseMatcher() {\n override fun describeTo(description: Description?) {\n description!!.appendText(\"> $value\")\n }\n\n override fun matches(o: Any?): Boolean = (o as Long?)!! > value\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":621,"symbol":"describeTo","kind":"function","lang":"kotlin","code":"override fun describeTo(description: Description?) {\n description!!.appendText(\"> $value\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":625,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(o: Any?): Boolean = (o as Long?)!! > value"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":628,"symbol":"matchesProtocol","kind":"function","lang":"kotlin","code":"private fun matchesProtocol(protocol: Protocol?): Matcher =\n object : BaseMatcher() {\n override fun describeTo(description: Description?) {\n description!!.appendText(\"is HTTP/2\")\n }\n\n override fun matches(o: Any?): Boolean = (o as Response?)!!.protocol == protocol\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":630,"symbol":"describeTo","kind":"function","lang":"kotlin","code":"override fun describeTo(description: Description?) {\n description!!.appendText(\"is HTTP/2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":634,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(o: Any?): Boolean = (o as Response?)!!.protocol == protocol"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":637,"symbol":"successfulEmptyH2CallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun successfulEmptyH2CallEventSequence() {\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)\n server.enqueue(MockResponse())\n assertSuccessfulEventOrder(matchesProtocol(Protocol.HTTP_2), emptyBody = true)\n assertBytesReadWritten(\n eventRecorder,\n CoreMatchers.any(Long::class.java),\n null,\n greaterThan(0L),\n CoreMatchers.equalTo(0L),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":652,"symbol":"successfulEmptyHttpsCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun successfulEmptyHttpsCallEventSequence() {\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_1_1)\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n assertSuccessfulEventOrder(anyResponse)\n assertBytesReadWritten(\n eventRecorder,\n CoreMatchers.any(Long::class.java),\n null,\n greaterThan(0L),\n CoreMatchers.equalTo(3L),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":672,"symbol":"successfulChunkedHttpsCallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun successfulChunkedHttpsCallEventSequence() {\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_1_1)\n server.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(100, TimeUnit.MILLISECONDS)\n .chunkedBody(\"Hello!\", 2)\n .build(),\n )\n assertSuccessfulEventOrder(anyResponse)\n assertBytesReadWritten(\n eventRecorder,\n CoreMatchers.any(Long::class.java),\n null,\n greaterThan(0L),\n CoreMatchers.equalTo(6L),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":693,"symbol":"successfulChunkedH2CallEventSequence","kind":"function","lang":"kotlin","code":"@Test\n fun successfulChunkedH2CallEventSequence() {\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)\n server.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(100, TimeUnit.MILLISECONDS)\n .chunkedBody(\"Hello!\", 2)\n .build(),\n )\n assertSuccessfulEventOrder(matchesProtocol(Protocol.HTTP_2))\n assertBytesReadWritten(\n eventRecorder,\n CoreMatchers.any(Long::class.java),\n null,\n CoreMatchers.equalTo(0L),\n greaterThan(6L),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":714,"symbol":"successfulDnsLookup","kind":"function","lang":"kotlin","code":"@Test\n fun successfulDnsLookup() {\n server.enqueue(MockResponse())\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val dnsStart: DnsStart = eventRecorder.removeUpToEvent()\n assertThat(dnsStart.call).isSameInstanceAs(call)\n assertThat(dnsStart.domainName).isEqualTo(server.hostName)\n val dnsEnd: DnsEnd = eventRecorder.removeUpToEvent()\n assertThat(dnsEnd.call).isSameInstanceAs(call)\n assertThat(dnsEnd.domainName).isEqualTo(server.hostName)\n assertThat(dnsEnd.inetAddressList.size).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":736,"symbol":"noDnsLookupOnPooledConnection","kind":"function","lang":"kotlin","code":"@Test\n fun noDnsLookupOnPooledConnection() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n\n // Seed the pool.\n val call1 =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response1 = call1.execute()\n assertThat(response1.code).isEqualTo(200)\n response1.body.close()\n eventRecorder.clearAllEvents()\n val call2 =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response2 = call2.execute()\n assertThat(response2.code).isEqualTo(200)\n response2.body.close()\n val recordedEvents = eventRecorder.recordedEventTypes()\n assertThat(recordedEvents).doesNotContain(DnsStart::class)\n assertThat(recordedEvents).doesNotContain(DnsEnd::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":768,"symbol":"multipleDnsLookupsForSingleCall","kind":"function","lang":"kotlin","code":"@Test\n fun multipleDnsLookupsForSingleCall() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .setHeader(\"Location\", \"http://www.fakeurl:\" + server.port)\n .build(),\n )\n server.enqueue(MockResponse())\n val dns = FakeDns()\n dns[\"fakeurl\"] = client.dns.lookup(server.hostName)\n dns[\"www.fakeurl\"] = client.dns.lookup(server.hostName)\n client =\n client\n .newBuilder()\n .dns(dns)\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(\"http://fakeurl:\" + server.port)\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":802,"symbol":"failedDnsLookup","kind":"function","lang":"kotlin","code":"@Test\n fun failedDnsLookup() {\n client =\n client\n .newBuilder()\n .dns(FakeDns())\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(\"http://fakeurl/\")\n .build(),\n )\n assertFailsWith {\n call.execute()\n }\n eventRecorder.removeUpToEvent()\n val callFailed: CallFailed = eventRecorder.removeUpToEvent()\n assertThat(callFailed.call).isSameInstanceAs(call)\n assertThat(callFailed.ioe).isInstanceOf()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":825,"symbol":"emptyDnsLookup","kind":"function","lang":"kotlin","code":"@Test\n fun emptyDnsLookup() {\n val emptyDns = Dns { listOf() }\n client =\n client\n .newBuilder()\n .dns(emptyDns)\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(\"http://fakeurl/\")\n .build(),\n )\n assertFailsWith {\n call.execute()\n }\n eventRecorder.removeUpToEvent()\n val callFailed: CallFailed = eventRecorder.removeUpToEvent()\n assertThat(callFailed.call).isSameInstanceAs(call)\n assertThat(callFailed.ioe).isInstanceOf(\n UnknownHostException::class.java,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":851,"symbol":"successfulConnect","kind":"function","lang":"kotlin","code":"@Test\n fun successfulConnect() {\n server.enqueue(MockResponse())\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val address = client.dns.lookup(server.hostName)[0]\n val expectedAddress = InetSocketAddress(address, server.port)\n val connectStart = eventRecorder.removeUpToEvent()\n assertThat(connectStart.call).isSameInstanceAs(call)\n assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress)\n assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY)\n val connectEnd = eventRecorder.removeUpToEvent()\n assertThat(connectEnd.call).isSameInstanceAs(call)\n assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress)\n assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":876,"symbol":"failedConnect","kind":"function","lang":"kotlin","code":"@Test\n fun failedConnect() {\n enableTlsWithTunnel()\n server.enqueue(\n MockResponse\n .Builder()\n .failHandshake()\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n assertFailsWith {\n call.execute()\n }\n val address = client.dns.lookup(server.hostName)[0]\n val expectedAddress = InetSocketAddress(address, server.port)\n val connectStart = eventRecorder.removeUpToEvent()\n assertThat(connectStart.call).isSameInstanceAs(call)\n assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress)\n assertThat(connectStart.proxy).isEqualTo(Proxy.NO_PROXY)\n val connectFailed = eventRecorder.removeUpToEvent()\n assertThat(connectFailed.call).isSameInstanceAs(call)\n assertThat(connectFailed.inetSocketAddress).isEqualTo(expectedAddress)\n assertThat(connectFailed.protocol).isNull()\n assertThat(connectFailed.ioe).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":908,"symbol":"multipleConnectsForSingleCall","kind":"function","lang":"kotlin","code":"@Test\n fun multipleConnectsForSingleCall() {\n enableTlsWithTunnel()\n server.enqueue(\n MockResponse\n .Builder()\n .failHandshake()\n .build(),\n )\n server.enqueue(MockResponse())\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns())\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":939,"symbol":"successfulHttpProxyConnect","kind":"function","lang":"kotlin","code":"@Test\n fun successfulHttpProxyConnect() {\n server.enqueue(MockResponse())\n client =\n client\n .newBuilder()\n .proxy(server.proxyAddress)\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(\"http://www.fakeurl\")\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val address = client.dns.lookup(server.hostName)[0]\n val expectedAddress = InetSocketAddress(address, server.port)\n val connectStart: ConnectStart =\n eventRecorder.removeUpToEvent()\n assertThat(connectStart.call).isSameInstanceAs(call)\n assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress)\n assertThat(connectStart.proxy).isEqualTo(\n server.proxyAddress,\n )\n val connectEnd = eventRecorder.removeUpToEvent()\n assertThat(connectEnd.call).isSameInstanceAs(call)\n assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress)\n assertThat(connectEnd.protocol).isEqualTo(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":972,"symbol":"successfulSocksProxyConnect","kind":"function","lang":"kotlin","code":"@Test\n fun successfulSocksProxyConnect() {\n server.enqueue(MockResponse())\n socksProxy = SocksProxy()\n socksProxy!!.play()\n val proxy = socksProxy!!.proxy()\n client =\n client\n .newBuilder()\n .proxy(proxy)\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(\"http://\" + SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS + \":\" + server.port)\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val expectedAddress =\n InetSocketAddress.createUnresolved(\n SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS,\n server.port,\n )\n val connectStart = eventRecorder.removeUpToEvent()\n assertThat(connectStart.call).isSameInstanceAs(call)\n assertThat(connectStart.inetSocketAddress).isEqualTo(expectedAddress)\n assertThat(connectStart.proxy).isEqualTo(proxy)\n val connectEnd = eventRecorder.removeUpToEvent()\n assertThat(connectEnd.call).isSameInstanceAs(call)\n assertThat(connectEnd.inetSocketAddress).isEqualTo(expectedAddress)\n assertThat(connectEnd.protocol"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1008,"symbol":"authenticatingTunnelProxyConnect","kind":"function","lang":"kotlin","code":"@Test\n fun authenticatingTunnelProxyConnect() {\n enableTlsWithTunnel()\n server.enqueue(\n MockResponse\n .Builder()\n .inTunnel()\n .code(407)\n .addHeader(\"Proxy-Authenticate: Basic realm=\\\"localhost\\\"\")\n .addHeader(\"Connection: close\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .inTunnel()\n .build(),\n )\n server.enqueue(MockResponse())\n client =\n client\n .newBuilder()\n .proxy(server.proxyAddress)\n .proxyAuthenticator(RecordingOkAuthenticator(\"password\", \"Basic\"))\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n eventRecorder.removeUpToEvent()\n val connectEnd = eventRecorder.removeUpToEvent()\n assertThat(connectEnd.protocol).isNull()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1050,"symbol":"successfulSecureConnect","kind":"function","lang":"kotlin","code":"@Test\n fun successfulSecureConnect() {\n enableTlsWithTunnel()\n server.enqueue(MockResponse())\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val secureStart = eventRecorder.removeUpToEvent()\n assertThat(secureStart.call).isSameInstanceAs(call)\n val secureEnd = eventRecorder.removeUpToEvent()\n assertThat(secureEnd.call).isSameInstanceAs(call)\n assertThat(secureEnd.handshake).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1071,"symbol":"failedSecureConnect","kind":"function","lang":"kotlin","code":"@Test\n fun failedSecureConnect() {\n enableTlsWithTunnel()\n server.enqueue(\n MockResponse\n .Builder()\n .failHandshake()\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n assertFailsWith {\n call.execute()\n }\n val secureStart = eventRecorder.removeUpToEvent()\n assertThat(secureStart.call).isSameInstanceAs(call)\n val callFailed = eventRecorder.removeUpToEvent()\n assertThat(callFailed.call).isSameInstanceAs(call)\n assertThat(callFailed.ioe).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1097,"symbol":"secureConnectWithTunnel","kind":"function","lang":"kotlin","code":"@Test\n fun secureConnectWithTunnel() {\n enableTlsWithTunnel()\n server.enqueue(\n MockResponse\n .Builder()\n .inTunnel()\n .build(),\n )\n server.enqueue(MockResponse())\n client =\n client\n .newBuilder()\n .proxy(server.proxyAddress)\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val secureStart = eventRecorder.removeUpToEvent()\n assertThat(secureStart.call).isSameInstanceAs(call)\n val secureEnd = eventRecorder.removeUpToEvent()\n assertThat(secureEnd.call).isSameInstanceAs(call)\n assertThat(secureEnd.handshake).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1129,"symbol":"multipleSecureConnectsForSingleCall","kind":"function","lang":"kotlin","code":"@Test\n fun multipleSecureConnectsForSingleCall() {\n enableTlsWithTunnel()\n server.enqueue(\n MockResponse\n .Builder()\n .failHandshake()\n .build(),\n )\n server.enqueue(MockResponse())\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns())\n .build()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1160,"symbol":"noSecureConnectsOnPooledConnection","kind":"function","lang":"kotlin","code":"@Test\n fun noSecureConnectsOnPooledConnection() {\n enableTlsWithTunnel()\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns())\n .build()\n\n // Seed the pool.\n val call1 =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response1 = call1.execute()\n assertThat(response1.code).isEqualTo(200)\n response1.body.close()\n eventRecorder.clearAllEvents()\n val call2 =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response2 = call2.execute()\n assertThat(response2.code).isEqualTo(200)\n response2.body.close()\n val recordedEvents = eventRecorder.recordedEventTypes()\n assertThat(recordedEvents).doesNotContain(SecureConnectStart::class)\n assertThat(recordedEvents).doesNotContain(SecureConnectEnd::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1198,"symbol":"successfulConnectionFound","kind":"function","lang":"kotlin","code":"@Test\n fun successfulConnectionFound() {\n server.enqueue(MockResponse())\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n response.body.close()\n val connectionAcquired = eventRecorder.removeUpToEvent()\n assertThat(connectionAcquired.call).isSameInstanceAs(call)\n assertThat(connectionAcquired.connection).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1216,"symbol":"noConnectionFoundOnFollowUp","kind":"function","lang":"kotlin","code":"@Test\n fun noConnectionFoundOnFollowUp() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .addHeader(\"Location\", \"/foo\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"ABC\")\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"ABC\")\n eventRecorder.removeUpToEvent()\n val remainingEvents = eventRecorder.recordedEventTypes()\n assertThat(remainingEvents).doesNotContain(ConnectionAcquired::class)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1245,"symbol":"pooledConnectionFound","kind":"function","lang":"kotlin","code":"@Test\n fun pooledConnectionFound() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n\n // Seed the pool.\n val call1 =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response1 = call1.execute()\n assertThat(response1.code).isEqualTo(200)\n response1.body.close()\n val connectionAcquired1 = eventRecorder.removeUpToEvent()\n eventRecorder.clearAllEvents()\n val call2 =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response2 = call2.execute()\n assertThat(response2.code).isEqualTo(200)\n response2.body.close()\n val connectionAcquired2 = eventRecorder.removeUpToEvent()\n assertThat(connectionAcquired2.connection).isSameInstanceAs(\n connectionAcquired1.connection,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1279,"symbol":"multipleConnectionsFoundForSingleCall","kind":"function","lang":"kotlin","code":"@Test\n fun multipleConnectionsFoundForSingleCall() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(301)\n .addHeader(\"Location\", \"/foo\")\n .addHeader(\"Connection\", \"Close\")\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"ABC\")\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"ABC\")\n eventRecorder.removeUpToEvent()\n eventRecorder.removeUpToEvent()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1308,"symbol":"responseBodyFailHttp1OverHttps","kind":"function","lang":"kotlin","code":"@Test\n fun responseBodyFailHttp1OverHttps() {\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_1_1)\n responseBodyFail(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1315,"symbol":"responseBodyFailHttp2OverHttps","kind":"function","lang":"kotlin","code":"@Test\n fun responseBodyFailHttp2OverHttps() {\n platform.assumeHttp2Support()\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)\n responseBodyFail(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1323,"symbol":"responseBodyFailHttp","kind":"function","lang":"kotlin","code":"@Test\n fun responseBodyFailHttp() {\n responseBodyFail(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1328,"symbol":"responseBodyFail","kind":"function","lang":"kotlin","code":"private fun responseBodyFail(expectedProtocol: Protocol?) {\n // Use a 2 MiB body so the disconnect won't happen until the client has read some data.\n val responseBodySize = 2 * 1024 * 1024 // 2 MiB\n server.enqueue(\n MockResponse\n .Builder()\n .body(Buffer().write(ByteArray(responseBodySize)))\n .onResponseBody(CloseSocket())\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n if (expectedProtocol == Protocol.HTTP_2) {\n // soft failure since client may not support depending on Platform\n assumeThat(response, matchesProtocol(Protocol.HTTP_2))\n }\n assertThat(response.protocol).isEqualTo(expectedProtocol)\n assertFailsWith {\n response.body.string()\n }\n val callFailed = eventRecorder.removeUpToEvent()\n assertThat(callFailed.ioe).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1358,"symbol":"emptyResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun emptyResponseBody() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"\")\n .bodyDelay(1, TimeUnit.SECONDS)\n .onResponseBody(CloseSocket())\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n response.body.close()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n FollowUpDecision::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1398,"symbol":"emptyResponseBodyConnectionClose","kind":"function","lang":"kotlin","code":"@Test\n fun emptyResponseBodyConnectionClose() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Connection\", \"close\")\n .body(\"\")\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n response.body.close()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n FollowUpDecision::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1437,"symbol":"responseBodyClosedClosedWithoutReadingAllData","kind":"function","lang":"kotlin","code":"@Test\n fun responseBodyClosedClosedWithoutReadingAllData() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .bodyDelay(1, TimeUnit.SECONDS)\n .onResponseBody(CloseSocket())\n .build(),\n )\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n response.body.close()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1477,"symbol":"requestBodyFailHttp1OverHttps","kind":"function","lang":"kotlin","code":"@Test\n fun requestBodyFailHttp1OverHttps() {\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_1_1)\n requestBodyFail(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1484,"symbol":"requestBodyFailHttp2OverHttps","kind":"function","lang":"kotlin","code":"@Test\n fun requestBodyFailHttp2OverHttps() {\n platform.assumeHttp2Support()\n enableTlsWithTunnel()\n server.protocols = Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)\n requestBodyFail(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1492,"symbol":"requestBodyFailHttp","kind":"function","lang":"kotlin","code":"@Test\n fun requestBodyFailHttp() {\n requestBodyFail(null)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1497,"symbol":"requestBodyFail","kind":"function","lang":"kotlin","code":"private fun requestBodyFail(expectedProtocol: Protocol?) {\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestBody(CloseSocket())\n .build(),\n )\n val request = NonCompletingRequestBody()\n val call =\n client.newCallWithListener(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(request)\n .build(),\n )\n assertFailsWith {\n call.execute()\n }\n if (expectedProtocol != null) {\n val connectionAcquired = eventRecorder.removeUpToEvent()\n assertThat(connectionAcquired.connection.protocol())\n .isEqualTo(expectedProtocol)\n }\n val callFailed = eventRecorder.removeUpToEvent()\n assertThat(callFailed.ioe).isNotNull()\n assertThat(request.ioe).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/EventListenerTest.kt","line":1526,"symbol":"NonCompletingRequestBody","kind":"class","lang":"kotlin","code":"private inner class NonCompletingRequestBody : RequestBody() {\n private val chunk: ByteArray? = ByteArray(1024 * 1024)\n var ioe: IOException? = null\n\n override fun contentType(): MediaType? = \"text/plain\".toMediaType()\n\n override fun contentLength(): Long = chunk!!.size * 8L\n\n override fun writeTo(sink: BufferedSink) {\n try {\n var i = 0\n while (i < contentLength()) {\n sink.write(chunk!!)\n sink.flush()\n Thread.sleep(100)\n i += chunk.size\n }\n } catch (e: IOException) {\n ioe = e\n } catch (e: InterruptedException) {\n throw RuntimeException(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt","line":30,"symbol":"FakeNetworkOkHttpTest","kind":"class","lang":"kotlin","code":"open class FakeNetworkOkHttpTest {\n private val platform = FakeNetworkPlatform()\n\n @RegisterExtension\n val platformRule =\n PlatformRule(\n platform = platform,\n )\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private val handshakeCertificates = platformRule.localhostHandshakeCertificates()\n\n // We can't create these until after platformRule runs. Sigh.\n private lateinit var server: MockWebServer\n private lateinit var client: OkHttpClient\n\n @BeforeEach\n fun setUp() {\n server = MockWebServer()\n client = clientTestRule.newClient()\n\n server.start()\n }\n\n @AfterEach\n fun tearDown() {\n server.close()\n }\n\n @Test\n fun `happy path`() {\n makeRequest()\n }\n\n @Test\n fun `happy path with TLS`() {\n enableTls()\n makeRequest()\n }\n\n fun makeRequest() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n\n val request =\n Request(\n url = server.url(\"/\"),\n )\n\n val call = client.newCall(request)\n\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"abc\")\n\n val recordedRequest = se"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt","line":48,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n server = MockWebServer()\n client = clientTestRule.newClient()\n\n server.start()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt","line":56,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n server.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt","line":61,"symbol":"`happy path`","kind":"function","lang":"kotlin","code":"@Test\n fun `happy path`() {\n makeRequest()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt","line":66,"symbol":"`happy path with TLS`","kind":"function","lang":"kotlin","code":"@Test\n fun `happy path with TLS`() {\n enableTls()\n makeRequest()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt","line":72,"symbol":"makeRequest","kind":"function","lang":"kotlin","code":"fun makeRequest() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n\n val request =\n Request(\n url = server.url(\"/\"),\n )\n\n val call = client.newCall(request)\n\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"abc\")\n\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"GET\")\n assertThat(recordedRequest.body).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeNetworkOkHttpTest.kt","line":96,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":26,"symbol":"FakeRoutePlanner","kind":"class","lang":"kotlin","code":"class FakeRoutePlanner(\n val factory: TestValueFactory = TestValueFactory(),\n val taskFaker: TaskFaker = factory.taskFaker,\n) : RoutePlanner,\n Closeable {\n val pool = factory.newConnectionPool()\n val events = LinkedBlockingDeque()\n var canceled = false\n var autoGeneratePlans = false\n var defaultConnectionIdleAtNanos = Long.MAX_VALUE\n private var nextPlanId = 0\n private var nextPlanIndex = 0\n val plans = mutableListOf()\n\n override val deferredPlans = ArrayDeque()\n\n override val address = factory.newAddress(\"example.com\")\n\n fun addPlan(): FakePlan =\n FakePlan(nextPlanId++).also {\n plans += it\n }\n\n override fun isCanceled() = canceled\n\n override fun plan(): FakePlan {\n // Return deferred plans preferentially. These don't require addPlan().\n if (deferredPlans.isNotEmpty()) return deferredPlans.removeFirst() as FakePlan\n\n if (nextPlanIndex >= plans.size && autoGeneratePlans) addPlan()\n\n require(nextPlanIndex < plans.size) {\n \"not enough plans! call addPlan() or set autoGeneratePlans=true in the test to set this up\"\n }\n val result = plans[nextPlanIndex++]\n events += \"take plan ${result.id}\"\n\n if "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":44,"symbol":"addPlan","kind":"function","lang":"kotlin","code":"fun addPlan(): FakePlan =\n FakePlan(nextPlanId++).also {\n plans += it\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":49,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"override fun isCanceled() = canceled"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":51,"symbol":"plan","kind":"function","lang":"kotlin","code":"override fun plan(): FakePlan {\n // Return deferred plans preferentially. These don't require addPlan().\n if (deferredPlans.isNotEmpty()) return deferredPlans.removeFirst() as FakePlan\n\n if (nextPlanIndex >= plans.size && autoGeneratePlans) addPlan()\n\n require(nextPlanIndex < plans.size) {\n \"not enough plans! call addPlan() or set autoGeneratePlans=true in the test to set this up\"\n }\n val result = plans[nextPlanIndex++]\n events += \"take plan ${result.id}\"\n\n if (result.yieldBeforePlanReturns) {\n taskFaker.yield()\n }\n\n val planningThrowable = result.planningThrowable\n if (planningThrowable != null) throw planningThrowable\n\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":73,"symbol":"hasNext","kind":"function","lang":"kotlin","code":"override fun hasNext(failedConnection: RealConnection?): Boolean =\n deferredPlans.isNotEmpty() || nextPlanIndex < plans.size || autoGeneratePlans"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":76,"symbol":"sameHostAndPort","kind":"function","lang":"kotlin","code":"override fun sameHostAndPort(url: HttpUrl): Boolean = url.host == address.url.host && url.port == address.url.port"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":78,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n factory.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":82,"symbol":"FakePlan","kind":"class","lang":"kotlin","code":"inner class FakePlan(\n val id: Int,\n ) : RoutePlanner.Plan {\n var planningThrowable: Throwable? = null\n var canceled = false\n var connectState = ConnectState.READY\n val connection =\n factory.newConnection(\n pool = pool,\n route = factory.newRoute(address),\n idleAtNanos = defaultConnectionIdleAtNanos,\n )\n var retry: FakePlan? = null\n var retryTaken = false\n var yieldBeforePlanReturns = false\n\n override val isReady: Boolean\n get() = connectState == ConnectState.TLS_CONNECTED\n\n var tcpConnectDelayNanos = 0L\n var tcpConnectThrowable: Throwable? = null\n var yieldBeforeTcpConnectReturns = false\n var connectTcpNextPlan: FakePlan? = null\n var tlsConnectDelayNanos = 0L\n var tlsConnectThrowable: Throwable? = null\n var connectTlsNextPlan: FakePlan? = null\n\n fun createRetry(): FakePlan {\n check(retry == null)\n return FakePlan(nextPlanId++)\n .also {\n retry = it\n }\n }\n\n fun createConnectTcpNextPlan(): FakePlan {\n check(connectTcpNextPlan == null)\n return FakePlan(nextPlanId++)\n .also {\n connectTcpNextPlan = it\n }\n }\n\n fun createConne"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":109,"symbol":"createRetry","kind":"function","lang":"kotlin","code":"fun createRetry(): FakePlan {\n check(retry == null)\n return FakePlan(nextPlanId++)\n .also {\n retry = it\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":117,"symbol":"createConnectTcpNextPlan","kind":"function","lang":"kotlin","code":"fun createConnectTcpNextPlan(): FakePlan {\n check(connectTcpNextPlan == null)\n return FakePlan(nextPlanId++)\n .also {\n connectTcpNextPlan = it\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":125,"symbol":"createConnectTlsNextPlan","kind":"function","lang":"kotlin","code":"fun createConnectTlsNextPlan(): FakePlan {\n check(connectTlsNextPlan == null)\n return FakePlan(nextPlanId++)\n .also {\n connectTlsNextPlan = it\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":133,"symbol":"connectTcp","kind":"function","lang":"kotlin","code":"override fun connectTcp(): ConnectResult {\n check(connectState == ConnectState.READY)\n events += \"plan $id TCP connecting...\"\n\n taskFaker.sleep(tcpConnectDelayNanos)\n\n if (yieldBeforeTcpConnectReturns) {\n taskFaker.yield()\n }\n\n return when {\n tcpConnectThrowable != null -> {\n events += \"plan $id TCP connect failed\"\n ConnectResult(this, nextPlan = connectTcpNextPlan, throwable = tcpConnectThrowable)\n }\n\n canceled -> {\n events += \"plan $id TCP connect canceled\"\n ConnectResult(this, nextPlan = connectTcpNextPlan, throwable = IOException(\"canceled\"))\n }\n\n connectTcpNextPlan != null -> {\n events += \"plan $id needs follow-up\"\n ConnectResult(this, nextPlan = connectTcpNextPlan)\n }\n\n else -> {\n events += \"plan $id TCP connected\"\n connectState = ConnectState.TCP_CONNECTED\n ConnectResult(this)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":167,"symbol":"connectTlsEtc","kind":"function","lang":"kotlin","code":"override fun connectTlsEtc(): ConnectResult {\n check(connectState == ConnectState.TCP_CONNECTED)\n events += \"plan $id TLS connecting...\"\n\n taskFaker.sleep(tlsConnectDelayNanos)\n\n return when {\n tlsConnectThrowable != null -> {\n events += \"plan $id TLS connect failed\"\n ConnectResult(this, nextPlan = connectTlsNextPlan, throwable = tlsConnectThrowable)\n }\n\n canceled -> {\n events += \"plan $id TLS connect canceled\"\n ConnectResult(this, nextPlan = connectTlsNextPlan, throwable = IOException(\"canceled\"))\n }\n\n connectTlsNextPlan != null -> {\n events += \"plan $id needs follow-up\"\n ConnectResult(this, nextPlan = connectTlsNextPlan)\n }\n\n else -> {\n events += \"plan $id TLS connected\"\n connectState = ConnectState.TLS_CONNECTED\n ConnectResult(this)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":197,"symbol":"handleSuccess","kind":"function","lang":"kotlin","code":"override fun handleSuccess() = connection"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":199,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n events += \"plan $id cancel\"\n canceled = true\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":204,"symbol":"retry","kind":"function","lang":"kotlin","code":"override fun retry(): FakePlan? {\n check(!retryTaken)\n retryTaken = true\n return retry\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":211,"symbol":"ConnectState","kind":"enum","lang":"kotlin","code":"enum class ConnectState {\n READY,\n TCP_CONNECTED,\n TLS_CONNECTED,\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":212,"symbol":"READY","kind":"enum_member","lang":"kotlin","code":"READY"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":213,"symbol":"TCP_CONNECTED","kind":"enum_member","lang":"kotlin","code":"TCP_CONNECTED"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FakeRoutePlanner.kt","line":214,"symbol":"TLS_CONNECTED","kind":"enum_member","lang":"kotlin","code":"TLS_CONNECTED"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FallbackTestClientSocketFactory.kt","line":30,"symbol":"FallbackTestClientSocketFactory","kind":"class","lang":"kotlin","doc":"An SSLSocketFactory that delegates calls. Sockets created by the delegate are wrapped with ones that will not accept the [TLS_FALLBACK_SCSV] cipher, thus bypassing server-side fallback checks on platforms that support it. Unfortunately this wrapping will disable any reflection-based calls to SSLSocket from Platform.","code":"class FallbackTestClientSocketFactory(\n delegate: SSLSocketFactory,\n) : DelegatingSSLSocketFactory(delegate) {\n override fun configureSocket(sslSocket: SSLSocket): SSLSocket = TlsFallbackScsvDisabledSSLSocket(sslSocket)\n\n private class TlsFallbackScsvDisabledSSLSocket(\n socket: SSLSocket,\n ) : DelegatingSSLSocket(socket) {\n override fun setEnabledCipherSuites(suites: Array) {\n val enabledCipherSuites = mutableListOf()\n for (suite in suites) {\n if (suite != TLS_FALLBACK_SCSV) {\n enabledCipherSuites.add(suite)\n }\n }\n delegate!!.enabledCipherSuites = enabledCipherSuites.toTypedArray()\n }\n }\n\n companion object {\n /**\n * The cipher suite used during TLS connection fallback to indicate a fallback. See\n * https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00\n */\n const val TLS_FALLBACK_SCSV = \"TLS_FALLBACK_SCSV\"\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FallbackTestClientSocketFactory.kt","line":33,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"override fun configureSocket(sslSocket: SSLSocket): SSLSocket = TlsFallbackScsvDisabledSSLSocket(sslSocket)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FallbackTestClientSocketFactory.kt","line":35,"symbol":"TlsFallbackScsvDisabledSSLSocket","kind":"class","lang":"kotlin","code":"private class TlsFallbackScsvDisabledSSLSocket(\n socket: SSLSocket,\n ) : DelegatingSSLSocket(socket) {\n override fun setEnabledCipherSuites(suites: Array) {\n val enabledCipherSuites = mutableListOf()\n for (suite in suites) {\n if (suite != TLS_FALLBACK_SCSV) {\n enabledCipherSuites.add(suite)\n }\n }\n delegate!!.enabledCipherSuites = enabledCipherSuites.toTypedArray()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FallbackTestClientSocketFactory.kt","line":38,"symbol":"setEnabledCipherSuites","kind":"function","lang":"kotlin","code":"override fun setEnabledCipherSuites(suites: Array) {\n val enabledCipherSuites = mutableListOf()\n for (suite in suites) {\n if (suite != TLS_FALLBACK_SCSV) {\n enabledCipherSuites.add(suite)\n }\n }\n delegate!!.enabledCipherSuites = enabledCipherSuites.toTypedArray()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":58,"symbol":"FastFallbackTest","kind":"class","lang":"kotlin","doc":"By orchestrating two different servers with the same port but different IP addresses, we can test what OkHttp does when both are reachable, or if only one is reachable. This test only runs on host machines that have both IPv4 and IPv6 addresses for localhost.","code":"@Timeout(30)\nclass FastFallbackTest {\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n // Don't use JUnit 5 test rules for these; otherwise we can't bind them to a single local IP.\n private lateinit var localhostIpv4: InetAddress\n private lateinit var localhostIpv6: InetAddress\n private lateinit var serverIpv4: MockWebServer\n private lateinit var serverIpv6: MockWebServer\n\n private val eventRecorder = EventRecorder()\n private lateinit var client: OkHttpClient\n private lateinit var url: HttpUrl\n\n /**\n * This is mutable and order matters. By default, it contains [IPv4, IPv6]. Tests may manipulate\n * it to prefer IPv6.\n */\n private var dnsResults = listOf()\n\n @BeforeEach\n internal fun setUp() {\n val inetAddresses = InetAddress.getAllByName(\"localhost\")\n localhostIpv4 = inetAddresses.firstOrNull { it is Inet4Address }\n ?: throw TestAbortedException()\n localhostIpv6 = inetAddresses.firstOrNull { it is Inet6Address }\n ?: throw TestAbortedException()\n\n serverIpv4 = MockWebServer()\n serverIpv4.start(localhostIpv4, 0) // Pick any available port.\n\n serverIpv6 = MockWebServer()\n serverIpv6.start(localhostIpv6, s"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":79,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n internal fun setUp() {\n val inetAddresses = InetAddress.getAllByName(\"localhost\")\n localhostIpv4 = inetAddresses.firstOrNull { it is Inet4Address }\n ?: throw TestAbortedException()\n localhostIpv6 = inetAddresses.firstOrNull { it is Inet6Address }\n ?: throw TestAbortedException()\n\n serverIpv4 = MockWebServer()\n serverIpv4.start(localhostIpv4, 0) // Pick any available port.\n\n serverIpv6 = MockWebServer()\n serverIpv6.start(localhostIpv6, serverIpv4.port) // Pick the same port as the IPv4 server.\n\n dnsResults =\n listOf(\n localhostIpv4,\n localhostIpv6,\n )\n\n client =\n clientTestRule\n .newClientBuilder()\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .connectTimeout(60, TimeUnit.SECONDS) // Deliberately exacerbate slow fallbacks.\n .dns { dnsResults }\n .fastFallback(true)\n .build()\n url =\n serverIpv4\n .url(\"/\")\n .newBuilder()\n .host(\"localhost\")\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":115,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n internal fun tearDown() {\n serverIpv4.close()\n serverIpv6.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":121,"symbol":"callIpv6FirstEvenWhenIpv4IpIsListedFirst","kind":"function","lang":"kotlin","code":"@Test\n fun callIpv6FirstEvenWhenIpv4IpIsListedFirst() {\n dnsResults =\n listOf(\n localhostIpv4,\n localhostIpv6,\n )\n serverIpv4.enqueue(\n MockResponse(body = \"unexpected call to IPv4\"),\n )\n serverIpv6.enqueue(\n MockResponse(body = \"hello from IPv6\"),\n )\n\n val call = client.newCall(Request(url))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"hello from IPv6\")\n\n // In the process we made one successful connection attempt.\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectStart::class }).hasSize(1)\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectFailed::class }).hasSize(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":144,"symbol":"callIpv6WhenBothServersAreReachable","kind":"function","lang":"kotlin","code":"@Test\n fun callIpv6WhenBothServersAreReachable() {\n // Flip DNS results to prefer IPv6.\n dnsResults =\n listOf(\n localhostIpv6,\n localhostIpv4,\n )\n serverIpv4.enqueue(\n MockResponse(body = \"unexpected call to IPv4\"),\n )\n serverIpv6.enqueue(\n MockResponse(body = \"hello from IPv6\"),\n )\n\n val call = client.newCall(Request(url))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"hello from IPv6\")\n\n // In the process we made one successful connection attempt.\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectStart::class }).hasSize(1)\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectFailed::class }).hasSize(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":168,"symbol":"reachesIpv4WhenIpv6IsDown","kind":"function","lang":"kotlin","code":"@Test\n fun reachesIpv4WhenIpv6IsDown() {\n serverIpv6.close()\n serverIpv4.enqueue(\n MockResponse(body = \"hello from IPv4\"),\n )\n\n val call = client.newCall(Request(url))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"hello from IPv4\")\n\n // In the process we made one successful connection attempt.\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectStart::class }).hasSize(2)\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectFailed::class }).hasSize(1)\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectEnd::class }).hasSize(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":185,"symbol":"reachesIpv6WhenIpv4IsDown","kind":"function","lang":"kotlin","code":"@Test\n fun reachesIpv6WhenIpv4IsDown() {\n serverIpv4.close()\n serverIpv6.enqueue(\n MockResponse(body = \"hello from IPv6\"),\n )\n\n val call = client.newCall(Request(url))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"hello from IPv6\")\n\n // In the process we made two connection attempts including one failure.\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectStart::class }).hasSize(1)\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectEnd::class }).hasSize(1)\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectFailed::class }).hasSize(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":202,"symbol":"failsWhenBothServersAreDown","kind":"function","lang":"kotlin","code":"@Test\n fun failsWhenBothServersAreDown() {\n serverIpv4.close()\n serverIpv6.close()\n\n val call = client.newCall(Request(url))\n assertFailsWith {\n call.execute()\n }\n\n // In the process we made two unsuccessful connection attempts.\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectStart::class }).hasSize(2)\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectFailed::class }).hasSize(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":217,"symbol":"reachesIpv4AfterUnreachableIpv6Address","kind":"function","lang":"kotlin","code":"@RetryingTest(5)\n @Flaky\n fun reachesIpv4AfterUnreachableIpv6Address() {\n dnsResults =\n listOf(\n TestUtil.UNREACHABLE_ADDRESS_IPV6.address,\n localhostIpv4,\n )\n serverIpv6.close()\n serverIpv4.enqueue(\n MockResponse(body = \"hello from IPv4\"),\n )\n\n val call = client.newCall(Request(url))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"hello from IPv4\")\n\n // In the process we made two connection attempts including one failure.\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectStart::class }).hasSize(2)\n assertThat(eventRecorder.recordedEventTypes().filter { it == ConnectFailed::class }).hasSize(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":239,"symbol":"timesOutWithFastFallbackDisabled","kind":"function","lang":"kotlin","code":"@Test\n fun timesOutWithFastFallbackDisabled() {\n dnsResults =\n listOf(\n TestUtil.UNREACHABLE_ADDRESS_IPV4.address,\n localhostIpv6,\n )\n serverIpv4.close()\n serverIpv6.enqueue(\n MockResponse(body = \"hello from IPv6\"),\n )\n\n client =\n client\n .newBuilder()\n .fastFallback(false)\n .callTimeout(1_000, TimeUnit.MILLISECONDS)\n .build()\n val call = client.newCall(Request(url))\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected).hasMessage(\"timeout\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":272,"symbol":"preferCallConnectionOverDeferredConnection","kind":"function","lang":"kotlin","doc":"This test reproduces a crash where OkHttp attempted to use a deferred connection when the call already had a healthy connection. It sets up a deferred connection by stalling the IPv6 connect, and it sets up a same-connection retry with [ErrorCode.REFUSED_STREAM]. https://github.com/lysine-dev/okhttp/pull/7190","code":"@Test\n fun preferCallConnectionOverDeferredConnection() {\n // Make sure we have enough connection options to permit retries.\n dnsResults =\n listOf(\n localhostIpv4,\n localhostIpv6,\n TestUtil.UNREACHABLE_ADDRESS_IPV4.address,\n )\n serverIpv4.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE)\n serverIpv6.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE)\n\n // Yield the first IP address so the second IP address completes first.\n val firstConnectLatch = CountDownLatch(1)\n val socketFactory =\n object : DelegatingSocketFactory(Platform.get().socketFactory) {\n var first = true\n\n override fun createSocket(): Socket {\n if (first) {\n first = false\n firstConnectLatch.await()\n }\n return super.createSocket()\n }\n }\n\n client =\n client\n .newBuilder()\n .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE))\n .socketFactory(socketFactory)\n .addNetworkInterceptor(\n Interceptor { chain ->\n try {\n chain.proceed(chain.request())\n } finally {\n firstConnectLatch.countDown()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FastFallbackTest.kt","line":290,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(): Socket {\n if (first) {\n first = false\n firstConnectLatch.await()\n }\n return super.createSocket()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":25,"symbol":"FormBodyTest","kind":"class","lang":"kotlin","code":"class FormBodyTest {\n @Test\n fun urlEncoding() {\n val body =\n FormBody\n .Builder()\n .add(\"a+=& b\", \"c+=& d\")\n .add(\"space, the\", \"final frontier\")\n .add(\"%25\", \"%25\")\n .build()\n assertThat(body.size).isEqualTo(3)\n assertThat(body.encodedName(0)).isEqualTo(\"a%2B%3D%26+b\")\n assertThat(body.encodedName(1)).isEqualTo(\"space%2C+the\")\n assertThat(body.encodedName(2)).isEqualTo(\"%2525\")\n assertThat(body.name(0)).isEqualTo(\"a+=& b\")\n assertThat(body.name(1)).isEqualTo(\"space, the\")\n assertThat(body.name(2)).isEqualTo(\"%25\")\n assertThat(body.encodedValue(0)).isEqualTo(\"c%2B%3D%26+d\")\n assertThat(body.encodedValue(1)).isEqualTo(\"final+frontier\")\n assertThat(body.encodedValue(2)).isEqualTo(\"%2525\")\n assertThat(body.value(0)).isEqualTo(\"c+=& d\")\n assertThat(body.value(1)).isEqualTo(\"final frontier\")\n assertThat(body.value(2)).isEqualTo(\"%25\")\n assertThat(body.contentType().toString()).isEqualTo(\n \"application/x-www-form-urlencoded\",\n )\n val expected = \"a%2B%3D%26+b=c%2B%3D%26+d&space%2C+the=final+frontier&%2525=%2525\"\n assertThat(body.contentLength()).isEqualTo(expected.length.toLong())\n val"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":26,"symbol":"urlEncoding","kind":"function","lang":"kotlin","code":"@Test\n fun urlEncoding() {\n val body =\n FormBody\n .Builder()\n .add(\"a+=& b\", \"c+=& d\")\n .add(\"space, the\", \"final frontier\")\n .add(\"%25\", \"%25\")\n .build()\n assertThat(body.size).isEqualTo(3)\n assertThat(body.encodedName(0)).isEqualTo(\"a%2B%3D%26+b\")\n assertThat(body.encodedName(1)).isEqualTo(\"space%2C+the\")\n assertThat(body.encodedName(2)).isEqualTo(\"%2525\")\n assertThat(body.name(0)).isEqualTo(\"a+=& b\")\n assertThat(body.name(1)).isEqualTo(\"space, the\")\n assertThat(body.name(2)).isEqualTo(\"%25\")\n assertThat(body.encodedValue(0)).isEqualTo(\"c%2B%3D%26+d\")\n assertThat(body.encodedValue(1)).isEqualTo(\"final+frontier\")\n assertThat(body.encodedValue(2)).isEqualTo(\"%2525\")\n assertThat(body.value(0)).isEqualTo(\"c+=& d\")\n assertThat(body.value(1)).isEqualTo(\"final frontier\")\n assertThat(body.value(2)).isEqualTo(\"%25\")\n assertThat(body.contentType().toString()).isEqualTo(\n \"application/x-www-form-urlencoded\",\n )\n val expected = \"a%2B%3D%26+b=c%2B%3D%26+d&space%2C+the=final+frontier&%2525=%2525\"\n assertThat(body.contentLength()).isEqualTo(expected.length.toLong())\n val out = Buffer()\n bod"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":58,"symbol":"addEncoded","kind":"function","lang":"kotlin","code":"@Test\n fun addEncoded() {\n val body =\n FormBody\n .Builder()\n .addEncoded(\"a+=& b\", \"c+=& d\")\n .addEncoded(\"e+=& f\", \"g+=& h\")\n .addEncoded(\"%25\", \"%25\")\n .build()\n val expected = \"a+%3D%26+b=c+%3D%26+d&e+%3D%26+f=g+%3D%26+h&%25=%25\"\n val out = Buffer()\n body.writeTo(out)\n assertThat(out.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":73,"symbol":"encodedPair","kind":"function","lang":"kotlin","code":"@Test\n fun encodedPair() {\n val body =\n FormBody\n .Builder()\n .add(\"sim\", \"ple\")\n .build()\n val expected = \"sim=ple\"\n assertThat(body.contentLength()).isEqualTo(expected.length.toLong())\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":87,"symbol":"encodeMultiplePairs","kind":"function","lang":"kotlin","code":"@Test\n fun encodeMultiplePairs() {\n val body =\n FormBody\n .Builder()\n .add(\"sim\", \"ple\")\n .add(\"hey\", \"there\")\n .add(\"help\", \"me\")\n .build()\n val expected = \"sim=ple&hey=there&help=me\"\n assertThat(body.contentLength()).isEqualTo(expected.length.toLong())\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":103,"symbol":"buildEmptyForm","kind":"function","lang":"kotlin","code":"@Test\n fun buildEmptyForm() {\n val body = FormBody.Builder().build()\n val expected = \"\"\n assertThat(body.contentLength()).isEqualTo(expected.length.toLong())\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":113,"symbol":"characterEncoding","kind":"function","lang":"kotlin","code":"@Test\n fun characterEncoding() {\n // Browsers convert '\\u0000' to '%EF%BF%BD'.\n assertThat(formEncode(0)).isEqualTo(\"%00\")\n assertThat(formEncode(1)).isEqualTo(\"%01\")\n assertThat(formEncode(2)).isEqualTo(\"%02\")\n assertThat(formEncode(3)).isEqualTo(\"%03\")\n assertThat(formEncode(4)).isEqualTo(\"%04\")\n assertThat(formEncode(5)).isEqualTo(\"%05\")\n assertThat(formEncode(6)).isEqualTo(\"%06\")\n assertThat(formEncode(7)).isEqualTo(\"%07\")\n assertThat(formEncode(8)).isEqualTo(\"%08\")\n assertThat(formEncode(9)).isEqualTo(\"%09\")\n // Browsers convert '\\n' to '\\r\\n'\n assertThat(formEncode(10)).isEqualTo(\"%0A\")\n assertThat(formEncode(11)).isEqualTo(\"%0B\")\n assertThat(formEncode(12)).isEqualTo(\"%0C\")\n // Browsers convert '\\r' to '\\r\\n'\n assertThat(formEncode(13)).isEqualTo(\"%0D\")\n assertThat(formEncode(14)).isEqualTo(\"%0E\")\n assertThat(formEncode(15)).isEqualTo(\"%0F\")\n assertThat(formEncode(16)).isEqualTo(\"%10\")\n assertThat(formEncode(17)).isEqualTo(\"%11\")\n assertThat(formEncode(18)).isEqualTo(\"%12\")\n assertThat(formEncode(19)).isEqualTo(\"%13\")\n assertThat(formEncode(20)).isEqualTo(\"%14\")\n assertThat(formEncode(21)).isEqualTo("} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":195,"symbol":"formEncode","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun formEncode(codePoint: Int): String {\n // Wrap the codepoint with regular printable characters to prevent trimming.\n val body =\n FormBody\n .Builder()\n .add(\"a\", String(intArrayOf('b'.code, codePoint, 'c'.code), 0, 3))\n .build()\n val buffer = Buffer()\n body.writeTo(buffer)\n buffer.skip(3) // Skip \"a=b\" prefix.\n return buffer.readUtf8(buffer.size - 1) // Skip the \"c\" suffix.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/FormBodyTest.kt","line":209,"symbol":"manualCharset","kind":"function","lang":"kotlin","code":"@Test\n fun manualCharset() {\n val body =\n FormBody\n .Builder(StandardCharsets.ISO_8859_1)\n .add(\"name\", \"Nicolás\")\n .build()\n val expected = \"name=Nicol%E1s\"\n assertThat(body.contentLength()).isEqualTo(expected.length.toLong())\n val out = Buffer()\n body.writeTo(out)\n assertThat(out.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":32,"symbol":"HandshakeTest","kind":"class","lang":"kotlin","code":"class HandshakeTest {\n val serverRoot =\n HeldCertificate\n .Builder()\n .certificateAuthority(1)\n .build()\n val serverIntermediate =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .signedBy(serverRoot)\n .build()\n val serverCertificate =\n HeldCertificate\n .Builder()\n .signedBy(serverIntermediate)\n .build()\n\n @Test\n fun createFromParts() {\n val handshake =\n Handshake.get(\n tlsVersion = TlsVersion.TLS_1_3,\n cipherSuite = CipherSuite.TLS_AES_128_GCM_SHA256,\n peerCertificates = listOf(serverCertificate.certificate, serverIntermediate.certificate),\n localCertificates = listOf(),\n )\n\n assertThat(handshake.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n assertThat(handshake.cipherSuite).isEqualTo(CipherSuite.TLS_AES_128_GCM_SHA256)\n assertThat(handshake.peerCertificates).containsExactly(\n serverCertificate.certificate,\n serverIntermediate.certificate,\n )\n assertThat(handshake.localPrincipal).isNull()\n assertThat(handshake.peerPrincipal)\n .isEqualTo(serverCertificate.certificate.subjectX500Principal)\n assertThat(handshake.localCertificates).isEmpty()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":50,"symbol":"createFromParts","kind":"function","lang":"kotlin","code":"@Test\n fun createFromParts() {\n val handshake =\n Handshake.get(\n tlsVersion = TlsVersion.TLS_1_3,\n cipherSuite = CipherSuite.TLS_AES_128_GCM_SHA256,\n peerCertificates = listOf(serverCertificate.certificate, serverIntermediate.certificate),\n localCertificates = listOf(),\n )\n\n assertThat(handshake.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n assertThat(handshake.cipherSuite).isEqualTo(CipherSuite.TLS_AES_128_GCM_SHA256)\n assertThat(handshake.peerCertificates).containsExactly(\n serverCertificate.certificate,\n serverIntermediate.certificate,\n )\n assertThat(handshake.localPrincipal).isNull()\n assertThat(handshake.peerPrincipal)\n .isEqualTo(serverCertificate.certificate.subjectX500Principal)\n assertThat(handshake.localCertificates).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":72,"symbol":"createFromSslSession","kind":"function","lang":"kotlin","code":"@Test\n fun createFromSslSession() {\n val sslSession =\n FakeSSLSession(\n \"TLSv1.3\",\n \"TLS_AES_128_GCM_SHA256\",\n arrayOf(serverCertificate.certificate, serverIntermediate.certificate),\n null,\n )\n\n val handshake = sslSession.handshake()\n\n assertThat(handshake.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n assertThat(handshake.cipherSuite).isEqualTo(CipherSuite.TLS_AES_128_GCM_SHA256)\n assertThat(handshake.peerCertificates).containsExactly(\n serverCertificate.certificate,\n serverIntermediate.certificate,\n )\n assertThat(handshake.localPrincipal).isNull()\n assertThat(handshake.peerPrincipal)\n .isEqualTo(serverCertificate.certificate.subjectX500Principal)\n assertThat(handshake.localCertificates).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":96,"symbol":"sslWithNullNullNull","kind":"function","lang":"kotlin","code":"@Test\n fun sslWithNullNullNull() {\n val sslSession =\n FakeSSLSession(\n \"TLSv1.3\",\n \"SSL_NULL_WITH_NULL_NULL\",\n arrayOf(serverCertificate.certificate, serverIntermediate.certificate),\n null,\n )\n\n assertFailsWith {\n sslSession.handshake()\n }.also { expected ->\n assertThat(expected).hasMessage(\"cipherSuite == SSL_NULL_WITH_NULL_NULL\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":113,"symbol":"tlsWithNullNullNull","kind":"function","lang":"kotlin","code":"@Test\n fun tlsWithNullNullNull() {\n val sslSession =\n FakeSSLSession(\n \"TLSv1.3\",\n \"TLS_NULL_WITH_NULL_NULL\",\n arrayOf(serverCertificate.certificate, serverIntermediate.certificate),\n null,\n )\n\n assertFailsWith {\n sslSession.handshake()\n }.also { expected ->\n assertThat(expected).hasMessage(\"cipherSuite == TLS_NULL_WITH_NULL_NULL\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":130,"symbol":"FakeSSLSession","kind":"class","lang":"kotlin","code":"class FakeSSLSession(\n private val protocol: String,\n private val cipherSuite: String,\n private val peerCertificates: Array?,\n private val localCertificates: Array?,\n ) : DelegatingSSLSession(null) {\n override fun getProtocol() = protocol\n\n override fun getCipherSuite() = cipherSuite\n\n override fun getPeerCertificates() = peerCertificates\n\n override fun getLocalCertificates() = localCertificates\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":136,"symbol":"getProtocol","kind":"function","lang":"kotlin","code":"override fun getProtocol() = protocol"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":138,"symbol":"getCipherSuite","kind":"function","lang":"kotlin","code":"override fun getCipherSuite() = cipherSuite"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":140,"symbol":"getPeerCertificates","kind":"function","lang":"kotlin","code":"override fun getPeerCertificates() = peerCertificates"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HandshakeTest.kt","line":142,"symbol":"getLocalCertificates","kind":"function","lang":"kotlin","code":"override fun getLocalCertificates() = localCertificates"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":26,"symbol":"HeadersChallengesTest","kind":"class","lang":"kotlin","code":"class HeadersChallengesTest {\n /** See https://github.com/lysine-dev/okhttp/issues/2780. */\n @Test fun testDigestChallengeWithStrictRfc2617Header() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"Digest realm=\\\"myrealm\\\", nonce=\\\"fjalskdflwejrlaskdfjlaskdjflaks\" +\n \"jdflkasdf\\\", qop=\\\"auth\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }\n\n @Test fun testDigestChallengeWithDifferentlyOrderedAuthParams() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"Digest qop=\\\"auth\\\", realm=\\\"myrealm\\\", nonce=\\\"fjalskdflwej"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":28,"symbol":"testDigestChallengeWithStrictRfc2617Header","kind":"function","lang":"kotlin","doc":"See https://github.com/lysine-dev/okhttp/issues/2780.","code":"@Test fun testDigestChallengeWithStrictRfc2617Header() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"Digest realm=\\\"myrealm\\\", nonce=\\\"fjalskdflwejrlaskdfjlaskdjflaks\" +\n \"jdflkasdf\\\", qop=\\\"auth\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":49,"symbol":"testDigestChallengeWithDifferentlyOrderedAuthParams","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithDifferentlyOrderedAuthParams() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"Digest qop=\\\"auth\\\", realm=\\\"myrealm\\\", nonce=\\\"fjalskdflwejrlask\" +\n \"dfjlaskdjflaksjdflkasdf\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":70,"symbol":"testDigestChallengeWithDifferentlyOrderedAuthParams2","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithDifferentlyOrderedAuthParams2() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"Digest qop=\\\"auth\\\", nonce=\\\"fjalskdflwejrlaskdfjlaskdjflaksjdflk\" +\n \"asdf\\\", realm=\\\"myrealm\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":91,"symbol":"testDigestChallengeWithMissingRealm","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithMissingRealm() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"Digest qop=\\\"auth\\\", underrealm=\\\"myrealm\\\", nonce=\\\"fjalskdflwej\" +\n \"rlaskdfjlaskdjflaksjdflkasdf\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isNull()\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"underrealm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":112,"symbol":"testDigestChallengeWithAdditionalSpaces","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithAdditionalSpaces() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"Digest qop=\\\"auth\\\", realm=\\\"myrealm\\\", nonce=\\\"fjalskdflwejrl\" +\n \"askdfjlaskdjflaksjdflkasdf\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":133,"symbol":"testDigestChallengeWithAdditionalSpacesBeforeFirstAuthParam","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithAdditionalSpacesBeforeFirstAuthParam() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"Digest realm=\\\"myrealm\\\", nonce=\\\"fjalskdflwejrlaskdfjlaskdjfl\" +\n \"aksjdflkasdf\\\", qop=\\\"auth\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":154,"symbol":"testDigestChallengeWithCamelCasedNames","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithCamelCasedNames() {\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"DiGeSt qop=\\\"auth\\\", rEaLm=\\\"myrealm\\\", nonce=\\\"fjalskdflwejrlask\" +\n \"dfjlaskdjflaksjdflkasdf\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"DiGeSt\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":175,"symbol":"testDigestChallengeWithCamelCasedNames2","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithCamelCasedNames2() {\n // Strict RFC 2617 camelcased.\n val headers =\n Headers\n .Builder()\n .add(\n \"WWW-Authenticate\",\n \"DIgEsT rEaLm=\\\"myrealm\\\", nonce=\\\"fjalskdflwejrlaskdfjlaskdjflaks\" +\n \"jdflkasdf\\\", qop=\\\"auth\\\", stale=\\\"FALSE\\\"\",\n ).build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"DIgEsT\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"nonce\"] = \"fjalskdflwejrlaskdfjlaskdjflaksjdflkasdf\"\n expectedAuthParams[\"qop\"] = \"auth\"\n expectedAuthParams[\"stale\"] = \"FALSE\"\n assertThat(challenges[0].authParams).isEqualTo(expectedAuthParams)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":197,"symbol":"testDigestChallengeWithTokenFormOfAuthParam","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithTokenFormOfAuthParam() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest realm=myrealm\")\n .build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isEqualTo(\"myrealm\")\n assertThat(challenges[0].authParams)\n .isEqualTo(mapOf(\"realm\" to \"myrealm\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":211,"symbol":"testDigestChallengeWithoutAuthParams","kind":"function","lang":"kotlin","code":"@Test fun testDigestChallengeWithoutAuthParams() {\n // Scheme only.\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest\")\n .build()\n val challenges = headers.parseChallenges(\"WWW-Authenticate\")\n assertThat(challenges.size).isEqualTo(1)\n assertThat(challenges[0].scheme).isEqualTo(\"Digest\")\n assertThat(challenges[0].realm).isNull()\n assertThat(challenges[0].authParams).isEqualTo(emptyMap())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":225,"symbol":"basicChallenge","kind":"function","lang":"kotlin","code":"@Test fun basicChallenge() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate: Basic realm=\\\"protected area\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\"))\n .isEqualTo(listOf(Challenge(\"Basic\", mapOf(\"realm\" to \"protected area\"))))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":235,"symbol":"basicChallengeWithCharset","kind":"function","lang":"kotlin","code":"@Test fun basicChallengeWithCharset() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate: Basic realm=\\\"protected area\\\", charset=\\\"UTF-8\\\"\")\n .build()\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"protected area\"\n expectedAuthParams[\"charset\"] = \"UTF-8\"\n assertThat(headers.parseChallenges(\"WWW-Authenticate\"))\n .isEqualTo(listOf(Challenge(\"Basic\", expectedAuthParams)))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":248,"symbol":"basicChallengeWithUnexpectedCharset","kind":"function","lang":"kotlin","code":"@Test fun basicChallengeWithUnexpectedCharset() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate: Basic realm=\\\"protected area\\\", charset=\\\"US-ASCII\\\"\")\n .build()\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"protected area\"\n expectedAuthParams[\"charset\"] = \"US-ASCII\"\n assertThat(headers.parseChallenges(\"WWW-Authenticate\"))\n .isEqualTo(listOf(Challenge(\"Basic\", expectedAuthParams)))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":261,"symbol":"separatorsBeforeFirstChallenge","kind":"function","lang":"kotlin","code":"@Test fun separatorsBeforeFirstChallenge() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \" , , Basic realm=myrealm\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\"))\n .isEqualTo(listOf(Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\"))))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":271,"symbol":"spacesAroundKeyValueSeparator","kind":"function","lang":"kotlin","code":"@Test fun spacesAroundKeyValueSeparator() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Basic realm = \\\"myrealm\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\"))\n .isEqualTo(listOf(Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\"))))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":281,"symbol":"multipleChallengesInOneHeader","kind":"function","lang":"kotlin","code":"@Test fun multipleChallengesInOneHeader() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Basic realm = \\\"myrealm\\\",Digest\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\")),\n Challenge(\"Digest\", mapOf()),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":293,"symbol":"multipleChallengesWithSameSchemeButDifferentRealmInOneHeader","kind":"function","lang":"kotlin","code":"@Test fun multipleChallengesWithSameSchemeButDifferentRealmInOneHeader() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Basic realm = \\\"myrealm\\\",Basic realm=myotherrealm\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\")),\n Challenge(\"Basic\", mapOf(\"realm\" to \"myotherrealm\")),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":305,"symbol":"separatorsBeforeFirstAuthParam","kind":"function","lang":"kotlin","code":"@Test fun separatorsBeforeFirstAuthParam() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest, Basic ,,realm=\\\"myrealm\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\")),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":317,"symbol":"onlyCommaBetweenChallenges","kind":"function","lang":"kotlin","code":"@Test fun onlyCommaBetweenChallenges() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest,Basic realm=\\\"myrealm\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\")),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":329,"symbol":"multipleSeparatorsBetweenChallenges","kind":"function","lang":"kotlin","code":"@Test fun multipleSeparatorsBetweenChallenges() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest,,,, Basic ,,realm=\\\"myrealm\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\")),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":341,"symbol":"unknownAuthParams","kind":"function","lang":"kotlin","code":"@Test fun unknownAuthParams() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest,,,, Basic ,,foo=bar,realm=\\\"myrealm\\\"\")\n .build()\n val expectedAuthParams = mutableMapOf()\n expectedAuthParams[\"realm\"] = \"myrealm\"\n expectedAuthParams[\"foo\"] = \"bar\"\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n Challenge(\"Basic\", expectedAuthParams),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":356,"symbol":"escapedCharactersInQuotedString","kind":"function","lang":"kotlin","code":"@Test fun escapedCharactersInQuotedString() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest,,,, Basic ,,,realm=\\\"my\\\\\\\\\\\\\\\"r\\\\ealm\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n Challenge(\"Basic\", mapOf(\"realm\" to \"my\\\\\\\"realm\")),\n )\n }\n\n @Test fun commaInQuotedStringAndBeforeFirstChallenge() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \",Digest,,,, Basic ,,,realm=\\\"my, realm,\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n Challenge(\"Basic\", mapOf(\"realm\" to \"my, realm,\")),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":380,"symbol":"unescapedDoubleQuoteInQuotedStringWithEvenNumberOfBackslashesInFront","kind":"function","lang":"kotlin","code":"@Test fun unescapedDoubleQuoteInQuotedStringWithEvenNumberOfBackslashesInFront() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest,,,, Basic ,,,realm=\\\"my\\\\\\\\\\\\\\\\\\\"r\\\\ealm\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":391,"symbol":"unescapedDoubleQuoteInQuotedString","kind":"function","lang":"kotlin","code":"@Test fun unescapedDoubleQuoteInQuotedString() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest,,,, Basic ,,,realm=\\\"my\\\"realm\\\"\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":402,"symbol":"doubleQuoteInToken","kind":"function","lang":"kotlin","code":"@Disabled(\"TODO(jwilson): reject parameters that use invalid characters\")\n @Test\n fun doubleQuoteInToken() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest,,,, Basic ,,,realm=my\\\"realm\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":415,"symbol":"token68InsteadOfAuthParams","kind":"function","lang":"kotlin","code":"@Test fun token68InsteadOfAuthParams() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Other abc==\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\"))\n .isEqualTo(\n listOf(Challenge(\"Other\", mapOf(null to \"abc==\"))),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":427,"symbol":"token68AndAuthParams","kind":"function","lang":"kotlin","code":"@Test fun token68AndAuthParams() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Other abc==, realm=myrealm\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Other\", mapOf(null to \"abc==\")),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":438,"symbol":"repeatedAuthParamKey","kind":"function","lang":"kotlin","code":"@Test fun repeatedAuthParamKey() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Other realm=myotherrealm, realm=myrealm\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).isEqualTo(listOf())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":447,"symbol":"multipleAuthenticateHeaders","kind":"function","lang":"kotlin","code":"@Test fun multipleAuthenticateHeaders() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Digest\")\n .add(\"WWW-Authenticate\", \"Basic realm=myrealm\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Digest\", mapOf()),\n Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\")),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":460,"symbol":"multipleAuthenticateHeadersInDifferentOrder","kind":"function","lang":"kotlin","code":"@Test fun multipleAuthenticateHeadersInDifferentOrder() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Basic realm=myrealm\")\n .add(\"WWW-Authenticate\", \"Digest\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\")),\n Challenge(\"Digest\", mapOf()),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersChallengesTest.kt","line":473,"symbol":"multipleBasicAuthenticateHeaders","kind":"function","lang":"kotlin","code":"@Test fun multipleBasicAuthenticateHeaders() {\n val headers =\n Headers\n .Builder()\n .add(\"WWW-Authenticate\", \"Basic realm=myrealm\")\n .add(\"WWW-Authenticate\", \"Basic realm=myotherrealm\")\n .build()\n assertThat(headers.parseChallenges(\"WWW-Authenticate\")).containsExactly(\n Challenge(\"Basic\", mapOf(\"realm\" to \"myrealm\")),\n Challenge(\"Basic\", mapOf(\"realm\" to \"myotherrealm\")),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":27,"symbol":"HeadersJvmTest","kind":"class","lang":"kotlin","code":"class HeadersJvmTest {\n @Test fun byteCount() {\n assertThat(Headers.EMPTY.byteCount()).isEqualTo(0L)\n assertThat(\n Headers\n .Builder()\n .add(\"abc\", \"def\")\n .build()\n .byteCount(),\n ).isEqualTo(10L)\n assertThat(\n Headers\n .Builder()\n .add(\"abc\", \"def\")\n .add(\"ghi\", \"jkl\")\n .build()\n .byteCount(),\n ).isEqualTo(20L)\n }\n\n @Test fun addDate() {\n val expected = Date(0L)\n val headers =\n Headers\n .Builder()\n .add(\"testDate\", expected)\n .build()\n assertThat(headers[\"testDate\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n assertThat(headers.getDate(\"testDate\")).isEqualTo(Date(0L))\n }\n\n @Test fun addInstant() {\n val expected = Instant.ofEpochMilli(0L)\n val headers =\n Headers\n .Builder()\n .add(\"Test-Instant\", expected)\n .build()\n assertThat(headers[\"Test-Instant\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n assertThat(headers.getInstant(\"Test-Instant\")).isEqualTo(expected)\n }\n\n @Test fun setDate() {\n val expected = Date(1000)\n val headers =\n Headers\n .Builder()\n .add(\"testDate\", Date(0L))\n .se"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":28,"symbol":"byteCount","kind":"function","lang":"kotlin","code":"@Test fun byteCount() {\n assertThat(Headers.EMPTY.byteCount()).isEqualTo(0L)\n assertThat(\n Headers\n .Builder()\n .add(\"abc\", \"def\")\n .build()\n .byteCount(),\n ).isEqualTo(10L)\n assertThat(\n Headers\n .Builder()\n .add(\"abc\", \"def\")\n .add(\"ghi\", \"jkl\")\n .build()\n .byteCount(),\n ).isEqualTo(20L)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":47,"symbol":"addDate","kind":"function","lang":"kotlin","code":"@Test fun addDate() {\n val expected = Date(0L)\n val headers =\n Headers\n .Builder()\n .add(\"testDate\", expected)\n .build()\n assertThat(headers[\"testDate\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n assertThat(headers.getDate(\"testDate\")).isEqualTo(Date(0L))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":58,"symbol":"addInstant","kind":"function","lang":"kotlin","code":"@Test fun addInstant() {\n val expected = Instant.ofEpochMilli(0L)\n val headers =\n Headers\n .Builder()\n .add(\"Test-Instant\", expected)\n .build()\n assertThat(headers[\"Test-Instant\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n assertThat(headers.getInstant(\"Test-Instant\")).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":69,"symbol":"setDate","kind":"function","lang":"kotlin","code":"@Test fun setDate() {\n val expected = Date(1000)\n val headers =\n Headers\n .Builder()\n .add(\"testDate\", Date(0L))\n .set(\"testDate\", expected)\n .build()\n assertThat(headers[\"testDate\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:01 GMT\")\n assertThat(headers.getDate(\"testDate\")).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":81,"symbol":"setInstant","kind":"function","lang":"kotlin","code":"@Test fun setInstant() {\n val expected = Instant.ofEpochMilli(1000L)\n val headers =\n Headers\n .Builder()\n .add(\"Test-Instant\", Instant.ofEpochMilli(0L))\n .set(\"Test-Instant\", expected)\n .build()\n assertThat(headers[\"Test-Instant\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:01 GMT\")\n assertThat(headers.getInstant(\"Test-Instant\")).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":93,"symbol":"addParsing","kind":"function","lang":"kotlin","code":"@Test fun addParsing() {\n val headers =\n Headers\n .Builder()\n .add(\"foo: bar\")\n .add(\" foo: baz\") // Name leading whitespace is trimmed.\n .add(\"foo : bak\") // Name trailing whitespace is trimmed.\n .add(\"\\tkey\\t:\\tvalue\\t\") // '\\t' also counts as whitespace\n .add(\"ping: pong \") // Value whitespace is trimmed.\n .add(\"kit:kat\") // Space after colon is not required.\n .build()\n assertThat(headers.values(\"foo\")).containsExactly(\"bar\", \"baz\", \"bak\")\n assertThat(headers.values(\"key\")).containsExactly(\"value\")\n assertThat(headers.values(\"ping\")).containsExactly(\"pong\")\n assertThat(headers.values(\"kit\")).containsExactly(\"kat\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":110,"symbol":"addThrowsOnEmptyName","kind":"function","lang":"kotlin","code":"@Test fun addThrowsOnEmptyName() {\n assertFailsWith {\n Headers.Builder().add(\": bar\")\n }\n assertFailsWith {\n Headers.Builder().add(\" : bar\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":119,"symbol":"addThrowsOnNoColon","kind":"function","lang":"kotlin","code":"@Test fun addThrowsOnNoColon() {\n assertFailsWith {\n Headers.Builder().add(\"foo bar\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":125,"symbol":"addThrowsOnMultiColon","kind":"function","lang":"kotlin","code":"@Test fun addThrowsOnMultiColon() {\n assertFailsWith {\n Headers.Builder().add(\":status: 200 OK\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":131,"symbol":"addUnsafeNonAsciiRejectsUnicodeName","kind":"function","lang":"kotlin","code":"@Test fun addUnsafeNonAsciiRejectsUnicodeName() {\n assertFailsWith {\n Headers\n .Builder()\n .addUnsafeNonAscii(\"héader1\", \"value1\")\n .build()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Unexpected char 0xe9 at 1 in header name: héader1\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":142,"symbol":"addUnsafeNonAsciiAcceptsUnicodeValue","kind":"function","lang":"kotlin","code":"@Test fun addUnsafeNonAsciiAcceptsUnicodeValue() {\n val headers =\n Headers\n .Builder()\n .addUnsafeNonAscii(\"header1\", \"valué1\")\n .build()\n assertThat(headers.toString()).isEqualTo(\"header1: valué1\\n\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":152,"symbol":"ofMapThrowsOnNull","kind":"function","lang":"kotlin","doc":"Fails on JS, ClassCastException: Illegal cast","code":"@Test fun ofMapThrowsOnNull() {\n assertFailsWith {\n (mapOf(\"User-Agent\" to null) as Map).toHeaders()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":158,"symbol":"toMultimapGroupsHeaders","kind":"function","lang":"kotlin","code":"@Test fun toMultimapGroupsHeaders() {\n val headers =\n Headers.headersOf(\n \"cache-control\",\n \"no-cache\",\n \"cache-control\",\n \"no-store\",\n \"user-agent\",\n \"OkHttp\",\n )\n val headerMap = headers.toMultimap()\n assertThat(headerMap[\"cache-control\"]!!.size).isEqualTo(2)\n assertThat(headerMap[\"user-agent\"]!!.size).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":173,"symbol":"toMultimapUsesCanonicalCase","kind":"function","lang":"kotlin","code":"@Test fun toMultimapUsesCanonicalCase() {\n val headers =\n Headers.headersOf(\n \"cache-control\",\n \"no-store\",\n \"Cache-Control\",\n \"no-cache\",\n \"User-Agent\",\n \"OkHttp\",\n )\n val headerMap = headers.toMultimap()\n assertThat(headerMap[\"cache-control\"]!!.size).isEqualTo(2)\n assertThat(headerMap[\"user-agent\"]!!.size).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersJvmTest.kt","line":188,"symbol":"toMultimapAllowsCaseInsensitiveGet","kind":"function","lang":"kotlin","code":"@Test fun toMultimapAllowsCaseInsensitiveGet() {\n val headers =\n Headers.headersOf(\n \"cache-control\",\n \"no-store\",\n \"Cache-Control\",\n \"no-cache\",\n )\n val headerMap = headers.toMultimap()\n assertThat(headerMap[\"cache-control\"]!!.size).isEqualTo(2)\n assertThat(headerMap[\"Cache-Control\"]!!.size).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersKotlinTest.kt","line":27,"symbol":"HeadersKotlinTest","kind":"class","lang":"kotlin","code":"class HeadersKotlinTest {\n @Test fun getOperator() {\n val headers = headersOf(\"a\", \"b\", \"c\", \"d\")\n assertThat(headers[\"a\"]).isEqualTo(\"b\")\n assertThat(headers[\"c\"]).isEqualTo(\"d\")\n assertThat(headers[\"e\"]).isNull()\n }\n\n @Test fun iteratorOperator() {\n val headers = headersOf(\"a\", \"b\", \"c\", \"d\")\n\n val pairs = mutableListOf>()\n for ((name, value) in headers) {\n pairs += name to value\n }\n\n assertThat(pairs).containsExactly(\"a\" to \"b\", \"c\" to \"d\")\n }\n\n @Test fun builderGetOperator() {\n val builder = Headers.Builder()\n builder.add(\"a\", \"b\")\n builder.add(\"c\", \"d\")\n assertThat(builder[\"a\"]).isEqualTo(\"b\")\n assertThat(builder[\"c\"]).isEqualTo(\"d\")\n assertThat(builder[\"e\"]).isNull()\n }\n\n @Test fun builderSetOperator() {\n val builder = Headers.Builder()\n builder[\"a\"] = \"b\"\n builder[\"c\"] = \"d\"\n builder[\"e\"] = Date(0L)\n builder[\"g\"] = Instant.EPOCH\n assertThat(builder[\"a\"]).isEqualTo(\"b\")\n assertThat(builder[\"c\"]).isEqualTo(\"d\")\n assertThat(builder[\"e\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n assertThat(builder[\"g\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersKotlinTest.kt","line":28,"symbol":"getOperator","kind":"function","lang":"kotlin","code":"@Test fun getOperator() {\n val headers = headersOf(\"a\", \"b\", \"c\", \"d\")\n assertThat(headers[\"a\"]).isEqualTo(\"b\")\n assertThat(headers[\"c\"]).isEqualTo(\"d\")\n assertThat(headers[\"e\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersKotlinTest.kt","line":35,"symbol":"iteratorOperator","kind":"function","lang":"kotlin","code":"@Test fun iteratorOperator() {\n val headers = headersOf(\"a\", \"b\", \"c\", \"d\")\n\n val pairs = mutableListOf>()\n for ((name, value) in headers) {\n pairs += name to value\n }\n\n assertThat(pairs).containsExactly(\"a\" to \"b\", \"c\" to \"d\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersKotlinTest.kt","line":46,"symbol":"builderGetOperator","kind":"function","lang":"kotlin","code":"@Test fun builderGetOperator() {\n val builder = Headers.Builder()\n builder.add(\"a\", \"b\")\n builder.add(\"c\", \"d\")\n assertThat(builder[\"a\"]).isEqualTo(\"b\")\n assertThat(builder[\"c\"]).isEqualTo(\"d\")\n assertThat(builder[\"e\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersKotlinTest.kt","line":55,"symbol":"builderSetOperator","kind":"function","lang":"kotlin","code":"@Test fun builderSetOperator() {\n val builder = Headers.Builder()\n builder[\"a\"] = \"b\"\n builder[\"c\"] = \"d\"\n builder[\"e\"] = Date(0L)\n builder[\"g\"] = Instant.EPOCH\n assertThat(builder[\"a\"]).isEqualTo(\"b\")\n assertThat(builder[\"c\"]).isEqualTo(\"d\")\n assertThat(builder[\"e\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n assertThat(builder[\"g\"]).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersRequestTest.kt","line":26,"symbol":"HeadersRequestTest","kind":"class","lang":"kotlin","code":"class HeadersRequestTest {\n @Test fun readNameValueBlockDropsForbiddenHeadersHttp2() {\n val headerBlock =\n headersOf(\n \":status\",\n \"200 OK\",\n \":version\",\n \"HTTP/1.1\",\n \"connection\",\n \"close\",\n )\n val request = Request.Builder().url(\"http://square.com/\").build()\n val response = readHttp2HeadersList(headerBlock, Protocol.HTTP_2).request(request).build()\n val headers = response.headers\n assertThat(headers.size).isEqualTo(1)\n assertThat(headers.name(0)).isEqualTo(\":version\")\n assertThat(headers.value(0)).isEqualTo(\"HTTP/1.1\")\n }\n\n @Test fun http2HeadersListDropsForbiddenHeadersHttp2() {\n val request =\n Request\n .Builder()\n .url(\"http://square.com/\")\n .header(\"Connection\", \"upgrade\")\n .header(\"Upgrade\", \"websocket\")\n .header(\"Host\", \"square.com\")\n .header(\"TE\", \"gzip\")\n .build()\n val expected =\n headerEntries(\n \":method\",\n \"GET\",\n \":path\",\n \"/\",\n \":authority\",\n \"square.com\",\n \":scheme\",\n \"http\",\n )\n assertThat(http2HeadersList(request)).isEqualTo(expected)\n }\n\n @Test fun http2Headers"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersRequestTest.kt","line":27,"symbol":"readNameValueBlockDropsForbiddenHeadersHttp2","kind":"function","lang":"kotlin","code":"@Test fun readNameValueBlockDropsForbiddenHeadersHttp2() {\n val headerBlock =\n headersOf(\n \":status\",\n \"200 OK\",\n \":version\",\n \"HTTP/1.1\",\n \"connection\",\n \"close\",\n )\n val request = Request.Builder().url(\"http://square.com/\").build()\n val response = readHttp2HeadersList(headerBlock, Protocol.HTTP_2).request(request).build()\n val headers = response.headers\n assertThat(headers.size).isEqualTo(1)\n assertThat(headers.name(0)).isEqualTo(\":version\")\n assertThat(headers.value(0)).isEqualTo(\"HTTP/1.1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersRequestTest.kt","line":45,"symbol":"http2HeadersListDropsForbiddenHeadersHttp2","kind":"function","lang":"kotlin","code":"@Test fun http2HeadersListDropsForbiddenHeadersHttp2() {\n val request =\n Request\n .Builder()\n .url(\"http://square.com/\")\n .header(\"Connection\", \"upgrade\")\n .header(\"Upgrade\", \"websocket\")\n .header(\"Host\", \"square.com\")\n .header(\"TE\", \"gzip\")\n .build()\n val expected =\n headerEntries(\n \":method\",\n \"GET\",\n \":path\",\n \"/\",\n \":authority\",\n \"square.com\",\n \":scheme\",\n \"http\",\n )\n assertThat(http2HeadersList(request)).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersRequestTest.kt","line":69,"symbol":"http2HeadersListDontDropTeIfTrailersHttp2","kind":"function","lang":"kotlin","code":"@Test fun http2HeadersListDontDropTeIfTrailersHttp2() {\n val request =\n Request\n .Builder()\n .url(\"http://square.com/\")\n .header(\"TE\", \"trailers\")\n .build()\n val expected =\n headerEntries(\n \":method\",\n \"GET\",\n \":path\",\n \"/\",\n \":scheme\",\n \"http\",\n \"te\",\n \"trailers\",\n )\n assertThat(http2HeadersList(request)).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":26,"symbol":"HeadersTest","kind":"class","lang":"kotlin","code":"class HeadersTest {\n @Test fun ofTrims() {\n val headers = headersOf(\"\\t User-Agent \\n\", \" \\r OkHttp \")\n assertThat(headers.name(0)).isEqualTo(\"User-Agent\")\n assertThat(headers.value(0)).isEqualTo(\"OkHttp\")\n }\n\n @Test fun ofThrowsOddNumberOfHeaders() {\n assertFailsWith {\n headersOf(\"User-Agent\", \"OkHttp\", \"Content-Length\")\n }\n }\n\n @Test fun ofThrowsOnEmptyName() {\n assertFailsWith {\n headersOf(\"\", \"OkHttp\")\n }\n }\n\n @Test fun ofAcceptsEmptyValue() {\n val headers = headersOf(\"User-Agent\", \"\")\n assertThat(headers.value(0)).isEqualTo(\"\")\n }\n\n @Test fun ofMakesDefensiveCopy() {\n val namesAndValues =\n arrayOf(\n \"User-Agent\",\n \"OkHttp\",\n )\n val headers = headersOf(*namesAndValues)\n namesAndValues[1] = \"Chrome\"\n assertThat(headers.value(0)).isEqualTo(\"OkHttp\")\n }\n\n @Test fun ofRejectsNullChar() {\n assertFailsWith {\n headersOf(\"User-Agent\", \"Square\\u0000OkHttp\")\n }\n }\n\n @Test fun ofMapThrowsOnEmptyName() {\n assertFailsWith {\n mapOf(\"\" to \"OkHttp\").toHeaders()\n }\n }\n\n @Test fun ofMa"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":27,"symbol":"ofTrims","kind":"function","lang":"kotlin","code":"@Test fun ofTrims() {\n val headers = headersOf(\"\\t User-Agent \\n\", \" \\r OkHttp \")\n assertThat(headers.name(0)).isEqualTo(\"User-Agent\")\n assertThat(headers.value(0)).isEqualTo(\"OkHttp\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":33,"symbol":"ofThrowsOddNumberOfHeaders","kind":"function","lang":"kotlin","code":"@Test fun ofThrowsOddNumberOfHeaders() {\n assertFailsWith {\n headersOf(\"User-Agent\", \"OkHttp\", \"Content-Length\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":39,"symbol":"ofThrowsOnEmptyName","kind":"function","lang":"kotlin","code":"@Test fun ofThrowsOnEmptyName() {\n assertFailsWith {\n headersOf(\"\", \"OkHttp\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":45,"symbol":"ofAcceptsEmptyValue","kind":"function","lang":"kotlin","code":"@Test fun ofAcceptsEmptyValue() {\n val headers = headersOf(\"User-Agent\", \"\")\n assertThat(headers.value(0)).isEqualTo(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":50,"symbol":"ofMakesDefensiveCopy","kind":"function","lang":"kotlin","code":"@Test fun ofMakesDefensiveCopy() {\n val namesAndValues =\n arrayOf(\n \"User-Agent\",\n \"OkHttp\",\n )\n val headers = headersOf(*namesAndValues)\n namesAndValues[1] = \"Chrome\"\n assertThat(headers.value(0)).isEqualTo(\"OkHttp\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":61,"symbol":"ofRejectsNullChar","kind":"function","lang":"kotlin","code":"@Test fun ofRejectsNullChar() {\n assertFailsWith {\n headersOf(\"User-Agent\", \"Square\\u0000OkHttp\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":67,"symbol":"ofMapThrowsOnEmptyName","kind":"function","lang":"kotlin","code":"@Test fun ofMapThrowsOnEmptyName() {\n assertFailsWith {\n mapOf(\"\" to \"OkHttp\").toHeaders()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":73,"symbol":"ofMapThrowsOnBlankName","kind":"function","lang":"kotlin","code":"@Test fun ofMapThrowsOnBlankName() {\n assertFailsWith {\n mapOf(\" \" to \"OkHttp\").toHeaders()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":79,"symbol":"ofMapAcceptsEmptyValue","kind":"function","lang":"kotlin","code":"@Test fun ofMapAcceptsEmptyValue() {\n val headers = mapOf(\"User-Agent\" to \"\").toHeaders()\n assertThat(headers.value(0)).isEqualTo(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":84,"symbol":"ofMapTrimsKey","kind":"function","lang":"kotlin","code":"@Test fun ofMapTrimsKey() {\n val headers = mapOf(\" User-Agent \" to \"OkHttp\").toHeaders()\n assertThat(headers.name(0)).isEqualTo(\"User-Agent\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":89,"symbol":"ofMapTrimsValue","kind":"function","lang":"kotlin","code":"@Test fun ofMapTrimsValue() {\n val headers = mapOf(\"User-Agent\" to \" OkHttp \").toHeaders()\n assertThat(headers.value(0)).isEqualTo(\"OkHttp\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":94,"symbol":"ofMapMakesDefensiveCopy","kind":"function","lang":"kotlin","code":"@Test fun ofMapMakesDefensiveCopy() {\n val namesAndValues = mutableMapOf()\n namesAndValues[\"User-Agent\"] = \"OkHttp\"\n val headers = namesAndValues.toHeaders()\n namesAndValues[\"User-Agent\"] = \"Chrome\"\n assertThat(headers.value(0)).isEqualTo(\"OkHttp\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":102,"symbol":"ofMapRejectsNullCharInName","kind":"function","lang":"kotlin","code":"@Test fun ofMapRejectsNullCharInName() {\n assertFailsWith {\n mapOf(\"User-\\u0000Agent\" to \"OkHttp\").toHeaders()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":108,"symbol":"ofMapRejectsNullCharInValue","kind":"function","lang":"kotlin","code":"@Test fun ofMapRejectsNullCharInValue() {\n assertFailsWith {\n mapOf(\"User-Agent\" to \"Square\\u0000OkHttp\").toHeaders()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":114,"symbol":"builderRejectsUnicodeInHeaderName","kind":"function","lang":"kotlin","code":"@Test fun builderRejectsUnicodeInHeaderName() {\n assertFailsWith {\n Headers.Builder().add(\"héader1\", \"value1\")\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 1 in header name: héader1\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":123,"symbol":"builderRejectsUnicodeInHeaderValue","kind":"function","lang":"kotlin","code":"@Test fun builderRejectsUnicodeInHeaderValue() {\n assertFailsWith {\n Headers.Builder().add(\"header1\", \"valué1\")\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 4 in header1 value: valué1\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":132,"symbol":"varargFactoryRejectsUnicodeInHeaderName","kind":"function","lang":"kotlin","code":"@Test fun varargFactoryRejectsUnicodeInHeaderName() {\n assertFailsWith {\n headersOf(\"héader1\", \"value1\")\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 1 in header name: héader1\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":141,"symbol":"varargFactoryRejectsUnicodeInHeaderValue","kind":"function","lang":"kotlin","code":"@Test fun varargFactoryRejectsUnicodeInHeaderValue() {\n assertFailsWith {\n headersOf(\"header1\", \"valué1\")\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 4 in header1 value: valué1\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":150,"symbol":"mapFactoryRejectsUnicodeInHeaderName","kind":"function","lang":"kotlin","code":"@Test fun mapFactoryRejectsUnicodeInHeaderName() {\n assertFailsWith {\n mapOf(\"héader1\" to \"value1\").toHeaders()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 1 in header name: héader1\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":159,"symbol":"mapFactoryRejectsUnicodeInHeaderValue","kind":"function","lang":"kotlin","code":"@Test fun mapFactoryRejectsUnicodeInHeaderValue() {\n assertFailsWith {\n mapOf(\"header1\" to \"valué1\").toHeaders()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 4 in header1 value: valué1\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":168,"symbol":"sensitiveHeadersNotIncludedInExceptions","kind":"function","lang":"kotlin","code":"@Test fun sensitiveHeadersNotIncludedInExceptions() {\n assertFailsWith {\n Headers.Builder().add(\"Authorization\", \"valué1\")\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 4 in Authorization value\")\n }\n assertFailsWith {\n Headers.Builder().add(\"Cookie\", \"valué1\")\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 4 in Cookie value\")\n }\n assertFailsWith {\n Headers.Builder().add(\"Proxy-Authorization\", \"valué1\")\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 4 in Proxy-Authorization value\")\n }\n assertFailsWith {\n Headers.Builder().add(\"Set-Cookie\", \"valué1\")\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Unexpected char 0xe9 at 4 in Set-Cookie value\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":195,"symbol":"headersEquals","kind":"function","lang":"kotlin","code":"@Test fun headersEquals() {\n val headers1 =\n Headers\n .Builder()\n .add(\"Connection\", \"close\")\n .add(\"Transfer-Encoding\", \"chunked\")\n .build()\n val headers2 =\n Headers\n .Builder()\n .add(\"Connection\", \"close\")\n .add(\"Transfer-Encoding\", \"chunked\")\n .build()\n assertThat(headers2).isEqualTo(headers1)\n assertThat(headers2.hashCode()).isEqualTo(headers1.hashCode())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":212,"symbol":"headersNotEquals","kind":"function","lang":"kotlin","code":"@Test fun headersNotEquals() {\n val headers1 =\n Headers\n .Builder()\n .add(\"Connection\", \"close\")\n .add(\"Transfer-Encoding\", \"chunked\")\n .build()\n val headers2 =\n Headers\n .Builder()\n .add(\"Connection\", \"keep-alive\")\n .add(\"Transfer-Encoding\", \"chunked\")\n .build()\n assertThat(headers2).isNotEqualTo(headers1)\n assertThat(headers2.hashCode()).isNotEqualTo(headers1.hashCode().toLong())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":229,"symbol":"headersToString","kind":"function","lang":"kotlin","code":"@Test fun headersToString() {\n val headers =\n Headers\n .Builder()\n .add(\"A\", \"a\")\n .add(\"B\", \"bb\")\n .build()\n assertThat(headers.toString()).isEqualTo(\"A: a\\nB: bb\\n\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":239,"symbol":"headersToStringRedactsSensitiveHeaders","kind":"function","lang":"kotlin","code":"@Test fun headersToStringRedactsSensitiveHeaders() {\n val headers =\n Headers\n .Builder()\n .add(\"content-length\", \"99\")\n .add(\"authorization\", \"peanutbutter\")\n .add(\"proxy-authorization\", \"chocolate\")\n .add(\"cookie\", \"drink=coffee\")\n .add(\"set-cookie\", \"accessory=sugar\")\n .add(\"user-agent\", \"OkHttp\")\n .build()\n assertThat(headers.toString()).isEqualTo(\n \"\"\"\n |content-length: 99\n |authorization: ██\n |proxy-authorization: ██\n |cookie: ██\n |set-cookie: ██\n |user-agent: OkHttp\n |\n \"\"\".trimMargin(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":263,"symbol":"headersAddAll","kind":"function","lang":"kotlin","code":"@Test fun headersAddAll() {\n val sourceHeaders =\n Headers\n .Builder()\n .add(\"A\", \"aa\")\n .add(\"a\", \"aa\")\n .add(\"B\", \"bb\")\n .build()\n val headers =\n Headers\n .Builder()\n .add(\"A\", \"a\")\n .addAll(sourceHeaders)\n .add(\"C\", \"c\")\n .build()\n assertThat(headers.toString()).isEqualTo(\"A: a\\nA: aa\\na: aa\\nB: bb\\nC: c\\n\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":281,"symbol":"nameIndexesAreStrict","kind":"function","lang":"kotlin","code":"@Test fun nameIndexesAreStrict() {\n val headers = headersOf(\"a\", \"b\", \"c\", \"d\")\n assertFailsWith {\n headers.name(-1)\n }\n assertThat(headers.name(0)).isEqualTo(\"a\")\n assertThat(headers.name(1)).isEqualTo(\"c\")\n assertFailsWith {\n headers.name(2)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HeadersTest.kt","line":293,"symbol":"valueIndexesAreStrict","kind":"function","lang":"kotlin","code":"@Test fun valueIndexesAreStrict() {\n val headers = headersOf(\"a\", \"b\", \"c\", \"d\")\n assertFailsWith {\n headers.value(-1)\n }\n assertThat(headers.value(0)).isEqualTo(\"b\")\n assertThat(headers.value(1)).isEqualTo(\"d\")\n assertFailsWith {\n headers.value(2)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":33,"symbol":"hostContainsOnlyStrippedCharacters","kind":"function","lang":"kotlin","doc":"This one's ugly: the HttpUrl's host is non-empty, but the URI's host is null.","code":"@Test\n fun hostContainsOnlyStrippedCharacters() {\n val url = \"http://>/\".toHttpUrl()\n assertThat(url.host).isEqualTo(\">\")\n assertThat(url.toUri().host).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":44,"symbol":"hostToUriStripsCharacters","kind":"function","lang":"kotlin","doc":"Strip unexpected characters when converting to URI (which is more strict). https://github.com/lysine-dev/okhttp/issues/5667","code":"@Test\n fun hostToUriStripsCharacters() {\n val httpUrl = \"http://example\\\".com/\".toHttpUrl()\n assertThat(httpUrl.toUri().toString()).isEqualTo(\"http://example.com/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":51,"symbol":"hostToUriStripsCharacters2","kind":"function","lang":"kotlin","doc":"Confirm that URI retains other characters. https://github.com/lysine-dev/okhttp/issues/5236","code":"@Test\n fun hostToUriStripsCharacters2() {\n val httpUrl = \"http://\\${tracker}/\".toHttpUrl()\n assertThat(httpUrl.toUri().toString()).isEqualTo(\"http://\\$tracker/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":57,"symbol":"fragmentNonAsciiThatOffendsJavaNetUri","kind":"function","lang":"kotlin","code":"@Test\n fun fragmentNonAsciiThatOffendsJavaNetUri() {\n val url = \"http://host/#\\u0080\".toHttpUrl()\n assertThat(url.toString()).isEqualTo(\"http://host/#\\u0080\")\n assertThat(url.fragment).isEqualTo(\"\\u0080\")\n assertThat(url.encodedFragment).isEqualTo(\"\\u0080\")\n // Control characters may be stripped!\n assertThat(url.toUri()).isEqualTo(URI(\"http://host/#\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":67,"symbol":"toUriWithControlCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun toUriWithControlCharacters() {\n // Percent-encoded in the path.\n assertThat(\"http://host/a\\u0000b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/a%00b\"))\n assertThat(\"http://host/a\\u0080b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/a%C2%80b\"))\n assertThat(\"http://host/a\\u009fb\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/a%C2%9Fb\"))\n // Percent-encoded in the query.\n assertThat(\"http://host/?a\\u0000b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/?a%00b\"))\n assertThat(\"http://host/?a\\u0080b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/?a%C2%80b\"))\n assertThat(\"http://host/?a\\u009fb\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/?a%C2%9Fb\"))\n // Stripped from the fragment.\n assertThat(\"http://host/#a\\u0000b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/#a%00b\"))\n assertThat(\"http://host/#a\\u0080b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/#ab\"))\n assertThat(\"http://host/#a\\u009fb\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/#ab\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":92,"symbol":"toUriWithSpaceCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun toUriWithSpaceCharacters() {\n // Percent-encoded in the path.\n assertThat(\"http://host/a\\u000bb\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/a%0Bb\"))\n assertThat(\"http://host/a b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/a%20b\"))\n assertThat(\"http://host/a\\u2009b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/a%E2%80%89b\"))\n assertThat(\"http://host/a\\u3000b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/a%E3%80%80b\"))\n // Percent-encoded in the query.\n assertThat(\"http://host/?a\\u000bb\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/?a%0Bb\"))\n assertThat(\"http://host/?a b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/?a%20b\"))\n assertThat(\"http://host/?a\\u2009b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/?a%E2%80%89b\"))\n assertThat(\"http://host/?a\\u3000b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/?a%E3%80%80b\"))\n // Stripped from the fragment.\n assertThat(\"http://host/#a\\u000bb\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/#a%0Bb\"))\n assertThat(\"http://host/#a b\".toHttpUrl().toUri())\n .isEqualTo(URI(\"http://host/#a%20b\"))\n assert"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":123,"symbol":"toUriWithNonHexPercentEscape","kind":"function","lang":"kotlin","code":"@Test\n fun toUriWithNonHexPercentEscape() {\n assertThat(\"http://host/%xx\".toHttpUrl().toUri()).isEqualTo(URI(\"http://host/%25xx\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":128,"symbol":"toUriWithTruncatedPercentEscape","kind":"function","lang":"kotlin","code":"@Test\n fun toUriWithTruncatedPercentEscape() {\n assertThat(\"http://host/%a\".toHttpUrl().toUri()).isEqualTo(URI(\"http://host/%25a\"))\n assertThat(\"http://host/%\".toHttpUrl().toUri()).isEqualTo(URI(\"http://host/%25\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":134,"symbol":"fromJavaNetUrl","kind":"function","lang":"kotlin","code":"@Test\n fun fromJavaNetUrl() {\n val javaNetUrl = URL(\"http://username:password@host/path?query#fragment\")\n val httpUrl = javaNetUrl.toHttpUrlOrNull()\n assertThat(httpUrl.toString())\n .isEqualTo(\"http://username:password@host/path?query#fragment\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":142,"symbol":"fromJavaNetUrlUnsupportedScheme","kind":"function","lang":"kotlin","code":"@Test\n fun fromJavaNetUrlUnsupportedScheme() {\n // java.net.MalformedURLException: unknown protocol: mailto\n platform.assumeNotAndroid()\n\n // Accessing an URL protocol that was not enabled. The URL protocol mailto is not tested and\n // might not work as expected. It can be enabled by adding the --enable-url-protocols=mailto\n // option to the native-image command.\n platform.assumeNotGraalVMImage()\n val javaNetUrl = URL(\"mailto:user@example.com\")\n assertThat(javaNetUrl.toHttpUrlOrNull()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":155,"symbol":"fromUri","kind":"function","lang":"kotlin","code":"@Test\n fun fromUri() {\n val uri = URI(\"http://username:password@host/path?query#fragment\")\n val httpUrl = uri.toHttpUrlOrNull()\n assertThat(httpUrl.toString())\n .isEqualTo(\"http://username:password@host/path?query#fragment\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":163,"symbol":"fromUriUnsupportedScheme","kind":"function","lang":"kotlin","code":"@Test\n fun fromUriUnsupportedScheme() {\n val uri = URI(\"mailto:user@example.com\")\n assertThat(uri.toHttpUrlOrNull()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":169,"symbol":"fromUriPartial","kind":"function","lang":"kotlin","code":"@Test\n fun fromUriPartial() {\n val uri = URI(\"/path\")\n assertThat(uri.toHttpUrlOrNull()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":175,"symbol":"toJavaNetUrl","kind":"function","lang":"kotlin","code":"@Test\n fun toJavaNetUrl() {\n val httpUrl = \"http://username:password@host/path?query#fragment\".toHttpUrl()\n val javaNetUrl = httpUrl.toUrl()\n assertThat(javaNetUrl.toString())\n .isEqualTo(\"http://username:password@host/path?query#fragment\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":183,"symbol":"toUri","kind":"function","lang":"kotlin","code":"@Test\n fun toUri() {\n val httpUrl = \"http://username:password@host/path?query#fragment\".toHttpUrl()\n val uri = httpUrl.toUri()\n assertThat(uri.toString())\n .isEqualTo(\"http://username:password@host/path?query#fragment\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":191,"symbol":"toUriFragmentSpecialCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun toUriFragmentSpecialCharacters() {\n val url =\n HttpUrl\n .Builder()\n .scheme(\"http\")\n .host(\"host\")\n .fragment(\"=[]:;\\\"~|?#@^/$%*\")\n .build()\n assertThat(url.toString()).isEqualTo(\"http://host/#=[]:;\\\"~|?#@^/$%25*\")\n assertThat(url.toUri().toString())\n .isEqualTo(\"http://host/#=[]:;%22~%7C?%23@%5E/$%25*\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":205,"symbol":"toUriSpecialQueryCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun toUriSpecialQueryCharacters() {\n val httpUrl = \"http://host/?d=abc!@[]^`{}|\\\\\".toHttpUrl()\n val uri = httpUrl.toUri()\n assertThat(uri.toString()).isEqualTo(\"http://host/?d=abc!@[]%5E%60%7B%7D%7C%5C\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":212,"symbol":"toUriWithUsernameNoPassword","kind":"function","lang":"kotlin","code":"@Test\n fun toUriWithUsernameNoPassword() {\n val httpUrl =\n HttpUrl\n .Builder()\n .scheme(\"http\")\n .username(\"user\")\n .host(\"host\")\n .build()\n assertThat(httpUrl.toString()).isEqualTo(\"http://user@host/\")\n assertThat(httpUrl.toUri().toString()).isEqualTo(\"http://user@host/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":225,"symbol":"toUriUsernameSpecialCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun toUriUsernameSpecialCharacters() {\n val url =\n HttpUrl\n .Builder()\n .scheme(\"http\")\n .host(\"host\")\n .username(\"=[]:;\\\"~|?#@^/$%*\")\n .build()\n assertThat(url.toString())\n .isEqualTo(\"http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/\")\n assertThat(url.toUri().toString())\n .isEqualTo(\"http://%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":240,"symbol":"toUriPasswordSpecialCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun toUriPasswordSpecialCharacters() {\n val url =\n HttpUrl\n .Builder()\n .scheme(\"http\")\n .host(\"host\")\n .username(\"user\")\n .password(\"=[]:;\\\"~|?#@^/$%*\")\n .build()\n assertThat(url.toString())\n .isEqualTo(\"http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/\")\n assertThat(url.toUri().toString())\n .isEqualTo(\"http://user:%3D%5B%5D%3A%3B%22~%7C%3F%23%40%5E%2F$%25*@host/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlJvmTest.kt","line":256,"symbol":"toUriPathSpecialCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun toUriPathSpecialCharacters() {\n val url =\n HttpUrl\n .Builder()\n .scheme(\"http\")\n .host(\"host\")\n .addPathSegment(\"=[]:;\\\"~|?#@^/$%*\")\n .build()\n assertThat(url.toString())\n .isEqualTo(\"http://host/=[]:;%22~%7C%3F%23@%5E%2F$%25*\")\n assertThat(url.toUri().toString())\n .isEqualTo(\"http://host/=%5B%5D:;%22~%7C%3F%23@%5E%2F$%25*\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":34,"symbol":"parse","kind":"function","lang":"kotlin","code":"protected open fun parse(url: String): HttpUrl = url.toHttpUrl()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":36,"symbol":"assertInvalid","kind":"function","lang":"kotlin","code":"protected open fun assertInvalid(\n string: String,\n exceptionMessage: String?,\n ) {\n try {\n val result = string.toHttpUrl()\n if (exceptionMessage != null) {\n fail(\"Expected failure with $exceptionMessage but got $result\")\n } else {\n fail(\"Expected failure but got $result\")\n }\n } catch (iae: IllegalArgumentException) {\n iae.printStackTrace()\n if (exceptionMessage != null) {\n assertThat(iae).hasMessage(exceptionMessage)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":55,"symbol":"parseTrimsAsciiWhitespace","kind":"function","lang":"kotlin","code":"@Test\n fun parseTrimsAsciiWhitespace() {\n val expected = parse(\"http://host/\")\n // Leading.\n assertThat(parse(\"http://host/\\u000c\\n\\t \\r\")).isEqualTo(expected)\n // Trailing.\n assertThat(parse(\"\\r\\n\\u000c \\thttp://host/\")).isEqualTo(expected)\n // Both.\n assertThat(parse(\" http://host/ \")).isEqualTo(expected)\n // Both.\n assertThat(parse(\" http://host/ \")).isEqualTo(expected)\n assertThat(parse(\"http://host/\").resolve(\" \")).isEqualTo(expected)\n assertThat(parse(\"http://host/\").resolve(\" . \")).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":70,"symbol":"parseHostAsciiNonPrintable","kind":"function","lang":"kotlin","code":"@Test\n fun parseHostAsciiNonPrintable() {\n val host = \"host\\u0001\"\n assertInvalid(\"http://$host/\", \"Invalid URL host: \\\"host\\u0001\\\"\")\n // TODO make exception message escape non-printable characters\n }\n\n @Test\n fun parseDoesNotTrimOtherWhitespaceCharacters() {\n // Whitespace characters list from Google's Guava team: http://goo.gl/IcR9RD\n // line tabulation\n assertThat(parse(\"http://h/\\u000b\").encodedPath).isEqualTo(\"/%0B\")\n // information separator 4\n assertThat(parse(\"http://h/\\u001c\").encodedPath).isEqualTo(\"/%1C\")\n // information separator 3\n assertThat(parse(\"http://h/\\u001d\").encodedPath).isEqualTo(\"/%1D\")\n // information separator 2\n assertThat(parse(\"http://h/\\u001e\").encodedPath).isEqualTo(\"/%1E\")\n // information separator 1\n assertThat(parse(\"http://h/\\u001f\").encodedPath).isEqualTo(\"/%1F\")\n // next line\n assertThat(parse(\"http://h/\\u0085\").encodedPath).isEqualTo(\"/%C2%85\")\n // non-breaking space\n assertThat(parse(\"http://h/\\u00a0\").encodedPath).isEqualTo(\"/%C2%A0\")\n // ogham space mark\n assertThat(parse(\"http://h/\\u1680\").encodedPath).isEqualTo(\"/%E1%9A%80\")\n // mongolian vowel separator\n assertThat(par"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":142,"symbol":"newBuilderResolve","kind":"function","lang":"kotlin","code":"@Test\n fun newBuilderResolve() {\n // Non-exhaustive tests because implementation is the same as resolve.\n val base = parse(\"http://host/a/b\")\n assertThat(base.newBuilder(\"https://host2\")!!.build())\n .isEqualTo(parse(\"https://host2/\"))\n assertThat(base.newBuilder(\"//host2\")!!.build())\n .isEqualTo(parse(\"http://host2/\"))\n assertThat(base.newBuilder(\"/path\")!!.build())\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.newBuilder(\"path\")!!.build())\n .isEqualTo(parse(\"http://host/a/path\"))\n assertThat(base.newBuilder(\"?query\")!!.build())\n .isEqualTo(parse(\"http://host/a/b?query\"))\n assertThat(base.newBuilder(\"#fragment\")!!.build())\n .isEqualTo(parse(\"http://host/a/b#fragment\"))\n assertThat(base.newBuilder(\"\")!!.build()).isEqualTo(parse(\"http://host/a/b\"))\n assertThat(base.newBuilder(\"ftp://b\")).isNull()\n assertThat(base.newBuilder(\"ht+tp://b\")).isNull()\n assertThat(base.newBuilder(\"ht-tp://b\")).isNull()\n assertThat(base.newBuilder(\"ht.tp://b\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":165,"symbol":"redactedUrl","kind":"function","lang":"kotlin","code":"@Test\n fun redactedUrl() {\n val baseWithPasswordAndUsername = parse(\"http://username:password@host/a/b#fragment\")\n val baseWithUsernameOnly = parse(\"http://username@host/a/b#fragment\")\n val baseWithPasswordOnly = parse(\"http://password@host/a/b#fragment\")\n assertThat(baseWithPasswordAndUsername.redact()).isEqualTo(\"http://host/...\")\n assertThat(baseWithUsernameOnly.redact()).isEqualTo(\"http://host/...\")\n assertThat(baseWithPasswordOnly.redact()).isEqualTo(\"http://host/...\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":175,"symbol":"resolveNoScheme","kind":"function","lang":"kotlin","code":"@Test\n fun resolveNoScheme() {\n val base = parse(\"http://host/a/b\")\n assertThat(base.resolve(\"//host2\")).isEqualTo(parse(\"http://host2/\"))\n assertThat(base.resolve(\"/path\")).isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"path\")).isEqualTo(parse(\"http://host/a/path\"))\n assertThat(base.resolve(\"?query\")).isEqualTo(parse(\"http://host/a/b?query\"))\n assertThat(base.resolve(\"#fragment\"))\n .isEqualTo(parse(\"http://host/a/b#fragment\"))\n assertThat(base.resolve(\"\")).isEqualTo(parse(\"http://host/a/b\"))\n assertThat(base.resolve(\"\\\\path\")).isEqualTo(parse(\"http://host/path\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":188,"symbol":"resolveUnsupportedScheme","kind":"function","lang":"kotlin","code":"@Test\n fun resolveUnsupportedScheme() {\n val base = parse(\"http://a/\")\n assertThat(base.resolve(\"ftp://b\")).isNull()\n assertThat(base.resolve(\"ht+tp://b\")).isNull()\n assertThat(base.resolve(\"ht-tp://b\")).isNull()\n assertThat(base.resolve(\"ht.tp://b\")).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":197,"symbol":"resolveSchemeLikePath","kind":"function","lang":"kotlin","code":"@Test\n fun resolveSchemeLikePath() {\n val base = parse(\"http://a/\")\n assertThat(base.resolve(\"http//b/\")).isEqualTo(parse(\"http://a/http//b/\"))\n assertThat(base.resolve(\"ht+tp//b/\")).isEqualTo(parse(\"http://a/ht+tp//b/\"))\n assertThat(base.resolve(\"ht-tp//b/\")).isEqualTo(parse(\"http://a/ht-tp//b/\"))\n assertThat(base.resolve(\"ht.tp//b/\")).isEqualTo(parse(\"http://a/ht.tp//b/\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":209,"symbol":"rfc3886NormalExamples","kind":"function","lang":"kotlin","doc":"https://tools.ietf.org/html/rfc3986#section-5.4.1","code":"@Test\n fun rfc3886NormalExamples() {\n val url = parse(\"http://a/b/c/d;p?q\")\n // No 'g:' scheme in HttpUrl.\n assertThat(url.resolve(\"g:h\")).isNull()\n assertThat(url.resolve(\"g\")).isEqualTo(parse(\"http://a/b/c/g\"))\n assertThat(url.resolve(\"./g\")).isEqualTo(parse(\"http://a/b/c/g\"))\n assertThat(url.resolve(\"g/\")).isEqualTo(parse(\"http://a/b/c/g/\"))\n assertThat(url.resolve(\"/g\")).isEqualTo(parse(\"http://a/g\"))\n assertThat(url.resolve(\"//g\")).isEqualTo(parse(\"http://g\"))\n assertThat(url.resolve(\"?y\")).isEqualTo(parse(\"http://a/b/c/d;p?y\"))\n assertThat(url.resolve(\"g?y\")).isEqualTo(parse(\"http://a/b/c/g?y\"))\n assertThat(url.resolve(\"#s\")).isEqualTo(parse(\"http://a/b/c/d;p?q#s\"))\n assertThat(url.resolve(\"g#s\")).isEqualTo(parse(\"http://a/b/c/g#s\"))\n assertThat(url.resolve(\"g?y#s\")).isEqualTo(parse(\"http://a/b/c/g?y#s\"))\n assertThat(url.resolve(\";x\")).isEqualTo(parse(\"http://a/b/c/;x\"))\n assertThat(url.resolve(\"g;x\")).isEqualTo(parse(\"http://a/b/c/g;x\"))\n assertThat(url.resolve(\"g;x?y#s\")).isEqualTo(parse(\"http://a/b/c/g;x?y#s\"))\n assertThat(url.resolve(\"\")).isEqualTo(parse(\"http://a/b/c/d;p?q\"))\n assertThat(url.resolve(\".\")).isEqualTo(p"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":241,"symbol":"rfc3886AbnormalExamples","kind":"function","lang":"kotlin","doc":"https://tools.ietf.org/html/rfc3986#section-5.4.2","code":"@Test\n fun rfc3886AbnormalExamples() {\n val url = parse(\"http://a/b/c/d;p?q\")\n assertThat(url.resolve(\"../../../g\")).isEqualTo(parse(\"http://a/g\"))\n assertThat(url.resolve(\"../../../../g\")).isEqualTo(parse(\"http://a/g\"))\n assertThat(url.resolve(\"/./g\")).isEqualTo(parse(\"http://a/g\"))\n assertThat(url.resolve(\"/../g\")).isEqualTo(parse(\"http://a/g\"))\n assertThat(url.resolve(\"g.\")).isEqualTo(parse(\"http://a/b/c/g.\"))\n assertThat(url.resolve(\".g\")).isEqualTo(parse(\"http://a/b/c/.g\"))\n assertThat(url.resolve(\"g..\")).isEqualTo(parse(\"http://a/b/c/g..\"))\n assertThat(url.resolve(\"..g\")).isEqualTo(parse(\"http://a/b/c/..g\"))\n assertThat(url.resolve(\"./../g\")).isEqualTo(parse(\"http://a/b/g\"))\n assertThat(url.resolve(\"./g/.\")).isEqualTo(parse(\"http://a/b/c/g/\"))\n assertThat(url.resolve(\"g/./h\")).isEqualTo(parse(\"http://a/b/c/g/h\"))\n assertThat(url.resolve(\"g/../h\")).isEqualTo(parse(\"http://a/b/c/h\"))\n assertThat(url.resolve(\"g;x=1/./y\")).isEqualTo(parse(\"http://a/b/c/g;x=1/y\"))\n assertThat(url.resolve(\"g;x=1/../y\")).isEqualTo(parse(\"http://a/b/c/y\"))\n assertThat(url.resolve(\"g?y/./x\")).isEqualTo(parse(\"http://a/b/c/g?y/./x\"))\n assertThat(url.r"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":266,"symbol":"parseAuthoritySlashCountDoesntMatter","kind":"function","lang":"kotlin","code":"@Test\n fun parseAuthoritySlashCountDoesntMatter() {\n assertThat(parse(\"http:host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http://host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:\\\\/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:/\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:\\\\\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:///host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:\\\\//host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:/\\\\/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http://\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:\\\\\\\\/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http:/\\\\\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat("} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":300,"symbol":"resolveAuthoritySlashCountDoesntMatterWithDifferentScheme","kind":"function","lang":"kotlin","code":"@Test\n fun resolveAuthoritySlashCountDoesntMatterWithDifferentScheme() {\n val base = parse(\"https://a/b/c\")\n assertThat(base.resolve(\"http:host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http://host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:/\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:///host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\//host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:/\\\\/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http://\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\\\\\/host/path\"))\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":335,"symbol":"resolveAuthoritySlashCountMattersWithSameScheme","kind":"function","lang":"kotlin","code":"@Test\n fun resolveAuthoritySlashCountMattersWithSameScheme() {\n val base = parse(\"http://a/b/c\")\n assertThat(base.resolve(\"http:host/path\"))\n .isEqualTo(parse(\"http://a/b/host/path\"))\n assertThat(base.resolve(\"http:/host/path\"))\n .isEqualTo(parse(\"http://a/host/path\"))\n assertThat(base.resolve(\"http:\\\\host/path\"))\n .isEqualTo(parse(\"http://a/host/path\"))\n assertThat(base.resolve(\"http://host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:/\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:///host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\//host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:/\\\\/host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http://\\\\host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(base.resolve(\"http:\\\\\\\\/host/path\"))\n .i"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":370,"symbol":"username","kind":"function","lang":"kotlin","code":"@Test\n fun username() {\n assertThat(parse(\"http://@host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http://user@host/path\"))\n .isEqualTo(parse(\"http://user@host/path\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":381,"symbol":"authorityWithMultipleAtSigns","kind":"function","lang":"kotlin","doc":"Given multiple '@' characters, the last one is the delimiter.","code":"@Test\n fun authorityWithMultipleAtSigns() {\n val httpUrl = parse(\"http://foo@bar@baz/path\")\n assertThat(httpUrl.username).isEqualTo(\"foo@bar\")\n assertThat(httpUrl.password).isEqualTo(\"\")\n assertThat(httpUrl).isEqualTo(parse(\"http://foo%40bar@baz/path\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":392,"symbol":"authorityWithMultipleColons","kind":"function","lang":"kotlin","doc":"Given multiple ':' characters, the first one is the delimiter.","code":"@Test\n fun authorityWithMultipleColons() {\n val httpUrl = parse(\"http://foo:pass1@bar:pass2@baz/path\")\n assertThat(httpUrl.username).isEqualTo(\"foo\")\n assertThat(httpUrl.password).isEqualTo(\"pass1@bar:pass2\")\n assertThat(httpUrl).isEqualTo(parse(\"http://foo:pass1%40bar%3Apass2@baz/path\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":400,"symbol":"usernameAndPassword","kind":"function","lang":"kotlin","code":"@Test\n fun usernameAndPassword() {\n assertThat(parse(\"http://username:password@host/path\"))\n .isEqualTo(parse(\"http://username:password@host/path\"))\n assertThat(parse(\"http://username:@host/path\"))\n .isEqualTo(parse(\"http://username@host/path\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":408,"symbol":"passwordWithEmptyUsername","kind":"function","lang":"kotlin","code":"@Test\n fun passwordWithEmptyUsername() {\n // Chrome doesn't mind, but Firefox rejects URLs with empty usernames and non-empty passwords.\n assertThat(parse(\"http://:@host/path\"))\n .isEqualTo(parse(\"http://host/path\"))\n assertThat(parse(\"http://:password@@host/path\").encodedPassword)\n .isEqualTo(\"password%40\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":417,"symbol":"unprintableCharactersArePercentEncoded","kind":"function","lang":"kotlin","code":"@Test\n fun unprintableCharactersArePercentEncoded() {\n assertThat(parse(\"http://host/\\u0000\").encodedPath).isEqualTo(\"/%00\")\n assertThat(parse(\"http://host/\\u0008\").encodedPath).isEqualTo(\"/%08\")\n assertThat(parse(\"http://host/\\ufffd\").encodedPath).isEqualTo(\"/%EF%BF%BD\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":424,"symbol":"usernameCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun usernameCharacters() {\n if (!isJvm) return // TODO: this test is broken on non-JVM platforms.\n UrlComponentEncodingTester\n .newInstance()\n .override(\n Encoding.PERCENT,\n '['.code,\n ']'.code,\n '{'.code,\n '}'.code,\n '|'.code,\n '^'.code,\n '\\''.code,\n ';'.code,\n '='.code,\n '@'.code,\n ).override(\n Encoding.SKIP,\n ':'.code,\n '/'.code,\n '\\\\'.code,\n '?'.code,\n '#'.code,\n ).test(UrlComponentEncodingTester.Component.USER)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/HttpUrlTest.kt","line":451,"symbol":"passwordCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun passwordCharacters() {\n if (!isJvm) return // TODO: this test is broken on non-JVM platforms.\n UrlComponentEncodingTester\n .newInstance()\n .override(\n Encoding.PERCENT,\n '['.code,\n ']'.code,\n '{'.code,\n '}'.code,\n '|'.code,\n '^'.code,\n '\\''.code,\n ':'.code,\n ';'.code,\n '='.code,\n '@'.code,\n ).override(\n Encoding.SKIP,\n '/'.code,\n '\\\\'.code,\n '?'.code,\n '#'.code,\n ).test(UrlComponentEncodingTester.Component.PASSWORD)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InsecureForHostTest.kt","line":35,"symbol":"InsecureForHostTest","kind":"class","lang":"kotlin","code":"class InsecureForHostTest {\n @RegisterExtension @JvmField\n val platform = PlatformRule()\n\n @RegisterExtension @JvmField\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setup() {\n // BCX509ExtendedTrustManager not supported in TlsUtil.newTrustManager\n platform.assumeNotBouncyCastle()\n }\n\n @Test fun `untrusted host in insecureHosts connects successfully`() {\n val serverCertificates = platform.localhostHandshakeCertificates()\n server.useHttps(serverCertificates.sslSocketFactory())\n server.enqueue(MockResponse())\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .addPlatformTrustedCertificates()\n .addInsecureHost(server.hostName)\n .build()\n\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.handshake!!.cipherSuite).isNotNull()\n assertThat(response.handshake!!."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InsecureForHostTest.kt","line":45,"symbol":"setup","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setup() {\n // BCX509ExtendedTrustManager not supported in TlsUtil.newTrustManager\n platform.assumeNotBouncyCastle()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InsecureForHostTest.kt","line":51,"symbol":"`untrusted host in insecureHosts connects successfully`","kind":"function","lang":"kotlin","code":"@Test fun `untrusted host in insecureHosts connects successfully`() {\n val serverCertificates = platform.localhostHandshakeCertificates()\n server.useHttps(serverCertificates.sslSocketFactory())\n server.enqueue(MockResponse())\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .addPlatformTrustedCertificates()\n .addInsecureHost(server.hostName)\n .build()\n\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.handshake!!.cipherSuite).isNotNull()\n assertThat(response.handshake!!.tlsVersion).isNotNull()\n assertThat(response.handshake!!.localCertificates).isEmpty()\n assertThat(response.handshake!!.localPrincipal).isNull()\n assertThat(response.handshake!!.peerCertificates).isEmpty()\n assertThat(response.handshake!!.peerPrincipal).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InsecureForHostTest.kt","line":80,"symbol":"`bad certificates host in insecureHosts fails with SSLException`","kind":"function","lang":"kotlin","code":"@Test fun `bad certificates host in insecureHosts fails with SSLException`() {\n val heldCertificate =\n HeldCertificate\n .Builder()\n .addSubjectAlternativeName(\"example.com\")\n .build()\n val serverCertificates =\n HandshakeCertificates\n .Builder()\n .heldCertificate(heldCertificate)\n .build()\n server.useHttps(serverCertificates.sslSocketFactory())\n server.enqueue(MockResponse())\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .addPlatformTrustedCertificates()\n .addInsecureHost(server.hostName)\n .build()\n\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n val call = client.newCall(Request(server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InsecureForHostTest.kt","line":113,"symbol":"`untrusted host not in insecureHosts fails with SSLException`","kind":"function","lang":"kotlin","code":"@Test fun `untrusted host not in insecureHosts fails with SSLException`() {\n val serverCertificates = platform.localhostHandshakeCertificates()\n server.useHttps(serverCertificates.sslSocketFactory())\n server.enqueue(MockResponse())\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .addPlatformTrustedCertificates()\n .addInsecureHost(\"${server.hostName}2\")\n .build()\n\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n val call = client.newCall(Request(server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":82,"symbol":"testOverrideInApplicationInterceptor","kind":"function","lang":"kotlin","doc":"Test that we can override in a Application Interceptor, purely by seeing that the chain reports the override in a Network Interceptor.","code":"@Test\n fun testOverrideInApplicationInterceptor(\n override: OverrideParam =\n burstValues(\n OverrideParam.Authenticator,\n OverrideParam.Cache,\n OverrideParam.CertificatePinner,\n OverrideParam.ConnectTimeout,\n OverrideParam.ConnectionPool,\n OverrideParam.CookieJar,\n OverrideParam.Dns,\n OverrideParam.HostnameVerifier,\n OverrideParam.Proxy,\n OverrideParam.ProxyAuthenticator,\n OverrideParam.ProxySelector,\n OverrideParam.ReadTimeout,\n OverrideParam.RetryOnConnectionFailure,\n OverrideParam.SocketFactory,\n OverrideParam.SslSocketFactory,\n OverrideParam.WriteTimeout,\n OverrideParam.X509TrustManager,\n ),\n isDefault: Boolean,\n ) {\n fun Override.testApplicationInterceptor(chain: Interceptor.Chain): Response {\n val defaultValue = chain.value()\n assertThat(isDefaultValue(chain.value())).isTrue()\n val withOverride = chain.withOverride(nonDefaultValue)\n assertThat(chain).isNotSameInstanceAs(withOverride)\n assertThat(isDefaultValue(withOverride.value())).isFalse()\n\n return if (isDefault) {\n val withDefault = withOverr"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":106,"symbol":"testApplicationInterceptor","kind":"function","lang":"kotlin","code":"fun Override.testApplicationInterceptor(chain: Interceptor.Chain): Response {\n val defaultValue = chain.value()\n assertThat(isDefaultValue(chain.value())).isTrue()\n val withOverride = chain.withOverride(nonDefaultValue)\n assertThat(chain).isNotSameInstanceAs(withOverride)\n assertThat(isDefaultValue(withOverride.value())).isFalse()\n\n return if (isDefault) {\n val withDefault = withOverride.withOverride(defaultValue)\n assertThat(isDefaultValue(withDefault.value())).isTrue()\n withOverride.proceed(chain.request())\n } else {\n withOverride.proceed(chain.request())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":144,"symbol":"testOverrideInNetworkInterceptor","kind":"function","lang":"kotlin","doc":"Test that we can't override in a Network Interceptor, which will throw an exception.","code":"@Test\n fun testOverrideInNetworkInterceptor(\n override: OverrideParam =\n burstValues(\n OverrideParam.Authenticator,\n OverrideParam.Cache,\n OverrideParam.CertificatePinner,\n OverrideParam.ConnectTimeout,\n OverrideParam.ConnectionPool,\n OverrideParam.CookieJar,\n OverrideParam.Dns,\n OverrideParam.HostnameVerifier,\n OverrideParam.Proxy,\n OverrideParam.ProxyAuthenticator,\n OverrideParam.ProxySelector,\n OverrideParam.ReadTimeout,\n OverrideParam.RetryOnConnectionFailure,\n OverrideParam.SocketFactory,\n OverrideParam.SslSocketFactory,\n OverrideParam.WriteTimeout,\n OverrideParam.X509TrustManager,\n ),\n ) {\n with(override.override) {\n client =\n client\n .newBuilder()\n .addNetworkInterceptor { chain ->\n assertThat(isDefaultValue(chain.value())).isTrue()\n\n assertFailure {\n chain.withOverride(\n nonDefaultValue,\n )\n }.hasMessage(\"${override.paramName} can't be adjusted in a network interceptor\")\n\n chain.proceed(chain.request())\n }.build()\n\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":584,"symbol":"onPathParameter","kind":"function","lang":"kotlin","code":"override fun onPathParameter(\n path: Path,\n functionName: String,\n parameterName: String,\n ): Path = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":598,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): java.net.Proxy? = proxy"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":600,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: java.net.Proxy?): Interceptor.Chain = withProxy(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":602,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: java.net.Proxy?): OkHttpClient.Builder = proxy(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":609,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: java.net.Proxy?): Boolean = value == null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":613,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): ProxySelector = proxySelector"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":615,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: ProxySelector): Interceptor.Chain = withProxySelector(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":617,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: ProxySelector): OkHttpClient.Builder = proxySelector(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":621,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI?): MutableList = mutableListOf(java.net.Proxy.NO_PROXY)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":623,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI?,\n sa: SocketAddress?,\n ioe: java.io.IOException?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":633,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI?): MutableList = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":635,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI?,\n sa: SocketAddress?,\n ioe: java.io.IOException?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":643,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: ProxySelector): Boolean = value === ProxySelector.getDefault()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":647,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): Authenticator = proxyAuthenticator"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":649,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: Authenticator): Interceptor.Chain = withProxyAuthenticator(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":651,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: Authenticator): OkHttpClient.Builder = proxyAuthenticator(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":657,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: Authenticator): Boolean = value === Authenticator.NONE"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":661,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): SSLSocketFactory? = sslSocketFactoryOrNull"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":663,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: SSLSocketFactory?): Interceptor.Chain =\n withSslSocketFactory(value, x509TrustManagerOrNull)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":666,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: SSLSocketFactory?): OkHttpClient.Builder =\n sslSocketFactory(value!!, x509TrustManagerOrNull!!)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":675,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"override fun configureSocket(sslSocket: SSLSocket): SSLSocket = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":678,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: SSLSocketFactory?): Boolean = value !is DelegatingSSLSocketFactory"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":684,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): X509TrustManager? = x509TrustManagerOrNull"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":686,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: X509TrustManager?): Interceptor.Chain =\n withSslSocketFactory(Platform.get().newSslSocketFactory(value!!), value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":689,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: X509TrustManager?): OkHttpClient.Builder =\n sslSocketFactory(Platform.get().newSslSocketFactory(value!!), value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":694,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n x509Certificates: Array,\n s: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":700,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n x509Certificates: Array,\n s: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":706,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = arrayOf()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":711,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n x509Certificates: Array,\n s: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":717,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n x509Certificates: Array,\n s: String,\n ) {\n TODO()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":724,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = arrayOf()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":727,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: X509TrustManager?): Boolean =\n !value\n ?.javaClass\n ?.name\n .orEmpty()\n .startsWith(\"okhttp\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":736,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): HostnameVerifier = hostnameVerifier"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":738,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: HostnameVerifier): Interceptor.Chain = withHostnameVerifier(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":740,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: HostnameVerifier): OkHttpClient.Builder = hostnameVerifier(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":746,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: HostnameVerifier): Boolean = value === okhttp3.internal.tls.OkHostnameVerifier"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":750,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): CertificatePinner = certificatePinner"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":752,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: CertificatePinner): Interceptor.Chain = withCertificatePinner(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":754,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: CertificatePinner): OkHttpClient.Builder = certificatePinner(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":765,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: CertificatePinner): Boolean = value.pins.isEmpty()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":769,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): ConnectionPool = connectionPool"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":771,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: ConnectionPool): Interceptor.Chain = withConnectionPool(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":773,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: ConnectionPool): OkHttpClient.Builder = connectionPool(value)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":783,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n route: Route,\n call: Call,\n ): Unit = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":790,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: ConnectionPool): Boolean = value.delegate.keepAliveDurationNs == 5.minutes.inWholeNanoseconds"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":794,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): Int = connectTimeoutMillis()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":796,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: Int): Interceptor.Chain = withConnectTimeout(value, TimeUnit.MILLISECONDS)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":798,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: Int): OkHttpClient.Builder =\n connectTimeout(value.toLong(), TimeUnit.MILLISECONDS)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":806,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: Int): Boolean = value == 10000"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":810,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): Int = readTimeoutMillis()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":812,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: Int): Interceptor.Chain = withReadTimeout(value, TimeUnit.MILLISECONDS)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":814,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: Int): OkHttpClient.Builder = readTimeout(value.toLong(), TimeUnit.MILLISECONDS)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":821,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: Int): Boolean = value == 10000"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":825,"symbol":"value","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.value(): Int = writeTimeoutMillis()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":827,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun Interceptor.Chain.withOverride(value: Int): Interceptor.Chain = withWriteTimeout(value, TimeUnit.MILLISECONDS)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":829,"symbol":"withOverride","kind":"function","lang":"kotlin","code":"override fun OkHttpClient.Builder.withOverride(value: Int): OkHttpClient.Builder = writeTimeout(value.toLong(), TimeUnit.MILLISECONDS)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorOverridesTest.kt","line":836,"symbol":"isDefaultValue","kind":"function","lang":"kotlin","code":"override fun isDefaultValue(value: Int): Boolean = value == 10000"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":57,"symbol":"InterceptorTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slow\")\nclass InterceptorTest {\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private var client = clientTestRule.newClient()\n private val callback = RecordingCallback()\n\n @Test\n fun applicationInterceptorsCanShortCircuitResponses() {\n server.close() // Accept no connections.\n val request =\n Request\n .Builder()\n .url(\"https://localhost:1/\")\n .build()\n val interceptorResponse =\n Response\n .Builder()\n .request(request)\n .protocol(Protocol.HTTP_1_1)\n .code(200)\n .message(\"Intercepted!\")\n .body(\"abc\".toResponseBody(\"text/plain; charset=utf-8\".toMediaType()))\n .build()\n client =\n client\n .newBuilder()\n .addInterceptor(Interceptor { chain: Interceptor.Chain? -> interceptorResponse })\n .build()\n val response = client.newCall(request).execute()\n assertThat(response).isSameInstanceAs(interceptorResponse)\n }\n\n @Test\n fun networkInterceptorsCannotShortCircuitResponses() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(500)\n .build(),\n )\n val inter"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":68,"symbol":"applicationInterceptorsCanShortCircuitResponses","kind":"function","lang":"kotlin","code":"@Test\n fun applicationInterceptorsCanShortCircuitResponses() {\n server.close() // Accept no connections.\n val request =\n Request\n .Builder()\n .url(\"https://localhost:1/\")\n .build()\n val interceptorResponse =\n Response\n .Builder()\n .request(request)\n .protocol(Protocol.HTTP_1_1)\n .code(200)\n .message(\"Intercepted!\")\n .body(\"abc\".toResponseBody(\"text/plain; charset=utf-8\".toMediaType()))\n .build()\n client =\n client\n .newBuilder()\n .addInterceptor(Interceptor { chain: Interceptor.Chain? -> interceptorResponse })\n .build()\n val response = client.newCall(request).execute()\n assertThat(response).isSameInstanceAs(interceptorResponse)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":94,"symbol":"networkInterceptorsCannotShortCircuitResponses","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorsCannotShortCircuitResponses() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(500)\n .build(),\n )\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n Response\n .Builder()\n .request(chain.request())\n .protocol(Protocol.HTTP_1_1)\n .code(200)\n .message(\"Intercepted!\")\n .body(\"abc\".toResponseBody(\"text/plain; charset=utf-8\".toMediaType()))\n .build()\n }\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(interceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"network interceptor $interceptor must call proceed() exactly once\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":132,"symbol":"networkInterceptorsCannotCallProceedMultipleTimes","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorsCannotCallProceedMultipleTimes() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n chain.proceed(chain.request())\n chain.proceed(chain.request())\n }\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(interceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"network interceptor $interceptor must call proceed() exactly once\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":160,"symbol":"networkInterceptorsCannotChangeServerAddress","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorsCannotChangeServerAddress() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(500)\n .build(),\n )\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n val address = chain.connection()!!.route().address\n val sameHost = address.url.host\n val differentPort = address.url.port + 1\n chain.proceed(\n chain\n .request()\n .newBuilder()\n .url(\"http://$sameHost:$differentPort/\")\n .build(),\n )\n }\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(interceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"network interceptor $interceptor must retain the same host and port\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":200,"symbol":"networkInterceptorsHaveConnectionAccess","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorsHaveConnectionAccess() {\n server.enqueue(MockResponse())\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n val connection = chain.connection()\n assertThat(connection).isNotNull()\n chain.proceed(chain.request())\n }\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(interceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n client.newCall(request).execute()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":222,"symbol":"networkInterceptorsObserveNetworkHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorsObserveNetworkHeaders() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(gzip(\"abcabcabc\"))\n .addHeader(\"Content-Encoding: gzip\")\n .build(),\n )\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n // The network request has everything: User-Agent, Host, Accept-Encoding.\n val networkRequest = chain.request()\n assertThat(networkRequest.header(\"User-Agent\")).isNotNull()\n assertThat(networkRequest.header(\"Host\")).isEqualTo(\n server.hostName + \":\" + server.port,\n )\n assertThat(networkRequest.header(\"Accept-Encoding\")).isNotNull()\n\n // The network response also has everything, including the raw gzipped content.\n val networkResponse = chain.proceed(networkRequest)\n assertThat(networkResponse.header(\"Content-Encoding\")).isEqualTo(\"gzip\")\n networkResponse\n }\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(interceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n\n // No extra headers in the application's request.\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":268,"symbol":"networkInterceptorsCanChangeRequestMethodFromGetToPost","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorsCanChangeRequestMethodFromGetToPost() {\n server.enqueue(MockResponse())\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n val originalRequest = chain.request()\n val mediaType = \"text/plain\".toMediaType()\n val body = \"abc\".toRequestBody(mediaType)\n chain.proceed(\n originalRequest\n .newBuilder()\n .method(\"POST\", body)\n .header(\"Content-Type\", mediaType.toString())\n .header(\"Content-Length\", body.contentLength().toString())\n .build(),\n )\n }\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(interceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .get()\n .build()\n client.newCall(request).execute()\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.method).isEqualTo(\"POST\")\n assertThat(recordedRequest.body?.utf8()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":302,"symbol":"applicationInterceptorsRewriteRequestToServer","kind":"function","lang":"kotlin","code":"@Test\n fun applicationInterceptorsRewriteRequestToServer() {\n rewriteRequestToServer(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":307,"symbol":"networkInterceptorsRewriteRequestToServer","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorsRewriteRequestToServer() {\n rewriteRequestToServer(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":312,"symbol":"rewriteRequestToServer","kind":"function","lang":"kotlin","code":"private fun rewriteRequestToServer(network: Boolean) {\n server.enqueue(MockResponse())\n addInterceptor(network) { chain: Interceptor.Chain ->\n val originalRequest = chain.request()\n chain.proceed(\n originalRequest\n .newBuilder()\n .method(\"POST\", uppercase(originalRequest.body))\n .addHeader(\"OkHttp-Intercepted\", \"yep\")\n .build(),\n )\n }\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .addHeader(\"Original-Header\", \"foo\")\n .method(\"PUT\", \"abc\".toRequestBody(\"text/plain\".toMediaType()))\n .build()\n client.newCall(request).execute()\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.body?.utf8()).isEqualTo(\"ABC\")\n assertThat(recordedRequest.headers[\"Original-Header\"]).isEqualTo(\"foo\")\n assertThat(recordedRequest.headers[\"OkHttp-Intercepted\"]).isEqualTo(\"yep\")\n assertThat(recordedRequest.method).isEqualTo(\"POST\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":339,"symbol":"applicationInterceptorsRewriteResponseFromServer","kind":"function","lang":"kotlin","code":"@Test\n fun applicationInterceptorsRewriteResponseFromServer() {\n rewriteResponseFromServer(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":344,"symbol":"networkInterceptorsRewriteResponseFromServer","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorsRewriteResponseFromServer() {\n rewriteResponseFromServer(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":349,"symbol":"rewriteResponseFromServer","kind":"function","lang":"kotlin","code":"private fun rewriteResponseFromServer(network: Boolean) {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Original-Header: foo\")\n .body(\"abc\")\n .build(),\n )\n addInterceptor(network) { chain: Interceptor.Chain ->\n val originalResponse = chain.proceed(chain.request())\n originalResponse\n .newBuilder()\n .body(uppercase(originalResponse.body))\n .addHeader(\"OkHttp-Intercepted\", \"yep\")\n .build()\n }\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val response = client.newCall(request).execute()\n assertThat(response.body.string()).isEqualTo(\"ABC\")\n assertThat(response.header(\"OkHttp-Intercepted\")).isEqualTo(\"yep\")\n assertThat(response.header(\"Original-Header\")).isEqualTo(\"foo\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":376,"symbol":"multipleApplicationInterceptors","kind":"function","lang":"kotlin","code":"@Test\n fun multipleApplicationInterceptors() {\n multipleInterceptors(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":381,"symbol":"multipleNetworkInterceptors","kind":"function","lang":"kotlin","code":"@Test\n fun multipleNetworkInterceptors() {\n multipleInterceptors(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":386,"symbol":"multipleInterceptors","kind":"function","lang":"kotlin","code":"private fun multipleInterceptors(network: Boolean) {\n server.enqueue(MockResponse())\n addInterceptor(network) { chain: Interceptor.Chain ->\n val originalRequest = chain.request()\n val originalResponse =\n chain.proceed(\n originalRequest\n .newBuilder()\n .addHeader(\"Request-Interceptor\", \"Android\") // 1. Added first.\n .build(),\n )\n originalResponse\n .newBuilder()\n .addHeader(\"Response-Interceptor\", \"Donut\") // 4. Added last.\n .build()\n }\n addInterceptor(network) { chain: Interceptor.Chain ->\n val originalRequest = chain.request()\n val originalResponse =\n chain.proceed(\n originalRequest\n .newBuilder()\n .addHeader(\"Request-Interceptor\", \"Bob\") // 2. Added second.\n .build(),\n )\n originalResponse\n .newBuilder()\n .addHeader(\"Response-Interceptor\", \"Cupcake\") // 3. Added third.\n .build()\n }\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val response = client.newCall(request).execute()\n assertThat(response.headers(\"Response-Interceptor\"))\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":429,"symbol":"asyncApplicationInterceptors","kind":"function","lang":"kotlin","code":"@Test\n fun asyncApplicationInterceptors() {\n asyncInterceptors(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":434,"symbol":"asyncNetworkInterceptors","kind":"function","lang":"kotlin","code":"@Test\n fun asyncNetworkInterceptors() {\n asyncInterceptors(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":439,"symbol":"asyncInterceptors","kind":"function","lang":"kotlin","code":"private fun asyncInterceptors(network: Boolean) {\n server.enqueue(MockResponse())\n addInterceptor(network) { chain: Interceptor.Chain ->\n val originalResponse = chain.proceed(chain.request())\n originalResponse\n .newBuilder()\n .addHeader(\"OkHttp-Intercepted\", \"yep\")\n .build()\n }\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n client.newCall(request).enqueue(callback)\n callback\n .await(request.url)\n .assertCode(200)\n .assertHeader(\"OkHttp-Intercepted\", \"yep\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":460,"symbol":"applicationInterceptorsCanMakeMultipleRequestsToServer","kind":"function","lang":"kotlin","code":"@Test\n fun applicationInterceptorsCanMakeMultipleRequestsToServer() {\n server.enqueue(MockResponse.Builder().body(\"a\").build())\n server.enqueue(MockResponse.Builder().body(\"b\").build())\n client =\n client\n .newBuilder()\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain ->\n val response1 = chain.proceed(chain.request())\n response1.body.close()\n chain.proceed(chain.request())\n },\n ).build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val response = client.newCall(request).execute()\n assertThat(\"b\").isEqualTo(response.body.string())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":484,"symbol":"interceptorMakesAnUnrelatedRequest","kind":"function","lang":"kotlin","doc":"Make sure interceptors can interact with the OkHttp client.","code":"@Test\n fun interceptorMakesAnUnrelatedRequest() {\n server.enqueue(MockResponse.Builder().body(\"a\").build()) // Fetched by interceptor.\n server.enqueue(MockResponse.Builder().body(\"b\").build()) // Fetched directly.\n client =\n client\n .newBuilder()\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain ->\n if (chain.request().url.encodedPath == \"/b\") {\n val requestA =\n Request\n .Builder()\n .url(server.url(\"/a\"))\n .build()\n val responseA = client.newCall(requestA).execute()\n assertThat(responseA.body.string()).isEqualTo(\"a\")\n }\n chain.proceed(chain.request())\n },\n ).build()\n val requestB =\n Request\n .Builder()\n .url(server.url(\"/b\"))\n .build()\n val responseB = client.newCall(requestB).execute()\n assertThat(responseB.body.string()).isEqualTo(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":515,"symbol":"interceptorMakesAnUnrelatedAsyncRequest","kind":"function","lang":"kotlin","doc":"Make sure interceptors can interact with the OkHttp client asynchronously.","code":"@Test\n fun interceptorMakesAnUnrelatedAsyncRequest() {\n server.enqueue(MockResponse.Builder().body(\"a\").build()) // Fetched by interceptor.\n server.enqueue(MockResponse.Builder().body(\"b\").build()) // Fetched directly.\n client =\n client\n .newBuilder()\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain ->\n if (chain.request().url.encodedPath == \"/b\") {\n val requestA =\n Request\n .Builder()\n .url(server.url(\"/a\"))\n .build()\n try {\n val callbackA = RecordingCallback()\n client.newCall(requestA).enqueue(callbackA)\n callbackA.await(requestA.url).assertBody(\"a\")\n } catch (e: Exception) {\n throw RuntimeException(e)\n }\n }\n chain.proceed(chain.request())\n },\n ).build()\n val requestB =\n Request\n .Builder()\n .url(server.url(\"/b\"))\n .build()\n val callbackB = RecordingCallback()\n client.newCall(requestB).enqueue(callbackB)\n callbackB.await(requestB.url).assertBody(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":551,"symbol":"applicationInterceptorThrowsRuntimeExceptionSynchronous","kind":"function","lang":"kotlin","code":"@Test\n fun applicationInterceptorThrowsRuntimeExceptionSynchronous() {\n interceptorThrowsRuntimeExceptionSynchronous(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":556,"symbol":"networkInterceptorThrowsRuntimeExceptionSynchronous","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorThrowsRuntimeExceptionSynchronous() {\n interceptorThrowsRuntimeExceptionSynchronous(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":565,"symbol":"interceptorThrowsRuntimeExceptionSynchronous","kind":"function","lang":"kotlin","doc":"When an interceptor throws an unexpected exception, synchronous callers can catch it and deal with it.","code":"private fun interceptorThrowsRuntimeExceptionSynchronous(network: Boolean) {\n addInterceptor(network) { chain: Interceptor.Chain? -> throw RuntimeException(\"boom!\") }\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"boom!\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":579,"symbol":"networkInterceptorModifiedRequestIsReturned","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorModifiedRequestIsReturned() {\n server.enqueue(MockResponse())\n val modifyHeaderInterceptor =\n Interceptor { chain: Interceptor.Chain ->\n val modifiedRequest =\n chain\n .request()\n .newBuilder()\n .header(\"User-Agent\", \"intercepted request\")\n .build()\n chain.proceed(modifiedRequest)\n }\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(modifyHeaderInterceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"User-Agent\", \"user request\")\n .build()\n val response = client.newCall(request).execute()\n assertThat(response.request.header(\"User-Agent\")).isNotNull()\n assertThat(response.request.header(\"User-Agent\")).isEqualTo(\"user request\")\n assertThat(response.networkResponse!!.request.header(\"User-Agent\")).isEqualTo(\n \"intercepted request\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":611,"symbol":"applicationInterceptorThrowsRuntimeExceptionAsynchronous","kind":"function","lang":"kotlin","code":"@Test\n fun applicationInterceptorThrowsRuntimeExceptionAsynchronous() {\n interceptorThrowsRuntimeExceptionAsynchronous(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":616,"symbol":"networkInterceptorThrowsRuntimeExceptionAsynchronous","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorThrowsRuntimeExceptionAsynchronous() {\n interceptorThrowsRuntimeExceptionAsynchronous(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":625,"symbol":"interceptorThrowsRuntimeExceptionAsynchronous","kind":"function","lang":"kotlin","doc":"When an interceptor throws an unexpected exception, asynchronous calls are canceled. The exception goes to the uncaught exception handler.","code":"private fun interceptorThrowsRuntimeExceptionAsynchronous(network: Boolean) {\n val boom = RuntimeException(\"boom!\")\n addInterceptor(network) { chain: Interceptor.Chain? -> throw boom }\n val executor = ExceptionCatchingExecutor()\n client =\n client\n .newBuilder()\n .dispatcher(Dispatcher(executor))\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val call = client.newCall(request)\n call.enqueue(callback)\n val recordedResponse = callback.await(server.url(\"/\"))\n assertThat(recordedResponse.failure, \"canceled due to java.lang.RuntimeException: boom!\")\n assertThat(recordedResponse.failure?.cause).isEqualTo(boom)\n assertThat(call.isCanceled()).isTrue()\n assertThat(executor.takeException()).isEqualTo(boom)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":648,"symbol":"networkInterceptorReturnsConnectionOnEmptyBody","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorReturnsConnectionOnEmptyBody() {\n server.enqueue(\n MockResponse\n .Builder()\n .onResponseEnd(ShutdownConnection)\n .addHeader(\"Connection\", \"Close\")\n .build(),\n )\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n val response = chain.proceed(chain.request())\n assertThat(chain.connection()).isNotNull()\n response\n }\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(interceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val response = client.newCall(request).execute()\n response.body.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":677,"symbol":"connectTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun connectTimeout() {\n val interceptor1 =\n Interceptor { chainA: Interceptor.Chain ->\n assertThat(chainA.connectTimeoutMillis()).isEqualTo(5000)\n val chainB = chainA.withConnectTimeout(100, TimeUnit.MILLISECONDS)\n assertThat(chainB.connectTimeoutMillis()).isEqualTo(100)\n chainB.proceed(chainA.request())\n }\n val interceptor2 =\n Interceptor { chain: Interceptor.Chain ->\n assertThat(chain.connectTimeoutMillis()).isEqualTo(100)\n chain.proceed(chain.request())\n }\n client =\n client\n .newBuilder()\n .connectTimeout(Duration.ofSeconds(5))\n .addInterceptor(interceptor1)\n .addInterceptor(interceptor2)\n .build()\n val request1 =\n Request\n .Builder()\n .url(\"http://\" + TestUtil.UNREACHABLE_ADDRESS_IPV4)\n .build()\n val call = client.newCall(request1)\n val startNanos = System.nanoTime()\n assertFailsWith {\n call.execute()\n }\n val elapsedNanos = System.nanoTime() - startNanos\n org.junit.jupiter.api.Assertions.assertTrue(\n elapsedNanos < TimeUnit.SECONDS.toNanos(5),\n \"Timeout should have taken ~100m"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":715,"symbol":"chainWithReadTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun chainWithReadTimeout() {\n val interceptor1 =\n Interceptor { chainA: Interceptor.Chain ->\n assertThat(chainA.readTimeoutMillis()).isEqualTo(5000)\n val chainB = chainA.withReadTimeout(100, TimeUnit.MILLISECONDS)\n assertThat(chainB.readTimeoutMillis()).isEqualTo(100)\n chainB.proceed(chainA.request())\n }\n val interceptor2 =\n Interceptor { chain: Interceptor.Chain ->\n assertThat(chain.readTimeoutMillis()).isEqualTo(100)\n chain.proceed(chain.request())\n }\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofSeconds(5))\n .addInterceptor(interceptor1)\n .addInterceptor(interceptor2)\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .throttleBody(1, 1, TimeUnit.SECONDS)\n .build(),\n )\n val request1 =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val call = client.newCall(request1)\n val response = call.execute()\n val body = response.body\n assertFailsWith {\n body.string()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":756,"symbol":"networkInterceptorCannotChangeReadTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorCannotChangeReadTimeout() {\n addInterceptor(true) { chain: Interceptor.Chain ->\n chain\n .withReadTimeout(\n 100,\n TimeUnit.MILLISECONDS,\n ).proceed(chain.request())\n }\n val request1 = Request.Builder().url(server.url(\"/\")).build()\n val call = client.newCall(request1)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Timeouts can't be adjusted in a network interceptor\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":775,"symbol":"networkInterceptorCannotChangeWriteTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorCannotChangeWriteTimeout() {\n addInterceptor(true) { chain: Interceptor.Chain ->\n chain\n .withWriteTimeout(\n 100,\n TimeUnit.MILLISECONDS,\n ).proceed(chain.request())\n }\n val request1 = Request.Builder().url(server.url(\"/\")).build()\n val call = client.newCall(request1)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Timeouts can't be adjusted in a network interceptor\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":794,"symbol":"networkInterceptorCannotChangeConnectTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun networkInterceptorCannotChangeConnectTimeout() {\n addInterceptor(true) { chain: Interceptor.Chain ->\n chain\n .withConnectTimeout(\n 100,\n TimeUnit.MILLISECONDS,\n ).proceed(chain.request())\n }\n val request1 = Request.Builder().url(server.url(\"/\")).build()\n val call = client.newCall(request1)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Timeouts can't be adjusted in a network interceptor\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":813,"symbol":"chainWithWriteTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun chainWithWriteTimeout() {\n val interceptor1 =\n Interceptor { chainA: Interceptor.Chain ->\n assertThat(chainA.writeTimeoutMillis()).isEqualTo(5000)\n val chainB = chainA.withWriteTimeout(100, TimeUnit.MILLISECONDS)\n assertThat(chainB.writeTimeoutMillis()).isEqualTo(100)\n chainB.proceed(chainA.request())\n }\n val interceptor2 =\n Interceptor { chain: Interceptor.Chain ->\n assertThat(chain.writeTimeoutMillis()).isEqualTo(100)\n chain.proceed(chain.request())\n }\n client =\n client\n .newBuilder()\n .writeTimeout(Duration.ofSeconds(5))\n .addInterceptor(interceptor1)\n .addInterceptor(interceptor2)\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .throttleBody(1, 1, TimeUnit.SECONDS)\n .build(),\n )\n val data = ByteArray(2 * 1024 * 1024) // 2 MiB.\n val request1 =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(data.toRequestBody(\"text/plain\".toMediaType()))\n .build()\n val call = client.newCall(request1)\n assertFailsWith {\n call.execute() // we "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":854,"symbol":"chainCanCancelCall","kind":"function","lang":"kotlin","code":"@Test\n fun chainCanCancelCall() {\n val callRef = AtomicReference()\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n val call = chain.call()\n callRef.set(call)\n assertThat(call.isCanceled()).isFalse()\n call.cancel()\n assertThat(call.isCanceled()).isTrue()\n chain.proceed(chain.request())\n }\n client =\n client\n .newBuilder()\n .addInterceptor(interceptor)\n .build()\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val call = client.newCall(request)\n assertFailsWith {\n call.execute()\n }\n assertThat(callRef.get()).isSameInstanceAs(call)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":883,"symbol":"uppercase","kind":"function","lang":"kotlin","code":"private fun uppercase(original: RequestBody?): RequestBody =\n object : RequestBody() {\n override fun contentType(): MediaType? = original!!.contentType()\n\n override fun contentLength(): Long = original!!.contentLength()\n\n override fun writeTo(sink: BufferedSink) {\n val uppercase = uppercase(sink)\n val bufferedSink = uppercase.buffer()\n original!!.writeTo(bufferedSink)\n bufferedSink.emit()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":885,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = original!!.contentType()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":887,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = original!!.contentLength()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":889,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n val uppercase = uppercase(sink)\n val bufferedSink = uppercase.buffer()\n original!!.writeTo(bufferedSink)\n bufferedSink.emit()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":897,"symbol":"uppercase","kind":"function","lang":"kotlin","code":"private fun uppercase(original: BufferedSink): Sink =\n object : ForwardingSink(original) {\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n original.writeUtf8(source.readUtf8(byteCount).uppercase())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":899,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n original.writeUtf8(source.readUtf8(byteCount).uppercase())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":907,"symbol":"gzip","kind":"function","lang":"kotlin","code":"private fun gzip(data: String): Buffer {\n val result = Buffer()\n val sink = GzipSink(result).buffer()\n sink.writeUtf8(data)\n sink.close()\n return result\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":915,"symbol":"addInterceptor","kind":"function","lang":"kotlin","code":"private fun addInterceptor(\n network: Boolean,\n interceptor: Interceptor,\n ) {\n val builder = client.newBuilder()\n if (network) {\n builder.addNetworkInterceptor(interceptor)\n } else {\n builder.addInterceptor(interceptor)\n }\n client = builder.build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":929,"symbol":"ExceptionCatchingExecutor","kind":"class","lang":"kotlin","doc":"Catches exceptions that are otherwise headed for the uncaught exception handler.","code":"private class ExceptionCatchingExecutor : ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, SynchronousQueue()) {\n private val exceptions: BlockingQueue = LinkedBlockingQueue()\n\n override fun execute(runnable: Runnable) {\n super.execute {\n try {\n runnable.run()\n } catch (e: Exception) {\n exceptions.add(e)\n }\n }\n }\n\n fun takeException(): Exception = exceptions.take()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":932,"symbol":"execute","kind":"function","lang":"kotlin","code":"override fun execute(runnable: Runnable) {\n super.execute {\n try {\n runnable.run()\n } catch (e: Exception) {\n exceptions.add(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":942,"symbol":"takeException","kind":"function","lang":"kotlin","code":"fun takeException(): Exception = exceptions.take()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":946,"symbol":"uppercase","kind":"function","lang":"kotlin","code":"fun uppercase(original: ResponseBody): ResponseBody =\n object : ResponseBody() {\n override fun contentType() = original.contentType()\n\n override fun contentLength() = original.contentLength()\n\n override fun source() = uppercase(original.source()).buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":948,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = original.contentType()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":950,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = original.contentLength()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":952,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source() = uppercase(original.source()).buffer()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":955,"symbol":"uppercase","kind":"function","lang":"kotlin","code":"private fun uppercase(original: Source): Source {\n return object : ForwardingSource(original) {\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val mixedCase = Buffer()\n val count = original.read(mixedCase, byteCount)\n sink.writeUtf8(mixedCase.readUtf8().uppercase())\n return count\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/InterceptorTest.kt","line":957,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val mixedCase = Buffer()\n val count = original.read(mixedCase, byteCount)\n sink.writeUtf8(mixedCase.readUtf8().uppercase())\n return count\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/JSSETest.kt","line":40,"symbol":"JSSETest","kind":"class","lang":"kotlin","code":"class JSSETest {\n @JvmField @RegisterExtension\n var platform = PlatformRule()\n\n @JvmField @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n\n var client = clientTestRule.newClient()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n // Default after JDK 14, but we are avoiding tests that assume special setup.\n // System.setProperty(\"jdk.tls.client.enableSessionTicketExtension\", \"true\")\n // System.setProperty(\"jdk.tls.server.enableSessionTicketExtension\", \"true\")\n\n platform.assumeJdk9()\n }\n\n @Test\n fun testTlsv13Works() {\n // https://docs.oracle.com/en/java/javase/14/security/java-secure-socket-extension-jsse-reference-guide.html\n // TODO test jdk.tls.client.enableSessionTicketExtension\n // TODO check debugging information\n\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request(server.url(\"/\"))\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n if (PlatformVersion.majorVersion > 11) {\n assertEquals(TlsVersion.TLS_1_3, "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/JSSETest.kt","line":54,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n // Default after JDK 14, but we are avoiding tests that assume special setup.\n // System.setProperty(\"jdk.tls.client.enableSessionTicketExtension\", \"true\")\n // System.setProperty(\"jdk.tls.server.enableSessionTicketExtension\", \"true\")\n\n platform.assumeJdk9()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/JSSETest.kt","line":63,"symbol":"testTlsv13Works","kind":"function","lang":"kotlin","code":"@Test\n fun testTlsv13Works() {\n // https://docs.oracle.com/en/java/javase/14/security/java-secure-socket-extension-jsse-reference-guide.html\n // TODO test jdk.tls.client.enableSessionTicketExtension\n // TODO check debugging information\n\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request(server.url(\"/\"))\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n if (PlatformVersion.majorVersion > 11) {\n assertEquals(TlsVersion.TLS_1_3, response.handshake?.tlsVersion)\n }\n if (PlatformVersion.majorVersion > 8) {\n assertEquals(Protocol.HTTP_2, response.protocol)\n }\n\n assertThat(\n response.connection\n .socket()\n .javaClass.name,\n ).isEqualTo(\n \"sun.security.ssl.SSLSocketImpl\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/JSSETest.kt","line":96,"symbol":"testSupportedProtocols","kind":"function","lang":"kotlin","code":"@Test\n fun testSupportedProtocols() {\n val factory = SSLSocketFactory.getDefault()\n assertThat(factory.javaClass.name).isEqualTo(\"sun.security.ssl.SSLSocketFactoryImpl\")\n val s = factory.createSocket() as SSLSocket\n\n when {\n PlatformVersion.majorVersion > 11 -> {\n assertThat(s.enabledProtocols.toList()).containsExactly(\n \"TLSv1.3\",\n \"TLSv1.2\",\n )\n }\n\n // Not much we can guarantee on JDK 11.\n PlatformVersion.majorVersion == 11 -> {\n assertThat(s.enabledProtocols.toList()).contains(\n \"TLSv1.2\",\n )\n }\n\n // JDK 8 291 removed older versions\n // See https://java.com/en/jre-jdk-cryptoroadmap.html\n PlatformVersion.majorVersion == 8 -> {\n assertThat(s.enabledProtocols.toList()).contains(\n \"TLSv1.2\",\n )\n }\n\n else -> {\n assertThat(s.enabledProtocols.toList()).containsExactly(\n \"TLSv1.3\",\n \"TLSv1.2\",\n \"TLSv1.1\",\n \"TLSv1\",\n )\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/JSSETest.kt","line":136,"symbol":"testFacebook","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun testFacebook() {\n val sessionIds = mutableListOf()\n\n assumeNetwork()\n\n client =\n client\n .newBuilder()\n .eventListenerFactory(\n clientTestRule.wrap(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n val sslSocket = connection.socket() as SSLSocket\n\n sessionIds.add(\n sslSocket.session.id\n .toByteString()\n .hex(),\n )\n }\n },\n ),\n ).build()\n\n val request = Request.Builder().url(\"https://facebook.com/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n\n client.connectionPool.evictAll()\n assertEquals(0, client.connectionPool.connectionCount())\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersi"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/JSSETest.kt","line":149,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n val sslSocket = connection.socket() as SSLSocket\n\n sessionIds.add(\n sslSocket.session.id\n .toByteString()\n .hex(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/JSSETest.kt","line":185,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":56,"symbol":"KotlinDeprecationErrorTest","kind":"class","lang":"kotlin","doc":"Access every declaration that is deprecated with [DeprecationLevel.ERROR]. Although new Kotlin code shouldn't use these, they're necessary for clients migrating from OkHttp 3.x and this test ensures the symbols remain available and with the expected parameter and return types.","code":"@Suppress(\n \"DEPRECATION_ERROR\",\n \"UNUSED_VALUE\",\n \"UNUSED_VARIABLE\",\n \"VARIABLE_WITH_REDUNDANT_INITIALIZER\",\n)\nclass KotlinDeprecationErrorTest {\n private val factory = TestValueFactory()\n\n @AfterEach\n fun tearDown() {\n factory.close()\n }\n\n @Test @Disabled\n fun address() {\n val address: Address = factory.newAddress()\n val url: HttpUrl = address.url()\n val dns: Dns = address.dns()\n val socketFactory: SocketFactory = address.socketFactory()\n val proxyAuthenticator: Authenticator = address.proxyAuthenticator()\n val protocols: List = address.protocols()\n val connectionSpecs: List = address.connectionSpecs()\n val proxySelector: ProxySelector = address.proxySelector()\n val proxy: Proxy? = address.proxy()\n val sslSocketFactory: SSLSocketFactory? = address.sslSocketFactory()\n val hostnameVerifier: HostnameVerifier? = address.hostnameVerifier()\n val certificatePinner: CertificatePinner? = address.certificatePinner()\n }\n\n @Test @Disabled\n fun cache() {\n val cache = Cache(File(\"/cache/\"), Integer.MAX_VALUE.toLong())\n val directory: File = cache.directory()\n }\n\n @Test @Disabled\n fun cacheControl() {\n val"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":65,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n factory.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":70,"symbol":"address","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun address() {\n val address: Address = factory.newAddress()\n val url: HttpUrl = address.url()\n val dns: Dns = address.dns()\n val socketFactory: SocketFactory = address.socketFactory()\n val proxyAuthenticator: Authenticator = address.proxyAuthenticator()\n val protocols: List = address.protocols()\n val connectionSpecs: List = address.connectionSpecs()\n val proxySelector: ProxySelector = address.proxySelector()\n val proxy: Proxy? = address.proxy()\n val sslSocketFactory: SSLSocketFactory? = address.sslSocketFactory()\n val hostnameVerifier: HostnameVerifier? = address.hostnameVerifier()\n val certificatePinner: CertificatePinner? = address.certificatePinner()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":86,"symbol":"cache","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun cache() {\n val cache = Cache(File(\"/cache/\"), Integer.MAX_VALUE.toLong())\n val directory: File = cache.directory()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":92,"symbol":"cacheControl","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun cacheControl() {\n val cacheControl: CacheControl = CacheControl.Builder().build()\n val noCache: Boolean = cacheControl.noCache()\n val noStore: Boolean = cacheControl.noStore()\n val maxAgeSeconds: Int = cacheControl.maxAgeSeconds()\n val sMaxAgeSeconds: Int = cacheControl.sMaxAgeSeconds()\n val mustRevalidate: Boolean = cacheControl.mustRevalidate()\n val maxStaleSeconds: Int = cacheControl.maxStaleSeconds()\n val minFreshSeconds: Int = cacheControl.minFreshSeconds()\n val onlyIfCached: Boolean = cacheControl.onlyIfCached()\n val noTransform: Boolean = cacheControl.noTransform()\n val immutable: Boolean = cacheControl.immutable()\n val parse: CacheControl = CacheControl.parse(Headers.of())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":108,"symbol":"challenge","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun challenge() {\n val challenge = Challenge(\"\", mapOf(\"\" to \"\"))\n val scheme: String = challenge.scheme()\n val authParams: Map = challenge.authParams()\n val realm: String? = challenge.realm()\n val charset: Charset = challenge.charset()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":117,"symbol":"cipherSuite","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun cipherSuite() {\n val cipherSuite: CipherSuite = CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n val javaName: String = cipherSuite.javaName()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":123,"symbol":"connectionSpec","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun connectionSpec() {\n val connectionSpec: ConnectionSpec = ConnectionSpec.RESTRICTED_TLS\n val tlsVersions: List? = connectionSpec.tlsVersions()\n val cipherSuites: List? = connectionSpec.cipherSuites()\n val supportsTlsExtensions: Boolean = connectionSpec.supportsTlsExtensions()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":131,"symbol":"cookie","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun cookie() {\n val cookie: Cookie = Cookie.Builder().build()\n val name: String = cookie.name()\n val value: String = cookie.value()\n val persistent: Boolean = cookie.persistent()\n val expiresAt: Long = cookie.expiresAt()\n val hostOnly: Boolean = cookie.hostOnly()\n val domain: String = cookie.domain()\n val path: String = cookie.path()\n val httpOnly: Boolean = cookie.httpOnly()\n val secure: Boolean = cookie.secure()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":145,"symbol":"formBody","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun formBody() {\n val formBody: FormBody = FormBody.Builder().build()\n val size: Int = formBody.size()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":151,"symbol":"handshake","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun handshake() {\n val handshake: Handshake =\n Handshake.get((localhost().sslSocketFactory().createSocket() as SSLSocket).session)\n val tlsVersion: TlsVersion = handshake.tlsVersion()\n val cipherSuite: CipherSuite = handshake.cipherSuite()\n val peerCertificates: List = handshake.peerCertificates()\n val peerPrincipal: Principal? = handshake.peerPrincipal()\n val localCertificates: List = handshake.localCertificates()\n val localPrincipal: Principal? = handshake.localPrincipal()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":163,"symbol":"headers","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun headers() {\n var headers: Headers = Headers.of(\"\", \"\")\n headers = Headers.of(mapOf(\"\" to \"\"))\n val size: Int = headers.size()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":170,"symbol":"httpLoggingInterceptor","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun httpLoggingInterceptor() {\n val interceptor = HttpLoggingInterceptor()\n val level = interceptor.getLevel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":176,"symbol":"httpUrl","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun httpUrl() {\n val httpUrl: HttpUrl = HttpUrl.get(\"\")\n val url: URL = httpUrl.url()\n val uri: URI = httpUrl.uri()\n val scheme: String = httpUrl.scheme()\n val encodedUsername: String = httpUrl.encodedUsername()\n val username: String = httpUrl.username()\n val encodedPassword: String = httpUrl.encodedPassword()\n val password: String = httpUrl.password()\n val host: String = httpUrl.host()\n val port: Int = httpUrl.port()\n val pathSize: Int = httpUrl.pathSize()\n val encodedPath: String = httpUrl.encodedPath()\n val encodedPathSegments: List = httpUrl.encodedPathSegments()\n val pathSegments: List = httpUrl.pathSegments()\n val encodedQuery: String? = httpUrl.encodedQuery()\n val query: String? = httpUrl.query()\n val querySize: Int = httpUrl.querySize()\n val queryParameter: String? = httpUrl.queryParameter(\"\")\n val queryParameterNames: Set = httpUrl.queryParameterNames()\n val encodedFragment: String? = httpUrl.encodedFragment()\n val fragment: String? = httpUrl.fragment()\n val getFromUrl: HttpUrl? = HttpUrl.get(URL(\"\"))\n val getFromUri: HttpUrl? = HttpUrl.get(URI(\"\"))\n val parse:"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":204,"symbol":"handshakeCertificates","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun handshakeCertificates() {\n val handshakeCertificates = HandshakeCertificates.Builder().build()\n val keyManager: X509KeyManager = handshakeCertificates.keyManager()\n val trustManager: X509TrustManager = handshakeCertificates.trustManager()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":211,"symbol":"handshakeCertificatesBuilder","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun handshakeCertificatesBuilder() {\n var builder: HandshakeCertificates.Builder = HandshakeCertificates.Builder()\n val heldCertificate: HeldCertificate = HeldCertificate.Builder().build()\n builder = builder.heldCertificate(heldCertificate, heldCertificate.certificate())\n builder = builder.addTrustedCertificate(heldCertificate.certificate())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":219,"symbol":"heldCertificate","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun heldCertificate() {\n val heldCertificate: HeldCertificate = HeldCertificate.Builder().build()\n val certificate: X509Certificate = heldCertificate.certificate()\n val keyPair: KeyPair = heldCertificate.keyPair()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":226,"symbol":"mediaType","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun mediaType() {\n val mediaType: MediaType = MediaType.get(\"\")\n val type: String = mediaType.type()\n val subtype: String = mediaType.subtype()\n val parse: MediaType? = MediaType.parse(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":234,"symbol":"mockResponse","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun mockResponse() {\n val mockResponse = MockResponse()\n var status: String = mockResponse.getStatus()\n var headers: Headers = mockResponse.getHeaders()\n var trailers: Headers = mockResponse.getTrailers()\n var socketPolicy: SocketPolicy = mockResponse.getSocketPolicy()\n var http2ErrorCode: Int = mockResponse.getHttp2ErrorCode()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":244,"symbol":"mockWebServer","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun mockWebServer() {\n val mockWebServer = MockWebServer()\n var port: Int = mockWebServer.getPort()\n mockWebServer.setServerSocketFactory(ServerSocketFactory.getDefault())\n mockWebServer.setBodyLimit(0L)\n mockWebServer.setProtocolNegotiationEnabled(false)\n mockWebServer.setProtocols(listOf(Protocol.HTTP_1_1))\n var requestCount: Int = mockWebServer.getRequestCount()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":255,"symbol":"multipartBody","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun multipartBody() {\n val multipartBody: MultipartBody = MultipartBody.Builder().build()\n val type: MediaType = multipartBody.type()\n val boundary: String = multipartBody.boundary()\n val size: Int = multipartBody.size()\n val parts: List = multipartBody.parts()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":264,"symbol":"multipartBodyPart","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun multipartBodyPart() {\n val multipartBody: MultipartBody = MultipartBody.Builder().build()\n val part: MultipartBody.Part = multipartBody.part(0)\n val headers: Headers? = part.headers()\n val body: RequestBody = part.body()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":272,"symbol":"okHttpClient","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun okHttpClient() {\n val client = OkHttpClient()\n val dispatcher: Dispatcher = client.dispatcher()\n val proxy: Proxy? = client.proxy()\n val protocols: List = client.protocols()\n val connectionSpecs: List = client.connectionSpecs()\n val interceptors: List = client.interceptors()\n val networkInterceptors: List = client.networkInterceptors()\n val eventListenerFactory: EventListener.Factory = client.eventListenerFactory()\n val proxySelector: ProxySelector = client.proxySelector()\n val cookieJar: CookieJar = client.cookieJar()\n val cache: Cache? = client.cache()\n val socketFactory: SocketFactory = client.socketFactory()\n val sslSocketFactory: SSLSocketFactory = client.sslSocketFactory()\n val hostnameVerifier: HostnameVerifier = client.hostnameVerifier()\n val certificatePinner: CertificatePinner = client.certificatePinner()\n val proxyAuthenticator: Authenticator = client.proxyAuthenticator()\n val authenticator: Authenticator = client.authenticator()\n val connectionPool: ConnectionPool = client.connectionPool()\n val dns: Dns = client.dns()\n val followSslRedire"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":303,"symbol":"pushPromise","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun pushPromise() {\n val pushPromise = PushPromise(\"\", \"\", Headers.of(), MockResponse())\n val method: String = pushPromise.method()\n val path: String = pushPromise.path()\n val headers: Headers = pushPromise.headers()\n val response: MockResponse = pushPromise.response()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":312,"symbol":"recordedRequest","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun recordedRequest() {\n val recordedRequest = RecordedRequest(\"\", Headers.of(), listOf(), 0L, Buffer(), 0, Socket())\n var utf8Body: String = recordedRequest.utf8Body\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":318,"symbol":"request","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun request() {\n val request: Request = Request.Builder().build()\n val url: HttpUrl = request.url()\n val method: String = request.method()\n val headers: Headers = request.headers()\n val body: RequestBody? = request.body()\n val cacheControl: CacheControl = request.cacheControl()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":328,"symbol":"response","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun response() {\n val response: Response = Response.Builder().build()\n val request: Request = response.request()\n val protocol: Protocol = response.protocol()\n val code: Int = response.code()\n val message: String = response.message()\n val handshake: Handshake? = response.handshake()\n val headers: Headers = response.headers()\n val body: ResponseBody = response.body()\n val networkResponse: Response? = response.networkResponse()\n val cacheResponse: Response? = response.cacheResponse()\n val priorResponse: Response? = response.priorResponse()\n val cacheControl: CacheControl = response.cacheControl()\n val sentRequestAtMillis: Long = response.sentRequestAtMillis()\n val receivedResponseAtMillis: Long = response.receivedResponseAtMillis()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":346,"symbol":"route","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun route() {\n val route: Route = factory.newRoute()\n val address: Address = route.address()\n val proxy: Proxy = route.proxy()\n val inetSocketAddress: InetSocketAddress = route.socketAddress()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinDeprecationErrorTest.kt","line":354,"symbol":"tlsVersion","kind":"function","lang":"kotlin","code":"@Test @Disabled\n fun tlsVersion() {\n val tlsVersion: TlsVersion = TlsVersion.TLS_1_3\n val javaName: String = tlsVersion.javaName()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":93,"symbol":"KotlinSourceModernTest","kind":"class","lang":"kotlin","doc":"Access every type, function, and property from Kotlin to defend against unexpected regressions in modern 4.0.x kotlin source-compatibility.","code":"@Suppress(\n \"ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE\",\n \"AssignedValueIsNeverRead\",\n \"CanBeVal\",\n \"DEPRECATION\",\n \"IMPLICIT_NOTHING_AS_TYPE_PARAMETER\",\n \"RedundantExplicitType\",\n \"RedundantNullableReturnType\",\n \"UNUSED_ANONYMOUS_PARAMETER\",\n \"UNUSED_VALUE\",\n \"UNUSED_VARIABLE\",\n \"VARIABLE_WITH_REDUNDANT_INITIALIZER\",\n \"VariableInitializerIsRedundant\",\n \"VariableNeverRead\",\n \"unused\",\n)\n@Disabled\nclass KotlinSourceModernTest {\n private val factory = TestValueFactory()\n\n @BeforeEach\n fun disabled() {\n assumeFalse(true)\n }\n\n @AfterEach\n fun tearDown() {\n factory.close()\n }\n\n @Test\n fun address() {\n val address: Address = factory.newAddress()\n val url: HttpUrl = address.url\n val dns: Dns = address.dns\n val socketFactory: SocketFactory = address.socketFactory\n val proxyAuthenticator: Authenticator = address.proxyAuthenticator\n val protocols: List = address.protocols\n val connectionSpecs: List = address.connectionSpecs\n val proxySelector: ProxySelector = address.proxySelector\n val sslSocketFactory: SSLSocketFactory? = address.sslSocketFactory\n val hostnameVerifier: HostnameVerifier? = address.hostnameVerifie"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":113,"symbol":"disabled","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun disabled() {\n assumeFalse(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":118,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n factory.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":123,"symbol":"address","kind":"function","lang":"kotlin","code":"@Test\n fun address() {\n val address: Address = factory.newAddress()\n val url: HttpUrl = address.url\n val dns: Dns = address.dns\n val socketFactory: SocketFactory = address.socketFactory\n val proxyAuthenticator: Authenticator = address.proxyAuthenticator\n val protocols: List = address.protocols\n val connectionSpecs: List = address.connectionSpecs\n val proxySelector: ProxySelector = address.proxySelector\n val sslSocketFactory: SSLSocketFactory? = address.sslSocketFactory\n val hostnameVerifier: HostnameVerifier? = address.hostnameVerifier\n val certificatePinner: CertificatePinner? = address.certificatePinner\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":138,"symbol":"authenticator","kind":"function","lang":"kotlin","code":"@Test\n fun authenticator() {\n var authenticator: Authenticator = Authenticator { route, response -> TODO() }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":143,"symbol":"cache","kind":"function","lang":"kotlin","code":"@Test\n fun cache() {\n val cache = Cache(File(\"/cache/\"), Integer.MAX_VALUE.toLong())\n cache.initialize()\n cache.delete()\n cache.evictAll()\n val urls: MutableIterator = cache.urls()\n val writeAbortCount: Int = cache.writeAbortCount()\n val writeSuccessCount: Int = cache.writeSuccessCount()\n val size: Long = cache.size()\n val maxSize: Long = cache.maxSize()\n cache.flush()\n cache.close()\n val directory: File = cache.directory\n val networkCount: Int = cache.networkCount()\n val hitCount: Int = cache.hitCount()\n val requestCount: Int = cache.requestCount()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":162,"symbol":"cacheControl","kind":"function","lang":"kotlin","code":"@Test\n fun cacheControl() {\n val cacheControl: CacheControl = CacheControl.Builder().build()\n val noCache: Boolean = cacheControl.noCache\n val noStore: Boolean = cacheControl.noStore\n val maxAgeSeconds: Int = cacheControl.maxAgeSeconds\n val sMaxAgeSeconds: Int = cacheControl.sMaxAgeSeconds\n val mustRevalidate: Boolean = cacheControl.mustRevalidate\n val maxStaleSeconds: Int = cacheControl.maxStaleSeconds\n val minFreshSeconds: Int = cacheControl.minFreshSeconds\n val onlyIfCached: Boolean = cacheControl.onlyIfCached\n val noTransform: Boolean = cacheControl.noTransform\n val immutable: Boolean = cacheControl.immutable\n val forceCache: CacheControl = CacheControl.FORCE_CACHE\n val forceNetwork: CacheControl = CacheControl.FORCE_NETWORK\n val parse: CacheControl = CacheControl.parse(headersOf())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":180,"symbol":"cacheControlBuilder","kind":"function","lang":"kotlin","code":"@Test\n fun cacheControlBuilder() {\n var builder: CacheControl.Builder = CacheControl.Builder()\n builder = builder.noCache()\n builder = builder.noStore()\n builder = builder.maxAge(0, TimeUnit.MILLISECONDS)\n builder = builder.maxStale(0, TimeUnit.MILLISECONDS)\n builder = builder.minFresh(0, TimeUnit.MILLISECONDS)\n builder = builder.onlyIfCached()\n builder = builder.noTransform()\n builder = builder.immutable()\n val cacheControl: CacheControl = builder.build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":194,"symbol":"call","kind":"function","lang":"kotlin","code":"@Test\n fun call() {\n val call: Call =\n object : Call {\n override fun request(): Request = TODO()\n\n override fun execute(): Response = TODO()\n\n override fun enqueue(responseCallback: Callback) = TODO()\n\n override fun cancel() = TODO()\n\n override fun isExecuted(): Boolean = TODO()\n\n override fun isCanceled(): Boolean = TODO()\n\n override fun timeout(): Timeout = TODO()\n\n override fun addEventListener(eventListener: EventListener) = TODO()\n\n override fun tag(type: KClass): T? = TODO()\n\n override fun tag(type: Class): T? = TODO()\n\n override fun tag(\n type: KClass,\n computeIfAbsent: () -> T,\n ): T = TODO()\n\n override fun tag(\n type: Class,\n computeIfAbsent: () -> T,\n ): T = TODO()\n\n override fun clone(): Call = TODO()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":198,"symbol":"request","kind":"function","lang":"kotlin","code":"override fun request(): Request = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":200,"symbol":"execute","kind":"function","lang":"kotlin","code":"override fun execute(): Response = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":202,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(responseCallback: Callback) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":204,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":206,"symbol":"isExecuted","kind":"function","lang":"kotlin","code":"override fun isExecuted(): Boolean = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":208,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"override fun isCanceled(): Boolean = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":210,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":212,"symbol":"addEventListener","kind":"function","lang":"kotlin","code":"override fun addEventListener(eventListener: EventListener) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":214,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(type: KClass): T? = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":216,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(type: Class): T? = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":218,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(\n type: KClass,\n computeIfAbsent: () -> T,\n ): T = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":223,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(\n type: Class,\n computeIfAbsent: () -> T,\n ): T = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":228,"symbol":"clone","kind":"function","lang":"kotlin","code":"override fun clone(): Call = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":232,"symbol":"callback","kind":"function","lang":"kotlin","code":"@Test\n fun callback() {\n val callback =\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) = TODO()\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) = TODO()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":236,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":241,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":248,"symbol":"certificatePinner","kind":"function","lang":"kotlin","code":"@Test\n fun certificatePinner() {\n val heldCertificate: HeldCertificate = HeldCertificate.Builder().build()\n val certificate: X509Certificate = heldCertificate.certificate\n val certificatePinner: CertificatePinner = CertificatePinner.Builder().build()\n val certificates: List = listOf()\n certificatePinner.check(\"\", listOf(certificate))\n certificatePinner.check(\"\", arrayOf(certificate, certificate).toList())\n val pin: String = CertificatePinner.pin(certificate)\n val default: CertificatePinner = CertificatePinner.DEFAULT\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":260,"symbol":"certificatePinnerBuilder","kind":"function","lang":"kotlin","code":"@Test\n fun certificatePinnerBuilder() {\n val builder: CertificatePinner.Builder = CertificatePinner.Builder()\n builder.add(\"\", \"pin1\", \"pin2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":266,"symbol":"challenge","kind":"function","lang":"kotlin","code":"@Test\n fun challenge() {\n var challenge = Challenge(\"\", mapOf(\"\" to \"\"))\n challenge = Challenge(\"\", \"\")\n val scheme: String = challenge.scheme\n val authParams: Map = challenge.authParams\n val realm: String? = challenge.realm\n val charset: Charset = challenge.charset\n val utf8: Challenge = challenge.withCharset(Charsets.UTF_8)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":277,"symbol":"cipherSuite","kind":"function","lang":"kotlin","code":"@Test\n fun cipherSuite() {\n var cipherSuite: CipherSuite = CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n cipherSuite = CipherSuite.forJavaName(\"\")\n val javaName: String = cipherSuite.javaName\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":284,"symbol":"connection","kind":"function","lang":"kotlin","code":"@Test\n fun connection() {\n val connection =\n object : Connection {\n override fun route(): Route = TODO()\n\n override fun socket(): Socket = TODO()\n\n override fun handshake(): Handshake? = TODO()\n\n override fun protocol(): Protocol = TODO()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":288,"symbol":"route","kind":"function","lang":"kotlin","code":"override fun route(): Route = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":290,"symbol":"socket","kind":"function","lang":"kotlin","code":"override fun socket(): Socket = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":292,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(): Handshake? = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":294,"symbol":"protocol","kind":"function","lang":"kotlin","code":"override fun protocol(): Protocol = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":298,"symbol":"connectionPool","kind":"function","lang":"kotlin","code":"@Test\n fun connectionPool() {\n var connectionPool = ConnectionPool()\n connectionPool = ConnectionPool(0, 0L, TimeUnit.SECONDS)\n val idleConnectionCount: Int = connectionPool.idleConnectionCount()\n val connectionCount: Int = connectionPool.connectionCount()\n connectionPool.evictAll()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":307,"symbol":"connectionSpec","kind":"function","lang":"kotlin","code":"@Test\n fun connectionSpec() {\n var connectionSpec: ConnectionSpec = ConnectionSpec.RESTRICTED_TLS\n connectionSpec = ConnectionSpec.MODERN_TLS\n connectionSpec = ConnectionSpec.COMPATIBLE_TLS\n connectionSpec = ConnectionSpec.CLEARTEXT\n val tlsVersions: List? = connectionSpec.tlsVersions\n val cipherSuites: List? = connectionSpec.cipherSuites\n val supportsTlsExtensions: Boolean = connectionSpec.supportsTlsExtensions\n val compatible: Boolean =\n connectionSpec.isCompatible(\n localhost().sslSocketFactory().createSocket() as SSLSocket,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":322,"symbol":"connectionSpecBuilder","kind":"function","lang":"kotlin","code":"@Test\n fun connectionSpecBuilder() {\n var builder = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)\n builder = builder.allEnabledCipherSuites()\n builder = builder.cipherSuites(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)\n builder = builder.cipherSuites(\"\", \"\")\n builder = builder.allEnabledTlsVersions()\n builder = builder.tlsVersions(TlsVersion.TLS_1_3)\n builder = builder.tlsVersions(\"\", \"\")\n val connectionSpec: ConnectionSpec = builder.build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":334,"symbol":"cookie","kind":"function","lang":"kotlin","code":"@Test\n fun cookie() {\n val cookie: Cookie = Cookie.Builder().build()\n val name: String = cookie.name\n val value: String = cookie.value\n val persistent: Boolean = cookie.persistent\n val expiresAt: Long = cookie.expiresAt\n val hostOnly: Boolean = cookie.hostOnly\n val domain: String = cookie.domain\n val path: String = cookie.path\n val httpOnly: Boolean = cookie.httpOnly\n val secure: Boolean = cookie.secure\n val matches: Boolean = cookie.matches(\"\".toHttpUrl())\n val parsedCookie: Cookie? = Cookie.parse(\"\".toHttpUrl(), \"\")\n val cookies: List = Cookie.parseAll(\"\".toHttpUrl(), headersOf())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":351,"symbol":"cookieBuilder","kind":"function","lang":"kotlin","code":"@Test\n fun cookieBuilder() {\n var builder: Cookie.Builder = Cookie.Builder()\n builder = builder.name(\"\")\n builder = builder.value(\"\")\n builder = builder.expiresAt(0L)\n builder = builder.domain(\"\")\n builder = builder.hostOnlyDomain(\"\")\n builder = builder.path(\"\")\n builder = builder.secure()\n builder = builder.httpOnly()\n builder = builder.sameSite(\"None\")\n val cookie: Cookie = builder.build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":366,"symbol":"cookieJar","kind":"function","lang":"kotlin","code":"@Test\n fun cookieJar() {\n val cookieJar =\n object : CookieJar {\n override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) = TODO()\n\n override fun loadForRequest(url: HttpUrl): List = TODO()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":370,"symbol":"saveFromResponse","kind":"function","lang":"kotlin","code":"override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":375,"symbol":"loadForRequest","kind":"function","lang":"kotlin","code":"override fun loadForRequest(url: HttpUrl): List = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":379,"symbol":"credentials","kind":"function","lang":"kotlin","code":"@Test\n fun credentials() {\n val basic: String = Credentials.basic(\"\", \"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":384,"symbol":"dispatcher","kind":"function","lang":"kotlin","code":"@Test\n fun dispatcher() {\n var dispatcher = Dispatcher()\n dispatcher = Dispatcher(Executors.newCachedThreadPool())\n val maxRequests: Int = dispatcher.maxRequests\n dispatcher.maxRequests = 0\n val maxRequestsPerHost: Int = dispatcher.maxRequestsPerHost\n dispatcher.maxRequestsPerHost = 0\n val executorService: ExecutorService = dispatcher.executorService\n dispatcher.idleCallback = Runnable { TODO() }\n val queuedCalls: List = dispatcher.queuedCalls()\n val runningCalls: List = dispatcher.runningCalls()\n val queuedCallsCount: Int = dispatcher.queuedCallsCount()\n val runningCallsCount: Int = dispatcher.runningCallsCount()\n dispatcher.cancelAll()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":401,"symbol":"dispatcherFromMockWebServer","kind":"function","lang":"kotlin","code":"@Test\n fun dispatcherFromMockWebServer() {\n val dispatcher =\n object : okhttp3.mockwebserver.Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse = TODO()\n\n override fun peek(): MockResponse = TODO()\n\n override fun shutdown() = TODO()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":405,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"override fun dispatch(request: RecordedRequest): MockResponse = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":407,"symbol":"peek","kind":"function","lang":"kotlin","code":"override fun peek(): MockResponse = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":409,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"override fun shutdown() = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":413,"symbol":"dns","kind":"function","lang":"kotlin","code":"@Test\n fun dns() {\n var dns: Dns = Dns { TODO() }\n\n val system: Dns = Dns.SYSTEM\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":420,"symbol":"eventListener","kind":"function","lang":"kotlin","code":"@Test\n fun eventListener() {\n val eventListener =\n object : EventListener() {\n override fun callStart(call: Call) = TODO()\n\n override fun dnsStart(\n call: Call,\n domainName: String,\n ) = TODO()\n\n override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List,\n ) = TODO()\n\n override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) = TODO()\n\n override fun secureConnectStart(call: Call) = TODO()\n\n override fun secureConnectEnd(\n call: Call,\n handshake: Handshake?,\n ) = TODO()\n\n override fun connectEnd(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ) = TODO()\n\n override fun connectFailed(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ioe: IOException,\n ) = TODO()\n\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":424,"symbol":"callStart","kind":"function","lang":"kotlin","code":"override fun callStart(call: Call) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":426,"symbol":"dnsStart","kind":"function","lang":"kotlin","code":"override fun dnsStart(\n call: Call,\n domainName: String,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":431,"symbol":"dnsEnd","kind":"function","lang":"kotlin","code":"override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":437,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":443,"symbol":"secureConnectStart","kind":"function","lang":"kotlin","code":"override fun secureConnectStart(call: Call) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":445,"symbol":"secureConnectEnd","kind":"function","lang":"kotlin","code":"override fun secureConnectEnd(\n call: Call,\n handshake: Handshake?,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":450,"symbol":"connectEnd","kind":"function","lang":"kotlin","code":"override fun connectEnd(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":457,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ioe: IOException,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":465,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/KotlinSourceModernTest.kt","line":470,"symbol":"connectionReleased","kind":"function","lang":"kotlin","code":"override fun connectionReleased(\n call: Call,\n connection: Connection,\n ) = TODO()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":30,"symbol":"LookupDnsCallTest","kind":"class","lang":"kotlin","code":"class LookupDnsCallTest {\n private val dns = BlockingFakeDns()\n private val taskFaker = TaskFaker()\n private val taskRunner: TaskRunner\n get() = taskFaker.taskRunner\n private val callback = RecordingCallback()\n\n @Test\n fun `happy path`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.enqueue(callback)\n\n val address1 = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))\n dns.put(listOf(address1))\n\n taskFaker.runTasks()\n\n assertThat(callback.events.take())\n .isEqualTo(\"onRecords(last=true, records=[lysine.dev/127.0.0.1])\")\n }\n\n @Test\n fun `delegate throws`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.enqueue(callback)\n\n dns.put(UnknownHostException(\"boom!\"))\n\n taskFaker.runTasks()\n\n assertThat(callback.events.take())\n .isEqualTo(\"onFailure(boom!)\")\n }\n\n @Test\n fun `call canceled before callback is enqueued`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.cancel()\n call.enqueue(callback)\n\n assertThat(callback.events.take())\n .isEqualTo(\"onFailure(canceled)\")\n }\n\n /** Most importantly, the cancel is delivered to t"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":37,"symbol":"`happy path`","kind":"function","lang":"kotlin","code":"@Test\n fun `happy path`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.enqueue(callback)\n\n val address1 = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))\n dns.put(listOf(address1))\n\n taskFaker.runTasks()\n\n assertThat(callback.events.take())\n .isEqualTo(\"onRecords(last=true, records=[lysine.dev/127.0.0.1])\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":51,"symbol":"`delegate throws`","kind":"function","lang":"kotlin","code":"@Test\n fun `delegate throws`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.enqueue(callback)\n\n dns.put(UnknownHostException(\"boom!\"))\n\n taskFaker.runTasks()\n\n assertThat(callback.events.take())\n .isEqualTo(\"onFailure(boom!)\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":64,"symbol":"`call canceled before callback is enqueued`","kind":"function","lang":"kotlin","code":"@Test\n fun `call canceled before callback is enqueued`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.cancel()\n call.enqueue(callback)\n\n assertThat(callback.events.take())\n .isEqualTo(\"onFailure(canceled)\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":75,"symbol":"`call canceled before results are returned`","kind":"function","lang":"kotlin","doc":"Most importantly, the cancel is delivered to the [Dns.Callback] immediately.","code":"@Test\n fun `call canceled before results are returned`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.enqueue(callback)\n\n call.cancel()\n\n assertThat(callback.events.take())\n .isEqualTo(\"onFailure(canceled)\")\n assertThat(callback.events.poll())\n .isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":88,"symbol":"`call canceled after results are returned`","kind":"function","lang":"kotlin","code":"@Test\n fun `call canceled after results are returned`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.enqueue(callback)\n\n val address1 = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))\n dns.put(listOf(address1))\n taskFaker.runTasks()\n\n call.cancel()\n\n assertThat(callback.events.take())\n .isEqualTo(\"onRecords(last=true, records=[lysine.dev/127.0.0.1])\")\n assertThat(callback.events.poll())\n .isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":105,"symbol":"`results after cancel are not delivered`","kind":"function","lang":"kotlin","code":"@Test\n fun `results after cancel are not delivered`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.enqueue(callback)\n\n call.cancel()\n\n val address1 = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))\n dns.put(listOf(address1))\n taskFaker.runTasks()\n\n assertThat(callback.events.take())\n .isEqualTo(\"onFailure(canceled)\")\n assertThat(callback.events.poll())\n .isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":122,"symbol":"`exception after cancel is not delivered`","kind":"function","lang":"kotlin","code":"@Test\n fun `exception after cancel is not delivered`() {\n val call = LookupDnsCall(taskRunner, dns, Dns.Request(\"lysine.dev\"))\n call.enqueue(callback)\n\n call.cancel()\n\n dns.put(UnknownHostException(\"boom!\"))\n taskFaker.runTasks()\n\n assertThat(callback.events.take())\n .isEqualTo(\"onFailure(canceled)\")\n assertThat(callback.events.poll())\n .isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":138,"symbol":"BlockingFakeDns","kind":"class","lang":"kotlin","code":"class BlockingFakeDns : Dns {\n val results = LinkedBlockingDeque>>()\n\n override fun lookup(hostname: String): List = results.take().getOrThrow()\n\n fun put(inetAddresses: List) {\n results.put(Result.success(inetAddresses))\n }\n\n fun put(e: UnknownHostException) {\n results.put(Result.failure(e))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":141,"symbol":"lookup","kind":"function","lang":"kotlin","code":"override fun lookup(hostname: String): List = results.take().getOrThrow()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":143,"symbol":"put","kind":"function","lang":"kotlin","code":"fun put(inetAddresses: List) {\n results.put(Result.success(inetAddresses))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":147,"symbol":"put","kind":"function","lang":"kotlin","code":"fun put(e: UnknownHostException) {\n results.put(Result.failure(e))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":152,"symbol":"RecordingCallback","kind":"class","lang":"kotlin","code":"class RecordingCallback : Dns.Callback {\n val events = LinkedBlockingDeque()\n\n override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n events.put(\"onRecords(last=$last, records=$records)\")\n }\n\n override fun onFailure(\n call: Dns.Call,\n e: IOException,\n ) {\n events.put(\"onFailure(${e.message})\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":155,"symbol":"onRecords","kind":"function","lang":"kotlin","code":"override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n events.put(\"onRecords(last=$last, records=$records)\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LookupDnsCallTest.kt","line":163,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Dns.Call,\n e: IOException,\n ) {\n events.put(\"onFailure(${e.message})\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LoomTest.kt","line":31,"symbol":"LoomTest","kind":"class","lang":"kotlin","code":"class LoomTest {\n @JvmField\n @RegisterExtension\n val platform = PlatformRule()\n\n @JvmField\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private lateinit var client: OkHttpClient\n\n @BeforeEach\n fun setUp() {\n platform.assumeLoom()\n\n client =\n clientTestRule\n .newClientBuilder()\n .dispatcher(Dispatcher(newVirtualThreadPerTaskExecutor()))\n .build()\n }\n\n private fun newVirtualThreadPerTaskExecutor(): ExecutorService =\n Executors::class.java.getMethod(\"newVirtualThreadPerTaskExecutor\").invoke(null) as ExecutorService\n\n @Test\n fun testRequest() {\n server.enqueue(MockResponse())\n\n val request = Request(server.url(\"/\"))\n\n client.newCall(request).execute().use {\n assertThat(it.code).isEqualTo(200)\n }\n }\n\n @Test\n fun testIfSupported() {\n assertThat(platform.isLoom()).isTrue()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LoomTest.kt","line":45,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeLoom()\n\n client =\n clientTestRule\n .newClientBuilder()\n .dispatcher(Dispatcher(newVirtualThreadPerTaskExecutor()))\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LoomTest.kt","line":56,"symbol":"newVirtualThreadPerTaskExecutor","kind":"function","lang":"kotlin","code":"private fun newVirtualThreadPerTaskExecutor(): ExecutorService =\n Executors::class.java.getMethod(\"newVirtualThreadPerTaskExecutor\").invoke(null) as ExecutorService"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LoomTest.kt","line":59,"symbol":"testRequest","kind":"function","lang":"kotlin","code":"@Test\n fun testRequest() {\n server.enqueue(MockResponse())\n\n val request = Request(server.url(\"/\"))\n\n client.newCall(request).execute().use {\n assertThat(it.code).isEqualTo(200)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/LoomTest.kt","line":70,"symbol":"testIfSupported","kind":"function","lang":"kotlin","code":"@Test\n fun testIfSupported() {\n assertThat(platform.isLoom()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeGetTest.kt","line":22,"symbol":"MediaTypeGetTest","kind":"class","lang":"kotlin","code":"open class MediaTypeGetTest : MediaTypeTest() {\n override fun parse(string: String): MediaType = string.toMediaType()\n\n override fun assertInvalid(\n string: String,\n exceptionMessage: String?,\n ) {\n val e =\n assertFailsWith {\n parse(string)\n }\n assertEquals(exceptionMessage, e.message)\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeGetTest.kt","line":23,"symbol":"parse","kind":"function","lang":"kotlin","code":"override fun parse(string: String): MediaType = string.toMediaType()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeGetTest.kt","line":25,"symbol":"assertInvalid","kind":"function","lang":"kotlin","code":"override fun assertInvalid(\n string: String,\n exceptionMessage: String?,\n ) {\n val e =\n assertFailsWith {\n parse(string)\n }\n assertEquals(exceptionMessage, e.message)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":25,"symbol":"MediaTypeJvmTest","kind":"class","lang":"kotlin","code":"class MediaTypeJvmTest : MediaTypeGetTest() {\n override fun MediaType.charsetName(): String? = this.charset()?.name()\n\n @Test fun testCharsetNameIsDoubleQuotedAndSingleQuotedAndroid() {\n val mediaType = \"text/plain;charset=\\\"'utf-8'\\\"\".toMediaType()\n if (isAndroid) {\n // Charset.forName(\"'utf-8'\") == UTF-8\n assertEquals(\"UTF-8\", mediaType.charsetName())\n } else {\n assertNull(mediaType.charset())\n }\n }\n\n @Test fun testDefaultCharset() {\n val noCharset = parse(\"text/plain\")\n assertEquals(\n \"UTF-8\",\n noCharset.charset(Charsets.UTF_8)!!.name(),\n )\n assertEquals(\n \"US-ASCII\",\n noCharset.charset(Charsets.US_ASCII)!!.name(),\n )\n val charset = parse(\"text/plain; charset=iso-8859-1\")\n assertEquals(\n \"ISO-8859-1\",\n charset.charset(Charsets.UTF_8)!!.name(),\n )\n assertEquals(\n \"ISO-8859-1\",\n charset.charset(Charsets.US_ASCII)!!.name(),\n )\n }\n\n @Test fun testTurkishDotlessIWithEnUs() {\n withLocale(Locale(\"en\", \"US\")) {\n val mediaType = parse(\"IMAGE/JPEG\")\n assertEquals(\"image\", mediaType.type)\n assertEquals(\"jpeg\", mediaType.subtype)\n }\n }\n\n @Test fun testTurkishDotlessI"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":26,"symbol":"charsetName","kind":"function","lang":"kotlin","code":"override fun MediaType.charsetName(): String? = this.charset()?.name()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":28,"symbol":"testCharsetNameIsDoubleQuotedAndSingleQuotedAndroid","kind":"function","lang":"kotlin","code":"@Test fun testCharsetNameIsDoubleQuotedAndSingleQuotedAndroid() {\n val mediaType = \"text/plain;charset=\\\"'utf-8'\\\"\".toMediaType()\n if (isAndroid) {\n // Charset.forName(\"'utf-8'\") == UTF-8\n assertEquals(\"UTF-8\", mediaType.charsetName())\n } else {\n assertNull(mediaType.charset())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":38,"symbol":"testDefaultCharset","kind":"function","lang":"kotlin","code":"@Test fun testDefaultCharset() {\n val noCharset = parse(\"text/plain\")\n assertEquals(\n \"UTF-8\",\n noCharset.charset(Charsets.UTF_8)!!.name(),\n )\n assertEquals(\n \"US-ASCII\",\n noCharset.charset(Charsets.US_ASCII)!!.name(),\n )\n val charset = parse(\"text/plain; charset=iso-8859-1\")\n assertEquals(\n \"ISO-8859-1\",\n charset.charset(Charsets.UTF_8)!!.name(),\n )\n assertEquals(\n \"ISO-8859-1\",\n charset.charset(Charsets.US_ASCII)!!.name(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":59,"symbol":"testTurkishDotlessIWithEnUs","kind":"function","lang":"kotlin","code":"@Test fun testTurkishDotlessIWithEnUs() {\n withLocale(Locale(\"en\", \"US\")) {\n val mediaType = parse(\"IMAGE/JPEG\")\n assertEquals(\"image\", mediaType.type)\n assertEquals(\"jpeg\", mediaType.subtype)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":67,"symbol":"testTurkishDotlessIWithTrTr","kind":"function","lang":"kotlin","code":"@Test fun testTurkishDotlessIWithTrTr() {\n withLocale(Locale(\"tr\", \"TR\")) {\n val mediaType = parse(\"IMAGE/JPEG\")\n assertEquals(\"image\", mediaType.type)\n assertEquals(\"jpeg\", mediaType.subtype)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":75,"symbol":"withLocale","kind":"function","lang":"kotlin","code":"private fun withLocale(\n locale: Locale,\n block: () -> T,\n ): T {\n val previous = Locale.getDefault()\n try {\n Locale.setDefault(locale)\n return block()\n } finally {\n Locale.setDefault(previous)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":88,"symbol":"testIllegalCharsetName","kind":"function","lang":"kotlin","code":"@Test fun testIllegalCharsetName() {\n val mediaType = parse(\"text/plain; charset=\\\"!@#$%^&*()\\\"\")\n assertNull(mediaType.charsetName())\n }\n\n @Test fun testUnsupportedCharset() {\n val mediaType = parse(\"text/plain; charset=utf-wtf\")\n assertNull(mediaType.charsetName())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":98,"symbol":"testCharsetNameIsDoubleQuotedAndSingleQuoted","kind":"function","lang":"kotlin","code":"@Test fun testCharsetNameIsDoubleQuotedAndSingleQuoted() {\n val mediaType = parse(\"text/plain;charset=\\\"'utf-8'\\\"\")\n assertNull(mediaType.charsetName())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeJvmTest.kt","line":103,"symbol":"testCharsetNameIsDoubleQuotedSingleQuote","kind":"function","lang":"kotlin","code":"@Test fun testCharsetNameIsDoubleQuotedSingleQuote() {\n val mediaType = parse(\"text/plain;charset=\\\"'\\\"\")\n assertNull(mediaType.charsetName())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeTest.kt","line":30,"symbol":"MediaTypeTest","kind":"class","lang":"kotlin","doc":"Test MediaType API and parsing. This test includes tests from [Guava's](https://code.google.com/p/guava-libraries/) MediaTypeTest.","code":"open class MediaTypeTest {\n open fun MediaType.charsetName(): String? = parameter(\"charset\")?.uppercase()\n\n protected open fun parse(string: String): MediaType = string.toMediaTypeOrNull()!!\n\n protected open fun assertInvalid(\n string: String,\n exceptionMessage: String?,\n ) {\n assertNull(string.toMediaTypeOrNull(), exceptionMessage)\n }\n\n @Test fun testParse() {\n val mediaType = parse(\"text/plain;boundary=foo;charset=utf-8\")\n assertEquals(\"text\", mediaType.type)\n assertEquals(\"plain\", mediaType.subtype)\n assertEquals(\"UTF-8\", mediaType.charsetName())\n assertEquals(\"text/plain;boundary=foo;charset=utf-8\", mediaType.toString())\n assertEquals(mediaType, parse(\"text/plain;boundary=foo;charset=utf-8\"))\n assertEquals(\n mediaType.hashCode(),\n parse(\"text/plain;boundary=foo;charset=utf-8\").hashCode(),\n )\n }\n\n @Test fun testValidParse() {\n assertMediaType(\"text/plain\")\n assertMediaType(\"application/atom+xml; charset=utf-8\")\n assertMediaType(\"application/atom+xml; a=1; a=2; b=3\")\n assertMediaType(\"image/gif; foo=bar\")\n assertMediaType(\"text/plain; a=1\")\n assertMediaType(\"text/plain; a=1; a=2; b=3\")\n assertMediaType(\"text/"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeTest.kt","line":31,"symbol":"charsetName","kind":"function","lang":"kotlin","code":"open fun MediaType.charsetName(): String? = parameter(\"charset\")?.uppercase()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeTest.kt","line":33,"symbol":"parse","kind":"function","lang":"kotlin","code":"protected open fun parse(string: String): MediaType = string.toMediaTypeOrNull()!!"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeTest.kt","line":35,"symbol":"assertInvalid","kind":"function","lang":"kotlin","code":"protected open fun assertInvalid(\n string: String,\n exceptionMessage: String?,\n ) {\n assertNull(string.toMediaTypeOrNull(), exceptionMessage)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeTest.kt","line":42,"symbol":"testParse","kind":"function","lang":"kotlin","code":"@Test fun testParse() {\n val mediaType = parse(\"text/plain;boundary=foo;charset=utf-8\")\n assertEquals(\"text\", mediaType.type)\n assertEquals(\"plain\", mediaType.subtype)\n assertEquals(\"UTF-8\", mediaType.charsetName())\n assertEquals(\"text/plain;boundary=foo;charset=utf-8\", mediaType.toString())\n assertEquals(mediaType, parse(\"text/plain;boundary=foo;charset=utf-8\"))\n assertEquals(\n mediaType.hashCode(),\n parse(\"text/plain;boundary=foo;charset=utf-8\").hashCode(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeTest.kt","line":55,"symbol":"testValidParse","kind":"function","lang":"kotlin","code":"@Test fun testValidParse() {\n assertMediaType(\"text/plain\")\n assertMediaType(\"application/atom+xml; charset=utf-8\")\n assertMediaType(\"application/atom+xml; a=1; a=2; b=3\")\n assertMediaType(\"image/gif; foo=bar\")\n assertMediaType(\"text/plain; a=1\")\n assertMediaType(\"text/plain; a=1; a=2; b=3\")\n assertMediaType(\"text/plain; charset=utf-16\")\n assertMediaType(\"text/plain; \\t \\n \\r a=b\")\n assertMediaType(\"text/plain;\")\n assertMediaType(\"text/plain; \")\n assertMediaType(\"text/plain; a=1;\")\n assertMediaType(\"text/plain; a=1; \")\n assertMediaType(\"text/plain; a=1;; b=2\")\n assertMediaType(\"text/plain;;\")\n assertMediaType(\"text/plain; ;\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MediaTypeTest.kt","line":73,"symbol":"testInvalidParse","kind":"function","lang":"kotlin","code":"@Test fun testInvalidParse() {\n assertInvalid(\"\", \"No subtype found for: \\\"\\\"\")\n assertInvalid(\"/\", \"No subtype found for: \\\"/\\\"\")\n assertInvalid(\"text\", \"No subtype found for: \\\"text\\\"\")\n assertInvalid(\"text/\", \"No subtype found for: \\\"text/\\\"\")\n assertInvalid(\"te {\n MultipartBody.Builder().build()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Multipart body must have at least one part.\")\n }\n }\n\n @Test\n fun singlePart() {\n val expected =\n \"\"\"\n |--123\n |\n |Hello, World!\n |--123--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"123\")\n .addPart(\"Hello, World!\".toRequestBody(null))\n .build()\n assertThat(body.boundary).isEqualTo(\"123\")\n assertThat(body.type).isEqualTo(MultipartBody.MIXED)\n assertThat(body.contentType().toString())\n .isEqualTo(\"multipart/mixed; boundary=123\")\n assertThat(body.parts.size).isEqualTo(1)\n assertThat(body.contentLength()).isEqualTo(33L)\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(body.contentLength()).isEqualTo(buffer.size)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }\n\n @Test\n fun threeParts() {\n val expected =\n \"\"\"\n |--123\n |\n |Quick\n |--123\n |\n |Brown\n |--123\n |\n |F"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":36,"symbol":"onePartRequired","kind":"function","lang":"kotlin","code":"@Test\n fun onePartRequired() {\n assertFailsWith {\n MultipartBody.Builder().build()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Multipart body must have at least one part.\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":46,"symbol":"singlePart","kind":"function","lang":"kotlin","code":"@Test\n fun singlePart() {\n val expected =\n \"\"\"\n |--123\n |\n |Hello, World!\n |--123--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"123\")\n .addPart(\"Hello, World!\".toRequestBody(null))\n .build()\n assertThat(body.boundary).isEqualTo(\"123\")\n assertThat(body.type).isEqualTo(MultipartBody.MIXED)\n assertThat(body.contentType().toString())\n .isEqualTo(\"multipart/mixed; boundary=123\")\n assertThat(body.parts.size).isEqualTo(1)\n assertThat(body.contentLength()).isEqualTo(33L)\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(body.contentLength()).isEqualTo(buffer.size)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":73,"symbol":"threeParts","kind":"function","lang":"kotlin","code":"@Test\n fun threeParts() {\n val expected =\n \"\"\"\n |--123\n |\n |Quick\n |--123\n |\n |Brown\n |--123\n |\n |Fox\n |--123--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"123\")\n .addPart(\"Quick\".toRequestBody(null))\n .addPart(\"Brown\".toRequestBody(null))\n .addPart(\"Fox\".toRequestBody(null))\n .build()\n assertThat(body.boundary).isEqualTo(\"123\")\n assertThat(body.type).isEqualTo(MultipartBody.MIXED)\n assertThat(body.contentType().toString())\n .isEqualTo(\"multipart/mixed; boundary=123\")\n assertThat(body.parts.size).isEqualTo(3)\n assertThat(body.contentLength()).isEqualTo(55L)\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(body.contentLength()).isEqualTo(buffer.size)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":108,"symbol":"fieldAndTwoFiles","kind":"function","lang":"kotlin","code":"@Test\n fun fieldAndTwoFiles() {\n val expected =\n \"\"\"\n |--AaB03x\n |Content-Disposition: form-data; name=\"submit-name\"\n |\n |Larry\n |--AaB03x\n |Content-Disposition: form-data; name=\"files\"\n |Content-Type: multipart/mixed; boundary=BbC04y\n |\n |--BbC04y\n |Content-Disposition: file; filename=\"file1.txt\"\n |Content-Type: text/plain; charset=utf-8\n |\n |... contents of file1.txt ...\n |--BbC04y\n |Content-Disposition: file; filename=\"file2.gif\"\n |Content-Transfer-Encoding: binary\n |Content-Type: image/gif\n |\n |... contents of file2.gif ...\n |--BbC04y--\n |\n |--AaB03x--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"AaB03x\")\n .setType(MultipartBody.FORM)\n .addFormDataPart(\"submit-name\", \"Larry\")\n .addFormDataPart(\n \"files\",\n null,\n MultipartBody\n .Builder(\"BbC04y\")\n .addPart(\n headersOf(\"Content-Disposition\", \"file; filename=\\\"file1.txt\\\"\"),\n \"... contents of file1.txt ...\".toRequestBody(\"text/plain\".toMediaType()),\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":174,"symbol":"stringEscapingIsWeird","kind":"function","lang":"kotlin","code":"@Test\n fun stringEscapingIsWeird() {\n val expected =\n \"\"\"\n |--AaB03x\n |Content-Disposition: form-data; name=\"field with spaces\"; filename=\"filename with spaces.txt\"\n |Content-Type: text/plain; charset=utf-8\n |\n |okay\n |--AaB03x\n |Content-Disposition: form-data; name=\"field with %22\"\n |\n |\"\n |--AaB03x\n |Content-Disposition: form-data; name=\"field with %22\"\n |\n |%22\n |--AaB03x\n |Content-Disposition: form-data; name=\"field with ~\"\n |\n |Alpha\n |--AaB03x--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"AaB03x\")\n .setType(MultipartBody.FORM)\n .addFormDataPart(\n \"field with spaces\",\n \"filename with spaces.txt\",\n \"okay\".toRequestBody(\"text/plain; charset=utf-8\".toMediaType()),\n ).addFormDataPart(\"field with \\\"\", \"\\\"\")\n .addFormDataPart(\"field with %22\", \"%22\")\n .addFormDataPart(\"field with \\u007e\", \"Alpha\")\n .build()\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":215,"symbol":"streamingPartHasNoLength","kind":"function","lang":"kotlin","code":"@Test\n fun streamingPartHasNoLength() {\n class StreamingBody(\n private val body: String,\n ) : RequestBody() {\n override fun contentType(): MediaType? = null\n\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(body)\n }\n }\n\n val expected =\n \"\"\"\n |--123\n |\n |Quick\n |--123\n |\n |Brown\n |--123\n |\n |Fox\n |--123--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"123\")\n .addPart(\"Quick\".toRequestBody(null))\n .addPart(StreamingBody(\"Brown\"))\n .addPart(\"Fox\".toRequestBody(null))\n .build()\n assertThat(body.boundary).isEqualTo(\"123\")\n assertThat(body.type).isEqualTo(MultipartBody.MIXED)\n assertThat(body.contentType().toString())\n .isEqualTo(\"multipart/mixed; boundary=123\")\n assertThat(body.parts.size).isEqualTo(3)\n assertThat(body.contentLength()).isEqualTo(-1)\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":217,"symbol":"StreamingBody","kind":"class","lang":"kotlin","code":"class StreamingBody(\n private val body: String,\n ) : RequestBody() {\n override fun contentType(): MediaType? = null\n\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(body)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":220,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":222,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(body)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":260,"symbol":"partThatClosesTheSink","kind":"function","lang":"kotlin","code":"@Test\n fun partThatClosesTheSink() {\n class ClosingBody(\n private val body: String,\n ) : RequestBody() {\n override fun contentType(): MediaType? = null\n\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(body)\n sink.close()\n }\n }\n\n val expected =\n \"\"\"\n |--123\n |\n |hello\n |--123\n |\n |world\n |--123--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"123\")\n .addPart(ClosingBody(\"hello\"))\n .addPart(\"world\".toRequestBody(null))\n .build()\n val buffer = Buffer()\n // Don't write to Buffer directly: Buffer.close() is a no-op. Wrap it so close()\n // actually closes the sink, like a real HTTP write.\n val sink = object : ForwardingSink(buffer) {}.buffer()\n body.writeTo(sink)\n sink.close()\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":262,"symbol":"ClosingBody","kind":"class","lang":"kotlin","code":"class ClosingBody(\n private val body: String,\n ) : RequestBody() {\n override fun contentType(): MediaType? = null\n\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(body)\n sink.close()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":265,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":267,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(body)\n sink.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":300,"symbol":"gzippedParts","kind":"function","lang":"kotlin","code":"@Test\n fun gzippedParts() {\n val body =\n MultipartBody\n .Builder(\"123\")\n .addPart(GzipRequestBody(\"part1\".toRequestBody(null)))\n .addPart(GzipRequestBody(\"part2\".toRequestBody(null)))\n .build()\n\n val expected = Buffer()\n expected.writeUtf8(\"--123\\r\\n\\r\\n\")\n GzipRequestBody(\"part1\".toRequestBody(null)).writeTo(expected)\n expected.writeUtf8(\"\\r\\n--123\\r\\n\\r\\n\")\n GzipRequestBody(\"part2\".toRequestBody(null)).writeTo(expected)\n expected.writeUtf8(\"\\r\\n--123--\\r\\n\")\n\n val buffer = Buffer()\n // Don't write to Buffer directly: Buffer.close() is a no-op. Wrap it so close()\n // actually closes the sink, like a real HTTP write.\n val sink = object : ForwardingSink(buffer) {}.buffer()\n body.writeTo(sink)\n sink.close()\n assertThat(buffer.readUtf8()).isEqualTo(expected.readUtf8())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":325,"symbol":"contentTypeHeaderIsForbidden","kind":"function","lang":"kotlin","code":"@Test\n fun contentTypeHeaderIsForbidden() {\n val multipart = MultipartBody.Builder()\n assertFailsWith {\n multipart.addPart(\n headersOf(\"Content-Type\", \"text/plain\"),\n \"Hello, World!\".toRequestBody(null),\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":336,"symbol":"contentLengthHeaderIsForbidden","kind":"function","lang":"kotlin","code":"@Test\n fun contentLengthHeaderIsForbidden() {\n val multipart = MultipartBody.Builder()\n assertFailsWith {\n multipart.addPart(\n headersOf(\"Content-Length\", \"13\"),\n \"Hello, World!\".toRequestBody(null),\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":347,"symbol":"partAccessors","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun partAccessors() {\n val body =\n MultipartBody\n .Builder()\n .addPart(headersOf(\"Foo\", \"Bar\"), \"Baz\".toRequestBody(null))\n .build()\n assertThat(body.parts.size).isEqualTo(1)\n val part1Buffer = Buffer()\n val part1 = body.part(0)\n part1.body.writeTo(part1Buffer)\n assertThat(part1.headers).isEqualTo(headersOf(\"Foo\", \"Bar\"))\n assertThat(part1Buffer.readUtf8()).isEqualTo(\"Baz\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":363,"symbol":"nonAsciiFilename","kind":"function","lang":"kotlin","code":"@Test\n fun nonAsciiFilename() {\n val expected =\n \"\"\"\n |--AaB03x\n |Content-Disposition: form-data; name=\"attachment\"; filename=\"resumé.pdf\"\n |Content-Type: application/pdf; charset=utf-8\n |\n |Jesse’s Resumé\n |--AaB03x--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"AaB03x\")\n .setType(MultipartBody.FORM)\n .addFormDataPart(\n \"attachment\",\n \"resumé.pdf\",\n \"Jesse’s Resumé\".toRequestBody(\"application/pdf\".toMediaTypeOrNull()),\n ).build()\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":389,"symbol":"writeTwice","kind":"function","lang":"kotlin","code":"@Test\n fun writeTwice() {\n val expected =\n \"\"\"\n |--123\n |\n |Hello, World!\n |--123--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"123\")\n .addPart(\"Hello, World!\".toRequestBody(null))\n .build()\n\n assertThat(body.isOneShot()).isEqualTo(false)\n\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(body.contentLength()).isEqualTo(buffer.size)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n\n val buffer2 = Buffer()\n body.writeTo(buffer2)\n assertThat(body.contentLength()).isEqualTo(buffer2.size)\n assertThat(buffer2.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":418,"symbol":"writeTwiceWithOneShot","kind":"function","lang":"kotlin","code":"@Test\n fun writeTwiceWithOneShot() {\n val expected =\n \"\"\"\n |--123\n |\n |Hello, World!\n |--123--\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\")\n val body =\n MultipartBody\n .Builder(\"123\")\n .addPart(\"Hello, World!\".toOneShotRequestBody())\n .build()\n\n assertThat(body.isOneShot()).isEqualTo(true)\n\n val buffer = Buffer()\n body.writeTo(buffer)\n assertThat(body.contentLength()).isEqualTo(buffer.size)\n assertThat(buffer.readUtf8()).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":442,"symbol":"toOneShotRequestBody","kind":"function","lang":"kotlin","code":"fun String.toOneShotRequestBody(): RequestBody =\n object : RequestBody() {\n override fun contentType() = null\n\n override fun isOneShot(): Boolean = true\n\n override fun contentLength() = this@toOneShotRequestBody.utf8Size()\n\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(this@toOneShotRequestBody)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":444,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":446,"symbol":"isOneShot","kind":"function","lang":"kotlin","code":"override fun isOneShot(): Boolean = true"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":448,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = this@toOneShotRequestBody.utf8Size()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartBodyTest.kt","line":450,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(this@toOneShotRequestBody)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":36,"symbol":"MultipartReaderTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass MultipartReaderTest {\n @Test fun `parse multipart`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |Content-Type: text/plain; charset=utf-8\n |Content-ID: abc\n |\n |abcd\n |efgh\n |--simple boundary\n |Content-Type: text/plain; charset=utf-8\n |Content-ID: ijk\n |\n |ijkl\n |mnop\n |\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n assertThat(parts.boundary).isEqualTo(\"simple boundary\")\n\n val partAbc = parts.nextPart()!!\n assertThat(partAbc.headers).isEqualTo(\n headersOf(\n \"Content-Type\",\n \"text/plain; charset=utf-8\",\n \"Content-ID\",\n \"abc\",\n ),\n )\n assertThat(partAbc.body.readUtf8()).isEqualTo(\"abcd\\r\\nefgh\")\n\n val partIjk = parts.nextPart()!!\n assertThat(partIjk.headers).isEqualTo(\n headersOf(\n \"Content-Type\",\n \"text/plain; charset=utf-8\",\n \"Content-ID\",\n \"ijk\",\n ),\n )\n assertThat(partIjk.body.readUtf8()).isEqualTo(\"ijkl\\r\\nmnop\\r\\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":38,"symbol":"`parse multipart`","kind":"function","lang":"kotlin","code":"@Test fun `parse multipart`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |Content-Type: text/plain; charset=utf-8\n |Content-ID: abc\n |\n |abcd\n |efgh\n |--simple boundary\n |Content-Type: text/plain; charset=utf-8\n |Content-ID: ijk\n |\n |ijkl\n |mnop\n |\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n assertThat(parts.boundary).isEqualTo(\"simple boundary\")\n\n val partAbc = parts.nextPart()!!\n assertThat(partAbc.headers).isEqualTo(\n headersOf(\n \"Content-Type\",\n \"text/plain; charset=utf-8\",\n \"Content-ID\",\n \"abc\",\n ),\n )\n assertThat(partAbc.body.readUtf8()).isEqualTo(\"abcd\\r\\nefgh\")\n\n val partIjk = parts.nextPart()!!\n assertThat(partIjk.headers).isEqualTo(\n headersOf(\n \"Content-Type\",\n \"text/plain; charset=utf-8\",\n \"Content-ID\",\n \"ijk\",\n ),\n )\n assertThat(partIjk.body.readUtf8()).isEqualTo(\"ijkl\\r\\nmnop\\r\\n\")\n\n assertThat(parts.nextPart()).isNull()\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":90,"symbol":"`parse from response body`","kind":"function","lang":"kotlin","code":"@Test fun `parse from response body`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val responseBody =\n multipart.toResponseBody(\n \"application/multipart; boundary=\\\"simple boundary\\\"\".toMediaType(),\n )\n\n val parts = MultipartReader(responseBody)\n assertThat(parts.boundary).isEqualTo(\"simple boundary\")\n\n val part = parts.nextPart()!!\n assertThat(part.body.readUtf8()).isEqualTo(\"abcd\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":114,"symbol":"`truncated multipart`","kind":"function","lang":"kotlin","code":"@Test fun `truncated multipart`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |efgh\n |\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val part = parts.nextPart()!!\n assertFailsWith {\n part.body.readUtf8()\n }\n\n assertFailsWith {\n assertThat(parts.nextPart()).isNull()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":141,"symbol":"`malformed headers`","kind":"function","lang":"kotlin","code":"@Test fun `malformed headers`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |abcd\n |\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n assertFailsWith {\n parts.nextPart()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":161,"symbol":"`lf instead of crlf boundary is not honored`","kind":"function","lang":"kotlin","code":"@Test fun `lf instead of crlf boundary is not honored`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundary\n |\n |efgh\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n .replace(Regex(\"(?m)abcd\\r\\n\"), \"abcd\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val part = parts.nextPart()!!\n assertThat(part.body.readUtf8()).isEqualTo(\"abcd\\n--simple boundary\\r\\n\\r\\nefgh\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":187,"symbol":"`partial boundary is not honored`","kind":"function","lang":"kotlin","code":"@Test fun `partial boundary is not honored`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundar\n |\n |efgh\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val part = parts.nextPart()!!\n assertThat(part.body.readUtf8()).isEqualTo(\"abcd\\r\\n--simple boundar\\r\\n\\r\\nefgh\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":212,"symbol":"`do not need to read entire part`","kind":"function","lang":"kotlin","code":"@Test fun `do not need to read entire part`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |efgh\n |ijkl\n |--simple boundary\n |\n |mnop\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n parts.nextPart()!!\n val partMno = parts.nextPart()!!\n assertThat(partMno.body.readUtf8()).isEqualTo(\"mnop\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":240,"symbol":"`cannot read part after calling nextPart`","kind":"function","lang":"kotlin","code":"@Test fun `cannot read part after calling nextPart`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |efgh\n |ijkl\n |--simple boundary\n |\n |mnop\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val partAbc = parts.nextPart()!!\n val partMno = parts.nextPart()!!\n\n assertFailsWith {\n partAbc.body.request(20)\n }.also { expected ->\n assertThat(expected).hasMessage(\"closed\")\n }\n\n assertThat(partMno.body.readUtf8()).isEqualTo(\"mnop\")\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":274,"symbol":"`cannot read part after calling close`","kind":"function","lang":"kotlin","code":"@Test fun `cannot read part after calling close`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val part = parts.nextPart()!!\n parts.close()\n\n assertFailsWith {\n part.body.request(10)\n }.also { expected ->\n assertThat(expected).hasMessage(\"closed\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":300,"symbol":"`cannot call nextPart after calling close`","kind":"function","lang":"kotlin","code":"@Test fun `cannot call nextPart after calling close`() {\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer(),\n )\n\n parts.close()\n\n assertFailsWith {\n parts.nextPart()\n }.also { expected ->\n assertThat(expected).hasMessage(\"closed\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":316,"symbol":"`zero parts`","kind":"function","lang":"kotlin","code":"@Test fun `zero parts`() {\n val multipart =\n \"\"\"\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n assertFailsWith {\n parts.nextPart()\n }.also { expected ->\n assertThat(expected).hasMessage(\"expected at least 1 part\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":336,"symbol":"`skip preamble`","kind":"function","lang":"kotlin","code":"@Test fun `skip preamble`() {\n val multipart =\n \"\"\"\n |this is the preamble! it is invisible to application code\n |\n |--simple boundary\n |\n |abcd\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val part = parts.nextPart()!!\n assertThat(part.headers).isEqualTo(headersOf())\n assertThat(part.body.readUtf8()).isEqualTo(\"abcd\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":361,"symbol":"`skip epilogue`","kind":"function","lang":"kotlin","code":"@Test fun `skip epilogue`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundary--\n |this is the epilogue! it is also invisible to application code\n |\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val part = parts.nextPart()!!\n assertThat(part.headers).isEqualTo(headersOf())\n assertThat(part.body.readUtf8()).isEqualTo(\"abcd\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":386,"symbol":"`skip whitespace after boundary`","kind":"function","lang":"kotlin","code":"@Test fun `skip whitespace after boundary`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(Regex(\"(?m)simple boundary$\"), \"simple boundary \\t \\t\")\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val part = parts.nextPart()!!\n assertThat(part.headers).isEqualTo(headersOf())\n assertThat(part.body.readUtf8()).isEqualTo(\"abcd\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":410,"symbol":"`skip whitespace after close delimiter`","kind":"function","lang":"kotlin","code":"@Test fun `skip whitespace after close delimiter`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(Regex(\"(?m)simple boundary--$\"), \"simple boundary-- \\t \\t\")\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val part = parts.nextPart()!!\n assertThat(part.headers).isEqualTo(headersOf())\n assertThat(part.body.readUtf8()).isEqualTo(\"abcd\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":434,"symbol":"`other characters after boundary`","kind":"function","lang":"kotlin","code":"@Test fun `other characters after boundary`() {\n val multipart =\n \"\"\"\n |--simple boundary hi\n \"\"\".trimMargin()\n .replace(Regex(\"(?m)simple boundary$\"), \"simple boundary \")\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n assertFailsWith {\n parts.nextPart()\n }.also { expected ->\n assertThat(expected).hasMessage(\"unexpected characters after boundary\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":455,"symbol":"`whitespace before close delimiter`","kind":"function","lang":"kotlin","code":"@Test fun `whitespace before close delimiter`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundary --\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n parts.nextPart()\n assertFailsWith {\n parts.nextPart()\n }.also { expected ->\n assertThat(expected).hasMessage(\"unexpected characters after boundary\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":480,"symbol":"`dash boundary`","kind":"function","lang":"kotlin","doc":"The documentation advises that '-' is the simplest boundary possible.","code":"@Test fun `dash boundary`() {\n val multipart =\n \"\"\"\n |---\n |Content-ID: abc\n |\n |abcd\n |---\n |Content-ID: efg\n |\n |efgh\n |-----\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"-\",\n source = Buffer().writeUtf8(multipart),\n )\n\n val partAbc = parts.nextPart()!!\n assertThat(partAbc.headers).isEqualTo(headersOf(\"Content-ID\", \"abc\"))\n assertThat(partAbc.body.readUtf8()).isEqualTo(\"abcd\")\n\n val partEfg = parts.nextPart()!!\n assertThat(partEfg.headers).isEqualTo(headersOf(\"Content-ID\", \"efg\"))\n assertThat(partEfg.body.readUtf8()).isEqualTo(\"efgh\")\n\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":512,"symbol":"`no more parts is idempotent`","kind":"function","lang":"kotlin","code":"@Test fun `no more parts is idempotent`() {\n val multipart =\n \"\"\"\n |--simple boundary\n |\n |abcd\n |--simple boundary--\n |\n |efgh\n |--simple boundary--\n \"\"\".trimMargin()\n .replace(\"\\n\", \"\\r\\n\")\n\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer().writeUtf8(multipart),\n )\n\n assertThat(parts.nextPart()).isNotNull()\n assertThat(parts.nextPart()).isNull()\n assertThat(parts.nextPart()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":536,"symbol":"`empty source`","kind":"function","lang":"kotlin","code":"@Test fun `empty source`() {\n val parts =\n MultipartReader(\n boundary = \"simple boundary\",\n source = Buffer(),\n )\n\n assertFailsWith {\n parts.nextPart()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":549,"symbol":"`multipart round trip`","kind":"function","lang":"kotlin","doc":"Confirm that [MultipartBody] and [MultipartReader] can work together.","code":"@Test fun `multipart round trip`() {\n val body =\n MultipartBody\n .Builder(\"boundary\")\n .setType(MultipartBody.PARALLEL)\n .addPart(\"Quick\".toRequestBody(\"text/plain\".toMediaType()))\n .addFormDataPart(\"color\", \"Brown\")\n .addFormDataPart(\"animal\", \"fox.txt\", \"Fox\".toRequestBody())\n .build()\n\n val bodyContent = Buffer()\n body.writeTo(bodyContent)\n\n val reader = MultipartReader(bodyContent, \"boundary\")\n\n val quickPart = reader.nextPart()!!\n assertThat(quickPart.headers).isEqualTo(\n headersOf(\n \"Content-Type\",\n \"text/plain; charset=utf-8\",\n ),\n )\n assertThat(quickPart.body.readUtf8()).isEqualTo(\"Quick\")\n\n val brownPart = reader.nextPart()!!\n assertThat(brownPart.headers).isEqualTo(\n headersOf(\n \"Content-Disposition\",\n \"form-data; name=\\\"color\\\"\",\n ),\n )\n assertThat(brownPart.body.readUtf8()).isEqualTo(\"Brown\")\n\n val foxPart = reader.nextPart()!!\n assertThat(foxPart.headers).isEqualTo(\n headersOf(\n \"Content-Disposition\",\n \"form-data; name=\\\"animal\\\"; filename=\\\"fox.txt\\\"\",\n ),\n )\n assertThat(foxPart.body.readUtf8()).isEqualT"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":606,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = \"application/octet-stream\".toMediaTypeOrNull()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":608,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = 1024L * 1024L * 100L"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/MultipartReaderTest.kt","line":610,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n val a1024x1024 = \"a\".repeat(1024 * 1024)\n repeat(100) {\n sink.writeUtf8(a1024x1024)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":51,"symbol":"OkHttpClientTest","kind":"class","lang":"kotlin","code":"class OkHttpClientTest {\n @RegisterExtension\n var platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @AfterEach fun tearDown() {\n ProxySelector.setDefault(DEFAULT_PROXY_SELECTOR)\n CookieManager.setDefault(DEFAULT_COOKIE_HANDLER)\n ResponseCache.setDefault(DEFAULT_RESPONSE_CACHE)\n }\n\n @Test fun durationDefaults() {\n val client = clientTestRule.newClient()\n assertThat(client.callTimeoutMillis).isEqualTo(0)\n assertThat(client.connectTimeoutMillis).isEqualTo(10000)\n assertThat(client.readTimeoutMillis).isEqualTo(10000)\n assertThat(client.writeTimeoutMillis).isEqualTo(10000)\n assertThat(client.pingIntervalMillis).isEqualTo(0)\n assertThat(client.webSocketCloseTimeout).isEqualTo(60_000)\n }\n\n @Test fun webSocketDefaults() {\n val client = clientTestRule.newClient()\n assertThat(client.minWebSocketMessageToCompress).isEqualTo(1024)\n }\n\n @Test fun timeoutValidRange() {\n val builder = OkHttpClient.Builder()\n try {\n builder.callTimeout(Duration.ofNanos(1))\n } catch (ignored: IllegalArgumentException) {\n }\n try {\n builder.connectTim"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":61,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n ProxySelector.setDefault(DEFAULT_PROXY_SELECTOR)\n CookieManager.setDefault(DEFAULT_COOKIE_HANDLER)\n ResponseCache.setDefault(DEFAULT_RESPONSE_CACHE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":67,"symbol":"durationDefaults","kind":"function","lang":"kotlin","code":"@Test fun durationDefaults() {\n val client = clientTestRule.newClient()\n assertThat(client.callTimeoutMillis).isEqualTo(0)\n assertThat(client.connectTimeoutMillis).isEqualTo(10000)\n assertThat(client.readTimeoutMillis).isEqualTo(10000)\n assertThat(client.writeTimeoutMillis).isEqualTo(10000)\n assertThat(client.pingIntervalMillis).isEqualTo(0)\n assertThat(client.webSocketCloseTimeout).isEqualTo(60_000)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":77,"symbol":"webSocketDefaults","kind":"function","lang":"kotlin","code":"@Test fun webSocketDefaults() {\n val client = clientTestRule.newClient()\n assertThat(client.minWebSocketMessageToCompress).isEqualTo(1024)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":82,"symbol":"timeoutValidRange","kind":"function","lang":"kotlin","code":"@Test fun timeoutValidRange() {\n val builder = OkHttpClient.Builder()\n try {\n builder.callTimeout(Duration.ofNanos(1))\n } catch (ignored: IllegalArgumentException) {\n }\n try {\n builder.connectTimeout(Duration.ofNanos(1))\n } catch (ignored: IllegalArgumentException) {\n }\n try {\n builder.writeTimeout(Duration.ofNanos(1))\n } catch (ignored: IllegalArgumentException) {\n }\n try {\n builder.readTimeout(Duration.ofNanos(1))\n } catch (ignored: IllegalArgumentException) {\n }\n try {\n builder.callTimeout(Duration.ofDays(365))\n } catch (ignored: IllegalArgumentException) {\n }\n try {\n builder.connectTimeout(Duration.ofDays(365))\n } catch (ignored: IllegalArgumentException) {\n }\n try {\n builder.writeTimeout(Duration.ofDays(365))\n } catch (ignored: IllegalArgumentException) {\n }\n try {\n builder.readTimeout(Duration.ofDays(365))\n } catch (ignored: IllegalArgumentException) {\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":118,"symbol":"clonedInterceptorsListsAreIndependent","kind":"function","lang":"kotlin","code":"@Test fun clonedInterceptorsListsAreIndependent() {\n val interceptor =\n Interceptor { chain: Interceptor.Chain ->\n chain.proceed(chain.request())\n }\n val original = clientTestRule.newClient()\n original\n .newBuilder()\n .addInterceptor(interceptor)\n .addNetworkInterceptor(interceptor)\n .build()\n assertThat(original.interceptors.size).isEqualTo(0)\n assertThat(original.networkInterceptors.size).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":137,"symbol":"cloneSharesStatefulInstances","kind":"function","lang":"kotlin","doc":"When copying the client, stateful things like the connection pool are shared across all clients.","code":"@Test fun cloneSharesStatefulInstances() {\n val client = clientTestRule.newClient()\n\n // Values should be non-null.\n val a = client.newBuilder().build()\n assertThat(a.dispatcher).isNotNull()\n assertThat(a.connectionPool).isNotNull()\n assertThat(a.sslSocketFactory).isNotNull()\n assertThat(a.x509TrustManager).isNotNull()\n\n // Multiple clients share the instances.\n val b = client.newBuilder().build()\n assertThat(b.dispatcher).isSameInstanceAs(a.dispatcher)\n assertThat(b.connectionPool).isSameInstanceAs(a.connectionPool)\n assertThat(b.sslSocketFactory).isSameInstanceAs(a.sslSocketFactory)\n assertThat(b.x509TrustManager).isSameInstanceAs(a.x509TrustManager)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":155,"symbol":"setProtocolsRejectsHttp10","kind":"function","lang":"kotlin","code":"@Test fun setProtocolsRejectsHttp10() {\n val builder = OkHttpClient.Builder()\n assertFailsWith {\n builder.protocols(listOf(Protocol.HTTP_1_0, Protocol.HTTP_1_1))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":162,"symbol":"certificatePinnerEquality","kind":"function","lang":"kotlin","code":"@Test fun certificatePinnerEquality() {\n val clientA = clientTestRule.newClient()\n val clientB = clientTestRule.newClient()\n assertThat(clientB.certificatePinner).isEqualTo(clientA.certificatePinner)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":168,"symbol":"nullInterceptorInList","kind":"function","lang":"kotlin","code":"@Test fun nullInterceptorInList() {\n val builder = OkHttpClient.Builder()\n builder.interceptors().addAll(listOf(null) as List)\n assertFailsWith {\n builder.build()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Null interceptor: [null]\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":178,"symbol":"nullNetworkInterceptorInList","kind":"function","lang":"kotlin","code":"@Test fun nullNetworkInterceptorInList() {\n val builder = OkHttpClient.Builder()\n builder.networkInterceptors().addAll(listOf(null) as List)\n assertFailsWith {\n builder.build()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Null network interceptor: [null]\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":188,"symbol":"testH2PriorKnowledgeOkHttpClientConstructionFallback","kind":"function","lang":"kotlin","code":"@Test fun testH2PriorKnowledgeOkHttpClientConstructionFallback() {\n assertFailsWith {\n OkHttpClient\n .Builder()\n .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_1_1))\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"protocols containing h2_prior_knowledge cannot use other protocols: \" +\n \"[h2_prior_knowledge, http/1.1]\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":201,"symbol":"testH2PriorKnowledgeOkHttpClientConstructionDuplicates","kind":"function","lang":"kotlin","code":"@Test fun testH2PriorKnowledgeOkHttpClientConstructionDuplicates() {\n assertFailsWith {\n OkHttpClient\n .Builder()\n .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.H2_PRIOR_KNOWLEDGE))\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"protocols containing h2_prior_knowledge cannot use other protocols: \" +\n \"[h2_prior_knowledge, h2_prior_knowledge]\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":214,"symbol":"testH2PriorKnowledgeOkHttpClientConstructionSuccess","kind":"function","lang":"kotlin","code":"@Test fun testH2PriorKnowledgeOkHttpClientConstructionSuccess() {\n val okHttpClient =\n OkHttpClient\n .Builder()\n .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE))\n .build()\n assertThat(okHttpClient.protocols.size).isEqualTo(1)\n assertThat(okHttpClient.protocols[0]).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":224,"symbol":"nullDefaultProxySelector","kind":"function","lang":"kotlin","code":"@Test fun nullDefaultProxySelector() {\n server!!.enqueue(MockResponse(body = \"abc\"))\n ProxySelector.setDefault(null)\n val client = clientTestRule.newClient()\n val request = Request(server!!.url(\"/\"))\n val response = client.newCall(request).execute()\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":233,"symbol":"sslSocketFactorySetAsSocketFactory","kind":"function","lang":"kotlin","code":"@Test fun sslSocketFactorySetAsSocketFactory() {\n val builder = OkHttpClient.Builder()\n assertFailsWith {\n builder.socketFactory(SSLSocketFactory.getDefault())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":240,"symbol":"noSslSocketFactoryConfigured","kind":"function","lang":"kotlin","code":"@Test fun noSslSocketFactoryConfigured() {\n val client =\n OkHttpClient\n .Builder()\n .connectionSpecs(listOf(ConnectionSpec.CLEARTEXT))\n .build()\n assertFailsWith {\n client.sslSocketFactory\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":251,"symbol":"nullHostileProtocolList","kind":"function","lang":"kotlin","code":"@Test fun nullHostileProtocolList() {\n val nullHostileProtocols =\n object : AbstractList() {\n override val size: Int = 1\n\n override fun get(index: Int) = Protocol.HTTP_1_1\n\n override fun contains(element: Protocol?): Boolean {\n if (element == null) throw NullPointerException()\n return super.contains(element)\n }\n\n override fun indexOf(element: Protocol?): Int {\n if (element == null) throw NullPointerException()\n return super.indexOf(element)\n }\n } as List\n val client =\n OkHttpClient\n .Builder()\n .protocols(nullHostileProtocols)\n .build()\n assertEquals(\n listOf(Protocol.HTTP_1_1),\n client.protocols,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":256,"symbol":"get","kind":"function","lang":"kotlin","code":"override fun get(index: Int) = Protocol.HTTP_1_1"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":258,"symbol":"contains","kind":"function","lang":"kotlin","code":"override fun contains(element: Protocol?): Boolean {\n if (element == null) throw NullPointerException()\n return super.contains(element)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":263,"symbol":"indexOf","kind":"function","lang":"kotlin","code":"override fun indexOf(element: Protocol?): Int {\n if (element == null) throw NullPointerException()\n return super.indexOf(element)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":279,"symbol":"nullProtocolInList","kind":"function","lang":"kotlin","code":"@Test fun nullProtocolInList() {\n val protocols =\n mutableListOf(\n Protocol.HTTP_1_1,\n null,\n )\n assertFailsWith {\n OkHttpClient\n .Builder()\n .protocols(protocols as List)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"protocols must not contain null\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":294,"symbol":"spdy3IsRemovedFromProtocols","kind":"function","lang":"kotlin","code":"@Test fun spdy3IsRemovedFromProtocols() {\n val protocols =\n mutableListOf(\n Protocol.HTTP_1_1,\n Protocol.SPDY_3,\n )\n val client =\n OkHttpClient\n .Builder()\n .protocols(protocols)\n .build()\n assertThat(client.protocols).containsExactly(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":308,"symbol":"testProxyDefaults","kind":"function","lang":"kotlin","code":"@Test fun testProxyDefaults() {\n var client = OkHttpClient.Builder().build()\n assertThat(client.proxy).isNull()\n assertThat(client.proxySelector)\n .isNotInstanceOf(NullProxySelector::class.java)\n client =\n OkHttpClient\n .Builder()\n .proxy(Proxy.NO_PROXY)\n .build()\n assertThat(client.proxy).isSameInstanceAs(Proxy.NO_PROXY)\n assertThat(client.proxySelector)\n .isInstanceOf(NullProxySelector::class.java)\n client =\n OkHttpClient\n .Builder()\n .proxySelector(FakeProxySelector())\n .build()\n assertThat(client.proxy).isNull()\n assertThat(client.proxySelector)\n .isInstanceOf(FakeProxySelector::class.java)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":331,"symbol":"sharesRouteDatabase","kind":"function","lang":"kotlin","code":"@Test fun sharesRouteDatabase() {\n val client =\n OkHttpClient\n .Builder()\n .build()\n val proxySelector: ProxySelector =\n object : ProxySelector() {\n override fun select(uri: URI): List = listOf()\n\n override fun connectFailed(\n uri: URI,\n socketAddress: SocketAddress,\n e: IOException,\n ) {}\n }\n\n val trustManager = get().platformTrustManager()\n val sslContext = get().newSSLContext()\n sslContext.init(null, null, null)\n\n // new client, may share all same fields but likely different connection pool\n assertNotSame(\n client.routeDatabase,\n OkHttpClient\n .Builder()\n .build()\n .routeDatabase,\n )\n\n // same client with no change affecting route db\n assertSame(\n client.routeDatabase,\n client\n .newBuilder()\n .build()\n .routeDatabase,\n )\n assertSame(\n client.routeDatabase,\n client\n .newBuilder()\n .callTimeout(Duration.ofSeconds(5))\n .build()\n .routeDatabase,\n )\n\n // logically different scope of client for route db\n assertNotSame(\n client.routeDatabase,\n client\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":338,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI): List = listOf()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":340,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI,\n socketAddress: SocketAddress,\n e: IOException,\n ) {}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OkHttpClientTest.kt","line":452,"symbol":"minWebSocketMessageToCompressNegative","kind":"function","lang":"kotlin","code":"@Test fun minWebSocketMessageToCompressNegative() {\n val builder = OkHttpClient.Builder()\n assertFailsWith {\n builder.minWebSocketMessageToCompress(-1024)\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"minWebSocketMessageToCompress must be positive: -1024\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OpenJSSETest.kt","line":40,"symbol":"OpenJSSETest","kind":"class","lang":"kotlin","code":"class OpenJSSETest {\n @JvmField @RegisterExtension\n var platform = PlatformRule()\n\n @JvmField @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n var client = clientTestRule.newClient()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n platform.assumeOpenJSSE()\n }\n\n @Test\n fun testTlsv13Works() {\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request(server.url(\"/\"))\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n assertEquals(TlsVersion.TLS_1_3, response.handshake?.tlsVersion)\n assertEquals(Protocol.HTTP_2, response.protocol)\n\n assertThat(response.exchangeAccessor!!.connectionAccessor.socket())\n .isInstanceOf()\n }\n }\n\n @Test\n fun testSupportedProtocols() {\n val factory = SSLSocketFactoryImpl()\n val s = factory.createSocket() as SSLSocketImpl\n\n assertEquals(listOf(\"TLSv1.3\", \"TLSv1.2\"), s.enabledProtocols.toList())\n }\n\n @Test\n @Disabled\n fun testMozilla() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://mozilla.org/robots.txt\").build()\n\n clie"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OpenJSSETest.kt","line":52,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeOpenJSSE()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OpenJSSETest.kt","line":57,"symbol":"testTlsv13Works","kind":"function","lang":"kotlin","code":"@Test\n fun testTlsv13Works() {\n enableTls()\n\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request(server.url(\"/\"))\n\n val response = client.newCall(request).execute()\n\n response.use {\n assertEquals(200, response.code)\n assertEquals(TlsVersion.TLS_1_3, response.handshake?.tlsVersion)\n assertEquals(Protocol.HTTP_2, response.protocol)\n\n assertThat(response.exchangeAccessor!!.connectionAccessor.socket())\n .isInstanceOf()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OpenJSSETest.kt","line":77,"symbol":"testSupportedProtocols","kind":"function","lang":"kotlin","code":"@Test\n fun testSupportedProtocols() {\n val factory = SSLSocketFactoryImpl()\n val s = factory.createSocket() as SSLSocketImpl\n\n assertEquals(listOf(\"TLSv1.3\", \"TLSv1.2\"), s.enabledProtocols.toList())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OpenJSSETest.kt","line":85,"symbol":"testMozilla","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun testMozilla() {\n assumeNetwork()\n\n val request = Request.Builder().url(\"https://mozilla.org/robots.txt\").build()\n\n client.newCall(request).execute().use {\n assertThat(it.protocol).isEqualTo(Protocol.HTTP_2)\n assertThat(it.handshake!!.tlsVersion).isEqualTo(TlsVersion.TLS_1_3)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OpenJSSETest.kt","line":98,"symbol":"testBuildIfSupported","kind":"function","lang":"kotlin","code":"@Test\n fun testBuildIfSupported() {\n val actual = OpenJSSEPlatform.buildIfSupported()\n assertThat(actual).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/OpenJSSETest.kt","line":104,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n // Generate a self-signed cert for the server to serve and the client to trust.\n // can't use TlsUtil.localhost with a non OpenJSSE trust manager\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"localhost\")\n .addSubjectAlternativeName(\"localhost\")\n .build()\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .heldCertificate(heldCertificate)\n .addTrustedCertificate(heldCertificate.certificate)\n .build()\n\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ProtocolTest.kt","line":25,"symbol":"ProtocolTest","kind":"class","lang":"kotlin","code":"class ProtocolTest {\n @Test\n fun testGetKnown() {\n assertThat(get(\"http/1.0\")).isEqualTo(Protocol.HTTP_1_0)\n assertThat(get(\"http/1.1\")).isEqualTo(Protocol.HTTP_1_1)\n assertThat(get(\"spdy/3.1\")).isEqualTo(Protocol.SPDY_3)\n assertThat(get(\"h2\")).isEqualTo(Protocol.HTTP_2)\n assertThat(get(\"h2_prior_knowledge\")).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE)\n assertThat(get(\"quic\")).isEqualTo(Protocol.QUIC)\n assertThat(get(\"h3\")).isEqualTo(Protocol.HTTP_3)\n assertThat(get(\"h3-29\")).isEqualTo(Protocol.HTTP_3)\n }\n\n @Test\n fun testGetUnknown() {\n assertThrows(IOException::class.java) { get(\"tcp\") }\n }\n\n @Test\n fun testToString() {\n assertThat(Protocol.HTTP_1_0.toString()).isEqualTo(\"http/1.0\")\n assertThat(Protocol.HTTP_1_1.toString()).isEqualTo(\"http/1.1\")\n assertThat(Protocol.SPDY_3.toString()).isEqualTo(\"spdy/3.1\")\n assertThat(Protocol.HTTP_2.toString()).isEqualTo(\"h2\")\n assertThat(Protocol.H2_PRIOR_KNOWLEDGE.toString())\n .isEqualTo(\"h2_prior_knowledge\")\n assertThat(Protocol.QUIC.toString()).isEqualTo(\"quic\")\n assertThat(Protocol.HTTP_3.toString()).isEqualTo(\"h3\")\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ProtocolTest.kt","line":26,"symbol":"testGetKnown","kind":"function","lang":"kotlin","code":"@Test\n fun testGetKnown() {\n assertThat(get(\"http/1.0\")).isEqualTo(Protocol.HTTP_1_0)\n assertThat(get(\"http/1.1\")).isEqualTo(Protocol.HTTP_1_1)\n assertThat(get(\"spdy/3.1\")).isEqualTo(Protocol.SPDY_3)\n assertThat(get(\"h2\")).isEqualTo(Protocol.HTTP_2)\n assertThat(get(\"h2_prior_knowledge\")).isEqualTo(Protocol.H2_PRIOR_KNOWLEDGE)\n assertThat(get(\"quic\")).isEqualTo(Protocol.QUIC)\n assertThat(get(\"h3\")).isEqualTo(Protocol.HTTP_3)\n assertThat(get(\"h3-29\")).isEqualTo(Protocol.HTTP_3)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ProtocolTest.kt","line":38,"symbol":"testGetUnknown","kind":"function","lang":"kotlin","code":"@Test\n fun testGetUnknown() {\n assertThrows(IOException::class.java) { get(\"tcp\") }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ProtocolTest.kt","line":43,"symbol":"testToString","kind":"function","lang":"kotlin","code":"@Test\n fun testToString() {\n assertThat(Protocol.HTTP_1_0.toString()).isEqualTo(\"http/1.0\")\n assertThat(Protocol.HTTP_1_1.toString()).isEqualTo(\"http/1.1\")\n assertThat(Protocol.SPDY_3.toString()).isEqualTo(\"spdy/3.1\")\n assertThat(Protocol.HTTP_2.toString()).isEqualTo(\"h2\")\n assertThat(Protocol.H2_PRIOR_KNOWLEDGE.toString())\n .isEqualTo(\"h2_prior_knowledge\")\n assertThat(Protocol.QUIC.toString()).isEqualTo(\"quic\")\n assertThat(Protocol.HTTP_3.toString()).isEqualTo(\"h3\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/PublicInternalApiTest.kt","line":25,"symbol":"PublicInternalApiTest","kind":"class","lang":"kotlin","code":"@Suppress(\"DEPRECATION_ERROR\")\nclass PublicInternalApiTest {\n @Test\n fun permitsRequestBody() {\n assertTrue(permitsRequestBody(\"POST\"))\n assertFalse(permitsRequestBody(\"GET\"))\n }\n\n @Test\n fun requiresRequestBody() {\n assertTrue(requiresRequestBody(\"PUT\"))\n assertFalse(requiresRequestBody(\"GET\"))\n }\n\n @Test\n fun hasBody() {\n val request = Request.Builder().url(\"http://example.com\").build()\n val response =\n Response\n .Builder()\n .code(200)\n .message(\"OK\")\n .request(request)\n .protocol(Protocol.HTTP_2)\n .build()\n assertTrue(hasBody(response))\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/PublicInternalApiTest.kt","line":27,"symbol":"permitsRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun permitsRequestBody() {\n assertTrue(permitsRequestBody(\"POST\"))\n assertFalse(permitsRequestBody(\"GET\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/PublicInternalApiTest.kt","line":33,"symbol":"requiresRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun requiresRequestBody() {\n assertTrue(requiresRequestBody(\"PUT\"))\n assertFalse(requiresRequestBody(\"GET\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/PublicInternalApiTest.kt","line":39,"symbol":"hasBody","kind":"function","lang":"kotlin","code":"@Test\n fun hasBody() {\n val request = Request.Builder().url(\"http://example.com\").build()\n val response =\n Response\n .Builder()\n .code(200)\n .message(\"OK\")\n .request(request)\n .protocol(Protocol.HTTP_2)\n .build()\n assertTrue(hasBody(response))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":34,"symbol":"RecordedResponse","kind":"class","lang":"kotlin","doc":"A received response or failure recorded by the response recorder.","code":"class RecordedResponse(\n @JvmField val request: Request,\n val response: Response?,\n val webSocket: WebSocket?,\n val body: String?,\n val failure: IOException?,\n) {\n fun assertRequestUrl(url: HttpUrl) =\n apply {\n assertThat(request.url).isEqualTo(url)\n }\n\n fun assertRequestMethod(method: String) =\n apply {\n assertThat(request.method).isEqualTo(method)\n }\n\n fun assertRequestHeader(\n name: String,\n vararg values: String,\n ) = apply {\n assertThat(request.headers(name)).containsExactly(*values)\n }\n\n fun assertCode(expectedCode: Int) =\n apply {\n assertThat(response!!.code).isEqualTo(expectedCode)\n }\n\n fun assertSuccessful() =\n apply {\n assertThat(failure).isNull()\n assertThat(response!!.isSuccessful).isTrue()\n }\n\n fun assertNotSuccessful() =\n apply {\n assertThat(response!!.isSuccessful).isFalse()\n }\n\n fun assertHeader(\n name: String,\n vararg values: String?,\n ) = apply {\n assertThat(response!!.headers(name)).containsExactly(*values)\n }\n\n fun assertHeaders(headers: Headers) =\n apply {\n assertThat(response!!.headers).isEqualTo(headers)\n }\n\n fun assertBody(expectedBody: String) =\n ap"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":41,"symbol":"assertRequestUrl","kind":"function","lang":"kotlin","code":"fun assertRequestUrl(url: HttpUrl) =\n apply {\n assertThat(request.url).isEqualTo(url)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":46,"symbol":"assertRequestMethod","kind":"function","lang":"kotlin","code":"fun assertRequestMethod(method: String) =\n apply {\n assertThat(request.method).isEqualTo(method)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":51,"symbol":"assertRequestHeader","kind":"function","lang":"kotlin","code":"fun assertRequestHeader(\n name: String,\n vararg values: String,\n ) = apply {\n assertThat(request.headers(name)).containsExactly(*values)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":58,"symbol":"assertCode","kind":"function","lang":"kotlin","code":"fun assertCode(expectedCode: Int) =\n apply {\n assertThat(response!!.code).isEqualTo(expectedCode)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":63,"symbol":"assertSuccessful","kind":"function","lang":"kotlin","code":"fun assertSuccessful() =\n apply {\n assertThat(failure).isNull()\n assertThat(response!!.isSuccessful).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":69,"symbol":"assertNotSuccessful","kind":"function","lang":"kotlin","code":"fun assertNotSuccessful() =\n apply {\n assertThat(response!!.isSuccessful).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":74,"symbol":"assertHeader","kind":"function","lang":"kotlin","code":"fun assertHeader(\n name: String,\n vararg values: String?,\n ) = apply {\n assertThat(response!!.headers(name)).containsExactly(*values)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":81,"symbol":"assertHeaders","kind":"function","lang":"kotlin","code":"fun assertHeaders(headers: Headers) =\n apply {\n assertThat(response!!.headers).isEqualTo(headers)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":86,"symbol":"assertBody","kind":"function","lang":"kotlin","code":"fun assertBody(expectedBody: String) =\n apply {\n assertThat(body).isEqualTo(expectedBody)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":91,"symbol":"assertHandshake","kind":"function","lang":"kotlin","code":"fun assertHandshake() =\n apply {\n val handshake = response!!.handshake!!\n assertThat(handshake.tlsVersion).isNotNull()\n assertThat(handshake.cipherSuite).isNotNull()\n assertThat(handshake.peerPrincipal).isNotNull()\n assertThat(handshake.peerCertificates.size).isEqualTo(1)\n assertThat(handshake.localPrincipal).isNull()\n assertThat(handshake.localCertificates.size).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":105,"symbol":"priorResponse","kind":"function","lang":"kotlin","doc":"Asserts that the current response was redirected and returns the prior response.","code":"fun priorResponse(): RecordedResponse {\n val priorResponse = response!!.priorResponse!!\n return RecordedResponse(priorResponse.request, priorResponse, null, null, null)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":113,"symbol":"networkResponse","kind":"function","lang":"kotlin","doc":"Asserts that the current response used the network and returns the network response.","code":"fun networkResponse(): RecordedResponse {\n val networkResponse = response!!.networkResponse!!\n return RecordedResponse(networkResponse.request, networkResponse, null, null, null)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":119,"symbol":"assertNoNetworkResponse","kind":"function","lang":"kotlin","doc":"Asserts that the current response didn't use the network.","code":"fun assertNoNetworkResponse() =\n apply {\n assertThat(response!!.networkResponse).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":125,"symbol":"assertNoCacheResponse","kind":"function","lang":"kotlin","doc":"Asserts that the current response didn't use the cache.","code":"fun assertNoCacheResponse() =\n apply {\n assertThat(response!!.cacheResponse).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":133,"symbol":"cacheResponse","kind":"function","lang":"kotlin","doc":"Asserts that the current response used the cache and returns the cache response.","code":"fun cacheResponse(): RecordedResponse {\n val cacheResponse = response!!.cacheResponse!!\n return RecordedResponse(cacheResponse.request, cacheResponse, null, null, null)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":138,"symbol":"assertFailure","kind":"function","lang":"kotlin","code":"fun assertFailure(vararg allowedExceptionTypes: Class<*>) =\n apply {\n var found = false\n for (expectedClass in allowedExceptionTypes) {\n if (expectedClass.isInstance(failure)) {\n found = true\n break\n }\n }\n assertThat(\n found,\n \"Expected exception type among ${allowedExceptionTypes.contentToString()}, got $failure\",\n ).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":153,"symbol":"assertFailure","kind":"function","lang":"kotlin","code":"fun assertFailure(vararg messages: String) =\n apply {\n assertThat(failure, \"No failure found\").isNotNull()\n assertThat(messages).contains(failure!!.message)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":159,"symbol":"assertFailureMatches","kind":"function","lang":"kotlin","code":"fun assertFailureMatches(vararg patterns: String) =\n apply {\n val message = failure!!.message!!\n assertThat(\n patterns.firstOrNull { pattern ->\n message.matches(pattern.toRegex())\n },\n ).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":169,"symbol":"assertSentRequestAtMillis","kind":"function","lang":"kotlin","code":"fun assertSentRequestAtMillis(\n minimum: Long,\n maximum: Long,\n ) = apply {\n assertDateInRange(minimum, response!!.sentRequestAtMillis, maximum)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":176,"symbol":"assertReceivedResponseAtMillis","kind":"function","lang":"kotlin","code":"fun assertReceivedResponseAtMillis(\n minimum: Long,\n maximum: Long,\n ) = apply {\n assertDateInRange(minimum, response!!.receivedResponseAtMillis, maximum)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":183,"symbol":"assertDateInRange","kind":"function","lang":"kotlin","code":"private fun assertDateInRange(\n minimum: Long,\n actual: Long,\n maximum: Long,\n ) {\n assertThat(actual, \"${format(minimum)} <= ${format(actual)} <= ${format(maximum)}\")\n .isBetween(minimum, maximum)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordedResponse.kt","line":192,"symbol":"format","kind":"function","lang":"kotlin","code":"private fun format(time: Long) = SimpleDateFormat(\"HH:mm:ss.SSS\").format(Date(time))"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingCallback.kt","line":24,"symbol":"RecordingCallback","kind":"class","lang":"kotlin","doc":"Records received HTTP responses so they can be later retrieved by tests.","code":"class RecordingCallback : Callback {\n private val responses = mutableListOf()\n\n @Synchronized\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n responses.add(RecordedResponse(call.request(), null, null, null, e))\n (this as Object).notifyAll()\n }\n\n @Synchronized\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val body = response.body.string()\n responses.add(RecordedResponse(call.request(), response, null, body, null))\n (this as Object).notifyAll()\n }\n\n /**\n * Returns the recorded response triggered by `request`. Throws if the response isn't\n * enqueued before the timeout.\n */\n @Synchronized\n fun await(url: HttpUrl): RecordedResponse {\n val timeoutMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) + TIMEOUT_MILLIS\n while (true) {\n val i = responses.iterator()\n while (i.hasNext()) {\n val recordedResponse = i.next()\n if (recordedResponse.request.url.equals(url)) {\n i.remove()\n return recordedResponse\n }\n }\n val nowMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime())\n if (nowMillis >= timeoutMillis) break\n (thi"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingCallback.kt","line":27,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"@Synchronized\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n responses.add(RecordedResponse(call.request(), null, null, null, e))\n (this as Object).notifyAll()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingCallback.kt","line":36,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"@Synchronized\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val body = response.body.string()\n responses.add(RecordedResponse(call.request(), response, null, body, null))\n (this as Object).notifyAll()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingCallback.kt","line":50,"symbol":"await","kind":"function","lang":"kotlin","doc":"Returns the recorded response triggered by `request`. Throws if the response isn't enqueued before the timeout.","code":"@Synchronized\n fun await(url: HttpUrl): RecordedResponse {\n val timeoutMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) + TIMEOUT_MILLIS\n while (true) {\n val i = responses.iterator()\n while (i.hasNext()) {\n val recordedResponse = i.next()\n if (recordedResponse.request.url.equals(url)) {\n i.remove()\n return recordedResponse\n }\n }\n val nowMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime())\n if (nowMillis >= timeoutMillis) break\n (this as Object).wait(timeoutMillis - nowMillis)\n }\n\n throw AssertionError(\"Timed out waiting for response to $url\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":30,"symbol":"RecordingExecutor","kind":"class","lang":"kotlin","doc":"A fake executor for testing that never executes anything! Instead, it just keeps track of what's been enqueued.","code":"internal class RecordingExecutor(\n private val dispatcherTest: DispatcherTest,\n) : AbstractExecutorService() {\n private var shutdown: Boolean = false\n private val calls = mutableListOf()\n\n override fun execute(command: Runnable) {\n if (shutdown) throw RejectedExecutionException()\n calls.add(command as RealCall.AsyncCall)\n }\n\n fun assertJobs(vararg expectedUrls: String) {\n val actualUrls = calls.map { it.request.url.toString() }\n assertThat(actualUrls).containsExactly(*expectedUrls)\n }\n\n fun finishJob(url: String) {\n val i = calls.iterator()\n while (i.hasNext()) {\n val call = i.next()\n if (call.request.url.toString() == url) {\n i.remove()\n dispatcherTest.dispatcher.finishedAccessor(call)\n return\n }\n }\n throw AssertionError(\"No such job: $url\")\n }\n\n override fun shutdown() {\n shutdown = true\n }\n\n override fun shutdownNow(): List = throw UnsupportedOperationException()\n\n override fun isShutdown(): Boolean = shutdown\n\n override fun isTerminated(): Boolean = throw UnsupportedOperationException()\n\n override fun awaitTermination(\n timeout: Long,\n unit: TimeUnit,\n ): Boolean ="} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":36,"symbol":"execute","kind":"function","lang":"kotlin","code":"override fun execute(command: Runnable) {\n if (shutdown) throw RejectedExecutionException()\n calls.add(command as RealCall.AsyncCall)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":41,"symbol":"assertJobs","kind":"function","lang":"kotlin","code":"fun assertJobs(vararg expectedUrls: String) {\n val actualUrls = calls.map { it.request.url.toString() }\n assertThat(actualUrls).containsExactly(*expectedUrls)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":46,"symbol":"finishJob","kind":"function","lang":"kotlin","code":"fun finishJob(url: String) {\n val i = calls.iterator()\n while (i.hasNext()) {\n val call = i.next()\n if (call.request.url.toString() == url) {\n i.remove()\n dispatcherTest.dispatcher.finishedAccessor(call)\n return\n }\n }\n throw AssertionError(\"No such job: $url\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":59,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"override fun shutdown() {\n shutdown = true\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":63,"symbol":"shutdownNow","kind":"function","lang":"kotlin","code":"override fun shutdownNow(): List = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":65,"symbol":"isShutdown","kind":"function","lang":"kotlin","code":"override fun isShutdown(): Boolean = shutdown"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":67,"symbol":"isTerminated","kind":"function","lang":"kotlin","code":"override fun isTerminated(): Boolean = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RecordingExecutor.kt","line":69,"symbol":"awaitTermination","kind":"function","lang":"kotlin","code":"override fun awaitTermination(\n timeout: Long,\n unit: TimeUnit,\n ): Boolean = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":36,"symbol":"RequestBodyTest","kind":"class","lang":"kotlin","code":"class RequestBodyTest {\n private lateinit var filePath: okio.Path\n\n @BeforeEach\n fun setup(\n @TempDir tempDir: Path,\n ) {\n filePath = tempDir.toOkioPath() / \"file.txt\"\n }\n\n @Test\n fun testFileDescriptor() {\n assertOnFileDescriptor { fd ->\n val requestBody = fd.toRequestBody()\n\n assertThat(requestBody.contentLength()).isEqualTo(-1L)\n assertThat(requestBody.isOneShot()).isEqualTo(true)\n }\n }\n\n @Test\n fun testFileDescriptorRead() {\n assertOnFileDescriptor(content = \"Hello\") { fd ->\n val requestBody = fd.toRequestBody()\n\n val buffer = Buffer()\n requestBody.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(\"Hello\")\n }\n }\n\n @Test\n fun testFileDescriptorDefaultMediaType() {\n assertOnFileDescriptor { fd ->\n val requestBody = fd.toRequestBody()\n\n assertThat(requestBody.contentType()).isNull()\n }\n }\n\n @Test\n fun testFileDescriptorMediaType() {\n assertOnFileDescriptor { fd ->\n val contentType = \"text/plain\".toMediaType()\n\n val requestBody = fd.toRequestBody(contentType)\n\n assertThat(requestBody.contentType()).isEqualTo(contentType)\n }\n }\n\n @Test\n fun testFileDescriptorReadTwice("} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":39,"symbol":"setup","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setup(\n @TempDir tempDir: Path,\n ) {\n filePath = tempDir.toOkioPath() / \"file.txt\"\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":46,"symbol":"testFileDescriptor","kind":"function","lang":"kotlin","code":"@Test\n fun testFileDescriptor() {\n assertOnFileDescriptor { fd ->\n val requestBody = fd.toRequestBody()\n\n assertThat(requestBody.contentLength()).isEqualTo(-1L)\n assertThat(requestBody.isOneShot()).isEqualTo(true)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":56,"symbol":"testFileDescriptorRead","kind":"function","lang":"kotlin","code":"@Test\n fun testFileDescriptorRead() {\n assertOnFileDescriptor(content = \"Hello\") { fd ->\n val requestBody = fd.toRequestBody()\n\n val buffer = Buffer()\n requestBody.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(\"Hello\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":67,"symbol":"testFileDescriptorDefaultMediaType","kind":"function","lang":"kotlin","code":"@Test\n fun testFileDescriptorDefaultMediaType() {\n assertOnFileDescriptor { fd ->\n val requestBody = fd.toRequestBody()\n\n assertThat(requestBody.contentType()).isNull()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":76,"symbol":"testFileDescriptorMediaType","kind":"function","lang":"kotlin","code":"@Test\n fun testFileDescriptorMediaType() {\n assertOnFileDescriptor { fd ->\n val contentType = \"text/plain\".toMediaType()\n\n val requestBody = fd.toRequestBody(contentType)\n\n assertThat(requestBody.contentType()).isEqualTo(contentType)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":87,"symbol":"testFileDescriptorReadTwice","kind":"function","lang":"kotlin","code":"@Test\n fun testFileDescriptorReadTwice() {\n assertOnFileDescriptor(content = \"Hello\") { fd ->\n val requestBody = fd.toRequestBody()\n\n val buffer = Buffer()\n requestBody.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(\"Hello\")\n\n assertThrows(IOException::class.java) {\n requestBody.writeTo(Buffer())\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":102,"symbol":"testFileDescriptorAfterClose","kind":"function","lang":"kotlin","code":"@Test\n fun testFileDescriptorAfterClose() {\n val closedRequestBody = assertOnFileDescriptor { it.toRequestBody() }\n\n assertThrows(IOException::class.java) {\n closedRequestBody.writeTo(Buffer())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":111,"symbol":"testPathRead","kind":"function","lang":"kotlin","code":"@Test\n fun testPathRead() {\n assertOnPath(content = \"Hello\") { path ->\n val requestBody = path.asRequestBody(FileSystem.SYSTEM)\n\n val buffer = Buffer()\n requestBody.writeTo(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(\"Hello\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":122,"symbol":"testSha256","kind":"function","lang":"kotlin","code":"@Test\n fun testSha256() {\n val hash = \"Hello\".toRequestBody().sha256().hex()\n assertThat(hash).isEqualTo(\"185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":128,"symbol":"assertOnFileDescriptor","kind":"function","lang":"kotlin","code":"private inline fun assertOnFileDescriptor(\n content: String? = null,\n fn: (FileDescriptor) -> T,\n ): T =\n assertOnPath(content) {\n FileInputStream(filePath.toFile()).use { fis ->\n fn(fis.fd)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestBodyTest.kt","line":138,"symbol":"assertOnPath","kind":"function","lang":"kotlin","code":"private inline fun assertOnPath(\n content: String? = null,\n fn: (okio.Path) -> T,\n ): T {\n FileSystem.SYSTEM.write(filePath) {\n if (content != null) {\n writeUtf8(content)\n }\n }\n\n return fn(filePath)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":32,"symbol":"RequestCommonTest","kind":"class","lang":"kotlin","code":"class RequestCommonTest {\n @Test\n fun constructorNormal() {\n val url = \"https://example.com/\".toHttpUrl()\n val body = \"hello\".toRequestBody()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val method = \"PUT\"\n val request =\n Request(\n url = url,\n headers = headers,\n method = method,\n body = body,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(method)\n assertThat(request.body).isEqualTo(body)\n assertThat(request.tags).isEqualTo(EmptyTags)\n }\n\n @Test\n fun constructorNoBodyNoMethod() {\n val url = \"https://example.com/\".toHttpUrl()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val request =\n Request(\n url = url,\n headers = headers,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(\"GET\")\n assertThat(request.body).isNull()\n assertThat(request.tags).isEqualTo(EmptyTags)\n }\n\n @Test\n fun constructorNoMethod() {\n val url = \"https://example.com/\".toHttpUrl()\n val body = \"hello\".toRequestBod"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":33,"symbol":"constructorNormal","kind":"function","lang":"kotlin","code":"@Test\n fun constructorNormal() {\n val url = \"https://example.com/\".toHttpUrl()\n val body = \"hello\".toRequestBody()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val method = \"PUT\"\n val request =\n Request(\n url = url,\n headers = headers,\n method = method,\n body = body,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(method)\n assertThat(request.body).isEqualTo(body)\n assertThat(request.tags).isEqualTo(EmptyTags)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":53,"symbol":"constructorNoBodyNoMethod","kind":"function","lang":"kotlin","code":"@Test\n fun constructorNoBodyNoMethod() {\n val url = \"https://example.com/\".toHttpUrl()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val request =\n Request(\n url = url,\n headers = headers,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(\"GET\")\n assertThat(request.body).isNull()\n assertThat(request.tags).isEqualTo(EmptyTags)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":69,"symbol":"constructorNoMethod","kind":"function","lang":"kotlin","code":"@Test\n fun constructorNoMethod() {\n val url = \"https://example.com/\".toHttpUrl()\n val body = \"hello\".toRequestBody()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val request =\n Request(\n url = url,\n headers = headers,\n body = body,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(\"POST\")\n assertThat(request.body).isEqualTo(body)\n assertThat(request.tags).isEqualTo(EmptyTags)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":87,"symbol":"constructorNoBody","kind":"function","lang":"kotlin","code":"@Test\n fun constructorNoBody() {\n val url = \"https://example.com/\".toHttpUrl()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val method = \"DELETE\"\n val request =\n Request(\n url = url,\n headers = headers,\n method = method,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(method)\n assertThat(request.body).isNull()\n assertThat(request.tags).isEqualTo(EmptyTags)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":105,"symbol":"newBuilderUrlResetsUrl","kind":"function","lang":"kotlin","code":"@Test\n fun newBuilderUrlResetsUrl() {\n val requestWithoutCache = Request.Builder().url(\"http://localhost/api\").build()\n val builtRequestWithoutCache = requestWithoutCache.newBuilder().url(\"http://localhost/api/foo\").build()\n assertThat(builtRequestWithoutCache.url).isEqualTo(\n \"http://localhost/api/foo\".toHttpUrl(),\n )\n val requestWithCache =\n Request\n .Builder()\n .url(\"http://localhost/api\")\n .build()\n // cache url object\n requestWithCache.url\n val builtRequestWithCache =\n requestWithCache\n .newBuilder()\n .url(\"http://localhost/api/foo\")\n .build()\n assertThat(builtRequestWithCache.url)\n .isEqualTo(\"http://localhost/api/foo\".toHttpUrl())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":128,"symbol":"cacheControl","kind":"function","lang":"kotlin","code":"@Test\n fun cacheControl() {\n val request =\n Request\n .Builder()\n .cacheControl(CacheControl.Builder().noCache().build())\n .url(\"https://square.com\")\n .build()\n assertThat(request.headers(\"Cache-Control\")).containsExactly(\"no-cache\")\n assertThat(request.cacheControl.noCache).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":140,"symbol":"emptyCacheControlClearsAllCacheControlHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun emptyCacheControlClearsAllCacheControlHeaders() {\n val request =\n Request\n .Builder()\n .header(\"Cache-Control\", \"foo\")\n .cacheControl(CacheControl.Builder().build())\n .url(\"https://square.com\")\n .build()\n assertThat(request.headers(\"Cache-Control\")).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":152,"symbol":"headerAcceptsPermittedCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun headerAcceptsPermittedCharacters() {\n val builder = Request.Builder()\n builder.header(\"AZab09~\", \"AZab09 ~\")\n builder.addHeader(\"AZab09~\", \"AZab09 ~\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":159,"symbol":"emptyNameForbidden","kind":"function","lang":"kotlin","code":"@Test\n fun emptyNameForbidden() {\n val builder = Request.Builder()\n assertFailsWith {\n builder.header(\"\", \"Value\")\n }\n assertFailsWith {\n builder.addHeader(\"\", \"Value\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":170,"symbol":"headerAllowsTabOnlyInValues","kind":"function","lang":"kotlin","code":"@Test\n fun headerAllowsTabOnlyInValues() {\n val builder = Request.Builder()\n builder.header(\"key\", \"sample\\tvalue\")\n assertFailsWith {\n builder.header(\"sample\\tkey\", \"value\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":179,"symbol":"headerForbidsControlCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun headerForbidsControlCharacters() {\n assertForbiddenHeader(\"\\u0000\")\n assertForbiddenHeader(\"\\r\")\n assertForbiddenHeader(\"\\n\")\n assertForbiddenHeader(\"\\u001f\")\n assertForbiddenHeader(\"\\u007f\")\n assertForbiddenHeader(\"\\u0080\")\n assertForbiddenHeader(\"\\ud83c\\udf69\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":190,"symbol":"assertForbiddenHeader","kind":"function","lang":"kotlin","code":"private fun assertForbiddenHeader(s: String) {\n val builder = Request.Builder()\n assertFailsWith {\n builder.header(s, \"Value\")\n }\n assertFailsWith {\n builder.addHeader(s, \"Value\")\n }\n assertFailsWith {\n builder.header(\"Name\", s)\n }\n assertFailsWith {\n builder.addHeader(\"Name\", s)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":206,"symbol":"noTag","kind":"function","lang":"kotlin","code":"@Test\n fun noTag() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .build()\n assertThat(request.tag()).isNull()\n assertThat(request.tag(Any::class)).isNull()\n assertThat(request.tag(String::class)).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag()).isNull()\n assertThat(request.tag(String::class)).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":222,"symbol":"defaultTag","kind":"function","lang":"kotlin","code":"@Test\n fun defaultTag() {\n val tag = \"1234\"\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(tag as Any)\n .build()\n assertThat(request.tag()).isSameInstanceAs(tag)\n assertThat(request.tag(Any::class)).isSameInstanceAs(tag)\n assertThat(request.tag(String::class)).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag()).isSameInstanceAs(tag)\n assertThat(request.tag(Any::class)).isSameInstanceAs(tag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":240,"symbol":"nullRemovesTag","kind":"function","lang":"kotlin","code":"@Test\n fun nullRemovesTag() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(\"a\" as Any)\n .tag(null)\n .build()\n assertThat(request.tag()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":252,"symbol":"removeAbsentTag","kind":"function","lang":"kotlin","code":"@Test\n fun removeAbsentTag() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(null)\n .build()\n assertThat(request.tag()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":263,"symbol":"objectTag","kind":"function","lang":"kotlin","code":"@Test\n fun objectTag() {\n val tag = \"1234\"\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(Any::class, tag)\n .build()\n assertThat(request.tag()).isSameInstanceAs(tag)\n assertThat(request.tag(Any::class)).isSameInstanceAs(tag)\n assertThat(request.tag(String::class)).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag(Any::class)).isSameInstanceAs(tag)\n assertThat(request.tag()).isSameInstanceAs(tag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":281,"symbol":"kotlinReifiedTag","kind":"function","lang":"kotlin","code":"@Test\n fun kotlinReifiedTag() {\n val uuidTag = \"1234\"\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(uuidTag) // Use the type parameter.\n .build()\n assertThat(request.tag()).isSameInstanceAs(\"1234\")\n assertThat(request.tag()).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag(String::class)).isSameInstanceAs(uuidTag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":297,"symbol":"kotlinClassTag","kind":"function","lang":"kotlin","code":"@Test\n fun kotlinClassTag() {\n val uuidTag = \"1234\"\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(String::class, uuidTag) // Use the KClass<*> parameter.\n .build()\n assertThat(request.tag(Any::class)).isNull()\n assertThat(request.tag(String::class)).isSameInstanceAs(\"1234\")\n\n // Alternate access APIs also work.\n assertThat(request.tag(String::class)).isSameInstanceAs(uuidTag)\n assertThat(request.tag()).isSameInstanceAs(uuidTag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":314,"symbol":"replaceOnlyTag","kind":"function","lang":"kotlin","code":"@Test\n fun replaceOnlyTag() {\n val uuidTag1 = \"1234\"\n val uuidTag2 = \"4321\"\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(String::class, uuidTag1)\n .tag(String::class, uuidTag2)\n .build()\n assertThat(request.tag(String::class)).isSameInstanceAs(uuidTag2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":328,"symbol":"multipleTags","kind":"function","lang":"kotlin","code":"@Test\n fun multipleTags() {\n val stringTag = \"dilophosaurus\"\n val longTag = 20170815L as Long?\n val objectTag = Any()\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(Any::class, objectTag)\n .tag(String::class, stringTag)\n .tag(Long::class, longTag)\n .build()\n assertThat(request.tag()).isSameInstanceAs(objectTag)\n assertThat(request.tag(Any::class)).isSameInstanceAs(objectTag)\n assertThat(request.tag(String::class)).isSameInstanceAs(stringTag)\n\n // TODO check for Jvm or handle Long/long correctly\n// assertThat(request.tag(Long::class)).isSameAs(longTag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":350,"symbol":"tagsAreImmutable","kind":"function","lang":"kotlin","doc":"Confirm that we don't accidentally share the backing map between objects.","code":"@Test\n fun tagsAreImmutable() {\n val builder =\n Request\n .Builder()\n .url(\"https://square.com\")\n val requestA = builder.tag(String::class, \"a\").build()\n val requestB = builder.tag(String::class, \"b\").build()\n val requestC = requestA.newBuilder().tag(String::class, \"c\").build()\n assertThat(requestA.tag(String::class)).isSameInstanceAs(\"a\")\n assertThat(requestB.tag(String::class)).isSameInstanceAs(\"b\")\n assertThat(requestC.tag(String::class)).isSameInstanceAs(\"c\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestCommonTest.kt","line":364,"symbol":"requestToStringRedactsSensitiveHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun requestToStringRedactsSensitiveHeaders() {\n val headers =\n Headers\n .Builder()\n .add(\"content-length\", \"99\")\n .add(\"authorization\", \"peanutbutter\")\n .add(\"proxy-authorization\", \"chocolate\")\n .add(\"cookie\", \"drink=coffee\")\n .add(\"set-cookie\", \"accessory=sugar\")\n .add(\"user-agent\", \"OkHttp\")\n .build()\n val request =\n Request(\n \"https://square.com\".toHttpUrl(),\n headers,\n )\n assertThat(request.toString()).isEqualTo(\n \"Request{method=GET, url=https://square.com/, headers=[\" +\n \"content-length:99,\" +\n \" authorization:██,\" +\n \" proxy-authorization:██,\" +\n \" cookie:██,\" +\n \" set-cookie:██,\" +\n \" user-agent:OkHttp\" +\n \"]}\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":46,"symbol":"constructor","kind":"function","lang":"kotlin","code":"@Test\n fun constructor() {\n val url = \"https://example.com/\".toHttpUrl()\n val body = \"hello\".toRequestBody()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val method = \"PUT\"\n val request =\n Request(\n url = url,\n headers = headers,\n method = method,\n body = body,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(method)\n assertThat(request.body).isEqualTo(body)\n assertThat(request.tags).isEqualTo(EmptyTags)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":66,"symbol":"constructorNoBodyNoMethod","kind":"function","lang":"kotlin","code":"@Test\n fun constructorNoBodyNoMethod() {\n val url = \"https://example.com/\".toHttpUrl()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val request =\n Request(\n url = url,\n headers = headers,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(\"GET\")\n assertThat(request.body).isNull()\n assertThat(request.tags).isEqualTo(EmptyTags)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":82,"symbol":"constructorNoMethod","kind":"function","lang":"kotlin","code":"@Test\n fun constructorNoMethod() {\n val url = \"https://example.com/\".toHttpUrl()\n val body = \"hello\".toRequestBody()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val request =\n Request(\n url = url,\n headers = headers,\n body = body,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(\"POST\")\n assertThat(request.body).isEqualTo(body)\n assertThat(request.tags).isEqualTo(EmptyTags)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":100,"symbol":"constructorNoBody","kind":"function","lang":"kotlin","code":"@Test\n fun constructorNoBody() {\n val url = \"https://example.com/\".toHttpUrl()\n val headers = headersOf(\"User-Agent\", \"RequestTest\")\n val method = \"DELETE\"\n val request =\n Request(\n url = url,\n headers = headers,\n method = method,\n )\n assertThat(request.url).isEqualTo(url)\n assertThat(request.headers).isEqualTo(headers)\n assertThat(request.method).isEqualTo(method)\n assertThat(request.body).isNull()\n assertThat(request.tags).isEqualTo(EmptyTags)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":118,"symbol":"string","kind":"function","lang":"kotlin","code":"@Test\n fun string() {\n val contentType = \"text/plain; charset=utf-8\".toMediaType()\n val body = \"abc\".toByteArray().toRequestBody(contentType)\n assertThat(body.contentType()).isEqualTo(contentType)\n assertThat(body.contentLength()).isEqualTo(3)\n assertThat(bodyToHex(body)).isEqualTo(\"616263\")\n assertThat(bodyToHex(body), \"Retransmit body\").isEqualTo(\"616263\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":128,"symbol":"stringWithDefaultCharsetAdded","kind":"function","lang":"kotlin","code":"@Test\n fun stringWithDefaultCharsetAdded() {\n val contentType = \"text/plain\".toMediaType()\n val body = \"\\u0800\".toRequestBody(contentType)\n assertThat(body.contentType()).isEqualTo(\"text/plain; charset=utf-8\".toMediaType())\n assertThat(body.contentLength()).isEqualTo(3)\n assertThat(bodyToHex(body)).isEqualTo(\"e0a080\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":137,"symbol":"stringWithNonDefaultCharsetSpecified","kind":"function","lang":"kotlin","code":"@Test\n fun stringWithNonDefaultCharsetSpecified() {\n val contentType = \"text/plain; charset=utf-16be\".toMediaType()\n val body = \"\\u0800\".toRequestBody(contentType)\n assertThat(body.contentType()).isEqualTo(contentType)\n assertThat(body.contentLength()).isEqualTo(2)\n assertThat(bodyToHex(body)).isEqualTo(\"0800\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":146,"symbol":"byteArray","kind":"function","lang":"kotlin","code":"@Test\n fun byteArray() {\n val contentType = \"text/plain\".toMediaType()\n val body: RequestBody = \"abc\".toByteArray().toRequestBody(contentType)\n assertThat(body.contentType()).isEqualTo(contentType)\n assertThat(body.contentLength()).isEqualTo(3)\n assertThat(bodyToHex(body)).isEqualTo(\"616263\")\n assertThat(bodyToHex(body), \"Retransmit body\").isEqualTo(\"616263\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":156,"symbol":"byteArrayRange","kind":"function","lang":"kotlin","code":"@Test\n fun byteArrayRange() {\n val contentType = \"text/plain\".toMediaType()\n val body: RequestBody = \".abcd\".toByteArray().toRequestBody(contentType, 1, 3)\n assertThat(body.contentType()).isEqualTo(contentType)\n assertThat(body.contentLength()).isEqualTo(3)\n assertThat(bodyToHex(body)).isEqualTo(\"616263\")\n assertThat(bodyToHex(body), \"Retransmit body\").isEqualTo(\"616263\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":166,"symbol":"byteString","kind":"function","lang":"kotlin","code":"@Test\n fun byteString() {\n val contentType = \"text/plain\".toMediaType()\n val body: RequestBody = \"Hello\".encodeUtf8().toRequestBody(contentType)\n assertThat(body.contentType()).isEqualTo(contentType)\n assertThat(body.contentLength()).isEqualTo(5)\n assertThat(bodyToHex(body)).isEqualTo(\"48656c6c6f\")\n assertThat(bodyToHex(body), \"Retransmit body\").isEqualTo(\"48656c6c6f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":176,"symbol":"file","kind":"function","lang":"kotlin","code":"@Test\n fun file() {\n val file = File.createTempFile(\"RequestTest\", \"tmp\")\n val writer = FileWriter(file)\n writer.write(\"abc\")\n writer.close()\n val contentType = \"text/plain\".toMediaType()\n val body: RequestBody = file.asRequestBody(contentType)\n assertThat(body.contentType()).isEqualTo(contentType)\n assertThat(body.contentLength()).isEqualTo(3)\n assertThat(bodyToHex(body)).isEqualTo(\"616263\")\n assertThat(bodyToHex(body), \"Retransmit body\").isEqualTo(\"616263\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":191,"symbol":"crudVerbs","kind":"function","lang":"kotlin","doc":"Common verbs used for apis such as GitHub, AWS, and Google Cloud.","code":"@Test\n fun crudVerbs() {\n val contentType = \"application/json\".toMediaType()\n val body = \"{}\".toRequestBody(contentType)\n\n val get =\n Request\n .Builder()\n .url(\"http://localhost/api\")\n .get()\n .build()\n assertThat(get.method).isEqualTo(\"GET\")\n assertThat(get.body).isNull()\n\n val head =\n Request\n .Builder()\n .url(\"http://localhost/api\")\n .head()\n .build()\n assertThat(head.method).isEqualTo(\"HEAD\")\n assertThat(head.body).isNull()\n\n val delete =\n Request\n .Builder()\n .url(\"http://localhost/api\")\n .delete()\n .build()\n assertThat(delete.method).isEqualTo(\"DELETE\")\n assertThat(delete.body!!.contentLength()).isEqualTo(0L)\n\n val post =\n Request\n .Builder()\n .url(\"http://localhost/api\")\n .post(body)\n .build()\n assertThat(post.method).isEqualTo(\"POST\")\n assertThat(post.body).isEqualTo(body)\n\n val put =\n Request\n .Builder()\n .url(\"http://localhost/api\")\n .put(body)\n .build()\n assertThat(put.method).isEqualTo(\"PUT\")\n assertThat(put.body).isEqualTo(body)\n\n val patch =\n Requ"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":260,"symbol":"uninitializedURI","kind":"function","lang":"kotlin","code":"@Test\n fun uninitializedURI() {\n val request = Request.Builder().url(\"http://localhost/api\").build()\n assertThat(request.url.toUri()).isEqualTo(URI(\"http://localhost/api\"))\n assertThat(request.url).isEqualTo(\"http://localhost/api\".toHttpUrl())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":267,"symbol":"newBuilderUrlResetsUrl","kind":"function","lang":"kotlin","code":"@Test\n fun newBuilderUrlResetsUrl() {\n val requestWithoutCache = Request.Builder().url(\"http://localhost/api\").build()\n val builtRequestWithoutCache = requestWithoutCache.newBuilder().url(\"http://localhost/api/foo\").build()\n assertThat(builtRequestWithoutCache.url).isEqualTo(\n \"http://localhost/api/foo\".toHttpUrl(),\n )\n val requestWithCache =\n Request\n .Builder()\n .url(\"http://localhost/api\")\n .build()\n // cache url object\n requestWithCache.url\n val builtRequestWithCache =\n requestWithCache\n .newBuilder()\n .url(\"http://localhost/api/foo\")\n .build()\n assertThat(builtRequestWithCache.url)\n .isEqualTo(\"http://localhost/api/foo\".toHttpUrl())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":290,"symbol":"cacheControl","kind":"function","lang":"kotlin","code":"@Test\n fun cacheControl() {\n val request =\n Request\n .Builder()\n .cacheControl(CacheControl.Builder().noCache().build())\n .url(\"https://square.com\")\n .build()\n assertThat(request.headers(\"Cache-Control\")).containsExactly(\"no-cache\")\n assertThat(request.cacheControl.noCache).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":302,"symbol":"emptyCacheControlClearsAllCacheControlHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun emptyCacheControlClearsAllCacheControlHeaders() {\n val request =\n Request\n .Builder()\n .header(\"Cache-Control\", \"foo\")\n .cacheControl(CacheControl.Builder().build())\n .url(\"https://square.com\")\n .build()\n assertThat(request.headers(\"Cache-Control\")).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":314,"symbol":"headerAcceptsPermittedCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun headerAcceptsPermittedCharacters() {\n val builder = Request.Builder()\n builder.header(\"AZab09~\", \"AZab09 ~\")\n builder.addHeader(\"AZab09~\", \"AZab09 ~\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":321,"symbol":"emptyNameForbidden","kind":"function","lang":"kotlin","code":"@Test\n fun emptyNameForbidden() {\n val builder = Request.Builder()\n assertFailsWith {\n builder.header(\"\", \"Value\")\n }\n assertFailsWith {\n builder.addHeader(\"\", \"Value\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":332,"symbol":"headerAllowsTabOnlyInValues","kind":"function","lang":"kotlin","code":"@Test\n fun headerAllowsTabOnlyInValues() {\n val builder = Request.Builder()\n builder.header(\"key\", \"sample\\tvalue\")\n assertFailsWith {\n builder.header(\"sample\\tkey\", \"value\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":341,"symbol":"headerForbidsControlCharacters","kind":"function","lang":"kotlin","code":"@Test\n fun headerForbidsControlCharacters() {\n assertForbiddenHeader(\"\\u0000\")\n assertForbiddenHeader(\"\\r\")\n assertForbiddenHeader(\"\\n\")\n assertForbiddenHeader(\"\\u001f\")\n assertForbiddenHeader(\"\\u007f\")\n assertForbiddenHeader(\"\\u0080\")\n assertForbiddenHeader(\"\\ud83c\\udf69\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":352,"symbol":"assertForbiddenHeader","kind":"function","lang":"kotlin","code":"private fun assertForbiddenHeader(s: String) {\n val builder = Request.Builder()\n assertFailsWith {\n builder.header(s, \"Value\")\n }\n assertFailsWith {\n builder.addHeader(s, \"Value\")\n }\n assertFailsWith {\n builder.header(\"Name\", s)\n }\n assertFailsWith {\n builder.addHeader(\"Name\", s)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":368,"symbol":"noTag","kind":"function","lang":"kotlin","code":"@Test\n fun noTag() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .build()\n assertThat(request.tag()).isNull()\n assertThat(request.tag(Any::class.java)).isNull()\n assertThat(request.tag(UUID::class.java)).isNull()\n assertThat(request.tag(String::class.java)).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag()).isNull()\n assertThat(request.tag(String::class)).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":385,"symbol":"defaultTag","kind":"function","lang":"kotlin","code":"@Test\n fun defaultTag() {\n val tag = UUID.randomUUID()\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(tag)\n .build()\n assertThat(request.tag()).isSameInstanceAs(tag)\n assertThat(request.tag(Any::class.java)).isSameInstanceAs(tag)\n assertThat(request.tag(UUID::class.java)).isNull()\n assertThat(request.tag(String::class.java)).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag()).isSameInstanceAs(tag)\n assertThat(request.tag(Any::class)).isSameInstanceAs(tag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":404,"symbol":"nullRemovesTag","kind":"function","lang":"kotlin","code":"@Test\n fun nullRemovesTag() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(\"a\")\n .tag(null)\n .build()\n assertThat(request.tag()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":416,"symbol":"removeAbsentTag","kind":"function","lang":"kotlin","code":"@Test\n fun removeAbsentTag() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(null)\n .build()\n assertThat(request.tag()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":427,"symbol":"objectTag","kind":"function","lang":"kotlin","code":"@Test\n fun objectTag() {\n val tag = UUID.randomUUID()\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(Any::class.java, tag)\n .build()\n assertThat(request.tag()).isSameInstanceAs(tag)\n assertThat(request.tag(Any::class.java)).isSameInstanceAs(tag)\n assertThat(request.tag(UUID::class.java)).isNull()\n assertThat(request.tag(String::class.java)).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag(Any::class)).isSameInstanceAs(tag)\n assertThat(request.tag()).isSameInstanceAs(tag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":446,"symbol":"javaClassTag","kind":"function","lang":"kotlin","code":"@Test\n fun javaClassTag() {\n val uuidTag = UUID.randomUUID()\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(UUID::class.java, uuidTag) // Use the Class<*> parameter.\n .build()\n assertThat(request.tag()).isNull()\n assertThat(request.tag(Any::class.java)).isNull()\n assertThat(request.tag(UUID::class.java)).isSameInstanceAs(uuidTag)\n assertThat(request.tag(String::class.java)).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag(UUID::class)).isSameInstanceAs(uuidTag)\n assertThat(request.tag()).isSameInstanceAs(uuidTag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":465,"symbol":"kotlinReifiedTag","kind":"function","lang":"kotlin","code":"@Test\n fun kotlinReifiedTag() {\n val uuidTag = UUID.randomUUID()\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(uuidTag) // Use the type parameter.\n .build()\n assertThat(request.tag()).isNull()\n assertThat(request.tag()).isNull()\n assertThat(request.tag()).isSameInstanceAs(uuidTag)\n assertThat(request.tag()).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag(UUID::class.java)).isSameInstanceAs(uuidTag)\n assertThat(request.tag(UUID::class)).isSameInstanceAs(uuidTag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":484,"symbol":"kotlinClassTag","kind":"function","lang":"kotlin","code":"@Test\n fun kotlinClassTag() {\n val uuidTag = UUID.randomUUID()\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(UUID::class, uuidTag) // Use the KClass<*> parameter.\n .build()\n assertThat(request.tag()).isNull()\n assertThat(request.tag(Any::class)).isNull()\n assertThat(request.tag(UUID::class)).isSameInstanceAs(uuidTag)\n assertThat(request.tag(String::class)).isNull()\n\n // Alternate access APIs also work.\n assertThat(request.tag(UUID::class.java)).isSameInstanceAs(uuidTag)\n assertThat(request.tag()).isSameInstanceAs(uuidTag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":503,"symbol":"replaceOnlyTag","kind":"function","lang":"kotlin","code":"@Test\n fun replaceOnlyTag() {\n val uuidTag1 = UUID.randomUUID()\n val uuidTag2 = UUID.randomUUID()\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(UUID::class.java, uuidTag1)\n .tag(UUID::class.java, uuidTag2)\n .build()\n assertThat(request.tag(UUID::class.java)).isSameInstanceAs(uuidTag2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":517,"symbol":"multipleTags","kind":"function","lang":"kotlin","code":"@Test\n fun multipleTags() {\n val uuidTag = UUID.randomUUID()\n val stringTag = \"dilophosaurus\"\n val longTag = 20170815L as Long?\n val objectTag = Any()\n val request =\n Request\n .Builder()\n .url(\"https://square.com\")\n .tag(Any::class.java, objectTag)\n .tag(UUID::class.java, uuidTag)\n .tag(String::class.java, stringTag)\n .tag(Long::class.javaObjectType, longTag)\n .build()\n assertThat(request.tag()).isSameInstanceAs(objectTag)\n assertThat(request.tag(Any::class.java)).isSameInstanceAs(objectTag)\n assertThat(request.tag(UUID::class.java)).isSameInstanceAs(uuidTag)\n assertThat(request.tag(String::class.java)).isSameInstanceAs(stringTag)\n assertThat(request.tag(Long::class.javaObjectType)).isSameInstanceAs(longTag)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":540,"symbol":"tagsAreImmutable","kind":"function","lang":"kotlin","doc":"Confirm that we don't accidentally share the backing map between objects.","code":"@Test\n fun tagsAreImmutable() {\n val builder =\n Request\n .Builder()\n .url(\"https://square.com\")\n val requestA = builder.tag(String::class.java, \"a\").build()\n val requestB = builder.tag(String::class.java, \"b\").build()\n val requestC = requestA.newBuilder().tag(String::class.java, \"c\").build()\n assertThat(requestA.tag(String::class.java)).isSameInstanceAs(\"a\")\n assertThat(requestB.tag(String::class.java)).isSameInstanceAs(\"b\")\n assertThat(requestC.tag(String::class.java)).isSameInstanceAs(\"c\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":554,"symbol":"requestToStringRedactsSensitiveHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun requestToStringRedactsSensitiveHeaders() {\n val headers =\n Headers\n .Builder()\n .add(\"content-length\", \"99\")\n .add(\"authorization\", \"peanutbutter\")\n .add(\"proxy-authorization\", \"chocolate\")\n .add(\"cookie\", \"drink=coffee\")\n .add(\"set-cookie\", \"accessory=sugar\")\n .add(\"user-agent\", \"OkHttp\")\n .build()\n val request =\n Request(\n \"https://square.com\".toHttpUrl(),\n headers,\n )\n assertThat(request.toString()).isEqualTo(\n \"Request{method=GET, url=https://square.com/, headers=[\" +\n \"content-length:99,\" +\n \" authorization:██,\" +\n \" proxy-authorization:██,\" +\n \" cookie:██,\" +\n \" set-cookie:██,\" +\n \" user-agent:OkHttp\" +\n \"]}\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":583,"symbol":"requestToStringIncludesTags","kind":"function","lang":"kotlin","code":"@Test\n fun requestToStringIncludesTags() {\n val request =\n Request\n .Builder()\n .url(\"https://square.com/\".toHttpUrl())\n .tag(\"hello\")\n .tag(5)\n .build()\n assertThat(request.toString()).isEqualTo(\n \"Request{method=GET, url=https://square.com/, tags={\" +\n \"class kotlin.String=hello, \" +\n \"class kotlin.Int=5\" +\n \"}}\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":600,"symbol":"gzip","kind":"function","lang":"kotlin","code":"@Test\n fun gzip() {\n val mediaType = \"text/plain; charset=utf-8\".toMediaType()\n val originalBody = \"This is the original message\".toRequestBody(mediaType)\n assertThat(originalBody.contentLength()).isEqualTo(28L)\n assertThat(originalBody.contentType()).isEqualTo(mediaType)\n\n val request =\n Request\n .Builder()\n .url(\"https://square.com/\")\n .post(originalBody)\n .gzip()\n .build()\n assertThat(request.headers[\"Content-Encoding\"]).isEqualTo(\"gzip\")\n assertThat(request.body?.contentLength()).isEqualTo(-1L)\n assertThat(request.body?.contentType()).isEqualTo(mediaType)\n\n val requestBodyBytes =\n Buffer()\n .apply {\n request.body?.writeTo(this)\n }\n\n val decompressedRequestBody =\n GzipSource(requestBodyBytes).use {\n it.buffer().readUtf8()\n }\n assertThat(decompressedRequestBody).isEqualTo(\"This is the original message\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":631,"symbol":"cannotGzipWithoutABody","kind":"function","lang":"kotlin","code":"@Test\n fun cannotGzipWithoutABody() {\n assertFailsWith {\n Request\n .Builder()\n .url(\"https://square.com/\")\n .gzip()\n .build()\n }.also {\n assertThat(it).hasMessage(\"cannot gzip a request that has no body\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":644,"symbol":"cannotGzipWithAnotherContentEncoding","kind":"function","lang":"kotlin","code":"@Test\n fun cannotGzipWithAnotherContentEncoding() {\n assertFailsWith {\n Request\n .Builder()\n .url(\"https://square.com/\")\n .post(\"This is the original message\".toRequestBody())\n .addHeader(\"Content-Encoding\", \"deflate\")\n .gzip()\n .build()\n }.also {\n assertThat(it).hasMessage(\"Content-Encoding already set: deflate\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":659,"symbol":"cannotGzipTwice","kind":"function","lang":"kotlin","code":"@Test\n fun cannotGzipTwice() {\n assertFailsWith {\n Request\n .Builder()\n .url(\"https://square.com/\")\n .post(\"This is the original message\".toRequestBody())\n .gzip()\n .gzip()\n .build()\n }.also {\n assertThat(it).hasMessage(\"Content-Encoding already set: gzip\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":674,"symbol":"curlGet","kind":"function","lang":"kotlin","code":"@Test\n fun curlGet() {\n val request =\n Request\n .Builder()\n .url(\"https://example.com\")\n .header(\"Authorization\", \"Bearer abc123\")\n .build()\n\n val curl = request.toCurl()\n assertThat(curl)\n .isEqualTo(\n \"\"\"\n |curl 'https://example.com/' \\\n | -H 'Authorization: Bearer abc123'\n \"\"\".trimMargin(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":693,"symbol":"curlPostWithBody","kind":"function","lang":"kotlin","code":"@Test\n fun curlPostWithBody() {\n val body = \"{\\\"key\\\":\\\"value\\\"}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":738,"symbol":"requestContentTypeIsFallback","kind":"function","lang":"kotlin","code":"@Test\n fun requestContentTypeIsFallback() {\n val body = \"{\\\"key\\\":\\\"value\\\"}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":761,"symbol":"curlPutWithBody","kind":"function","lang":"kotlin","doc":"Put is not the default method so `-X 'PUT'` is included.","code":"@Test\n fun curlPutWithBody() {\n val body = \"{\\\"key\\\":\\\"value\\\"}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":785,"symbol":"curlPostWithComplexBody","kind":"function","lang":"kotlin","code":"@Test\n fun curlPostWithComplexBody() {\n val jsonBody =\n \"\"\"\n |{\n | \"user\": {\n | \"id\": 123,\n | \"name\": \"Tim O'Reilly\"\n | },\n | \"roles\": [\"admin\", \"editor\"],\n | \"active\": true\n |}\n |\n \"\"\".trimMargin()\n\n val body = jsonBody.toRequestBody(\"application/json\".toMediaType())\n\n val request =\n Request\n .Builder()\n .url(\"https://api.example.com/users\")\n .post(body)\n .addHeader(\"Authorization\", \"Bearer xyz789\")\n .build()\n\n assertThat(request.toCurl())\n .isEqualTo(\n \"\"\"\n |curl 'https://api.example.com/users' \\\n | -H 'Authorization: Bearer xyz789' \\\n | -H 'Content-Type: application/json; charset=utf-8' \\\n | --data '{\n | \"user\": {\n | \"id\": 123,\n | \"name\": \"Tim O'\\''Reilly\"\n | },\n | \"roles\": [\"admin\", \"editor\"],\n | \"active\": true\n |}\n |'\n \"\"\".trimMargin(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":829,"symbol":"curlPostWithBinaryBody","kind":"function","lang":"kotlin","code":"@Test\n fun curlPostWithBinaryBody() {\n val binaryData = \"00010203\".decodeHex()\n val body = binaryData.toRequestBody(\"application/octet-stream\".toMediaType())\n\n val request =\n Request\n .Builder()\n .url(\"https://api.example.com/upload\")\n .post(body)\n .build()\n\n val curl = request.toCurl()\n assertThat(curl)\n .isEqualTo(\n \"\"\"\n |curl 'https://api.example.com/upload' \\\n | -H 'Content-Type: application/octet-stream' \\\n | --data-binary '00010203'\n \"\"\".trimMargin(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":852,"symbol":"curlPostWithBinaryBodyOmitted","kind":"function","lang":"kotlin","code":"@Test\n fun curlPostWithBinaryBodyOmitted() {\n val binaryData = \"1020\".decodeHex()\n val body = binaryData.toRequestBody(\"application/octet-stream\".toMediaType())\n\n val request =\n Request\n .Builder()\n .url(\"https://api.example.com/upload\")\n .post(body)\n .build()\n\n val curl = request.toCurl(includeBody = false)\n assertThat(curl)\n .isEqualTo(\n \"\"\"\n |curl 'https://api.example.com/upload' \\\n | -X 'POST' \\\n | -H 'Content-Type: application/octet-stream'\n \"\"\".trimMargin(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RequestTest.kt","line":875,"symbol":"bodyToHex","kind":"function","lang":"kotlin","code":"private fun bodyToHex(body: RequestBody): String {\n val buffer = Buffer()\n body.writeTo(buffer)\n return buffer.readByteString().hex()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":38,"symbol":"ResponseBodyJvmTest","kind":"class","lang":"kotlin","code":"class ResponseBodyJvmTest {\n @Test\n fun stringEmpty() {\n val body = body(\"\")\n assertThat(body.string()).isEqualTo(\"\")\n }\n\n @Test\n fun stringLooksLikeBomButTooShort() {\n val body = body(\"000048\")\n assertThat(body.string()).isEqualTo(\"\\u0000\\u0000H\")\n }\n\n @Test\n fun stringDefaultsToUtf8() {\n val body = body(\"68656c6c6f\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }\n\n @Test\n fun stringExplicitCharset() {\n val body = body(\"00000068000000650000006c0000006c0000006f\", \"utf-32be\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }\n\n @Test\n fun stringBomOverridesExplicitCharset() {\n val body = body(\"0000feff00000068000000650000006c0000006c0000006f\", \"utf-8\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }\n\n @Test\n fun stringBomUtf8() {\n val body = body(\"efbbbf68656c6c6f\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }\n\n @Test\n fun stringBomUtf16Be() {\n val body = body(\"feff00680065006c006c006f\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }\n\n @Test\n fun stringBomUtf16Le() {\n val body = body(\"fffe680065006c006c006f00\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }\n\n @Test\n fun stringBomUtf32Be() {\n val bo"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":39,"symbol":"stringEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun stringEmpty() {\n val body = body(\"\")\n assertThat(body.string()).isEqualTo(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":45,"symbol":"stringLooksLikeBomButTooShort","kind":"function","lang":"kotlin","code":"@Test\n fun stringLooksLikeBomButTooShort() {\n val body = body(\"000048\")\n assertThat(body.string()).isEqualTo(\"\\u0000\\u0000H\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":51,"symbol":"stringDefaultsToUtf8","kind":"function","lang":"kotlin","code":"@Test\n fun stringDefaultsToUtf8() {\n val body = body(\"68656c6c6f\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":57,"symbol":"stringExplicitCharset","kind":"function","lang":"kotlin","code":"@Test\n fun stringExplicitCharset() {\n val body = body(\"00000068000000650000006c0000006c0000006f\", \"utf-32be\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":63,"symbol":"stringBomOverridesExplicitCharset","kind":"function","lang":"kotlin","code":"@Test\n fun stringBomOverridesExplicitCharset() {\n val body = body(\"0000feff00000068000000650000006c0000006c0000006f\", \"utf-8\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":69,"symbol":"stringBomUtf8","kind":"function","lang":"kotlin","code":"@Test\n fun stringBomUtf8() {\n val body = body(\"efbbbf68656c6c6f\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":75,"symbol":"stringBomUtf16Be","kind":"function","lang":"kotlin","code":"@Test\n fun stringBomUtf16Be() {\n val body = body(\"feff00680065006c006c006f\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":81,"symbol":"stringBomUtf16Le","kind":"function","lang":"kotlin","code":"@Test\n fun stringBomUtf16Le() {\n val body = body(\"fffe680065006c006c006f00\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":87,"symbol":"stringBomUtf32Be","kind":"function","lang":"kotlin","code":"@Test\n fun stringBomUtf32Be() {\n val body = body(\"0000feff00000068000000650000006c0000006c0000006f\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":93,"symbol":"stringBomUtf32Le","kind":"function","lang":"kotlin","code":"@Test\n fun stringBomUtf32Le() {\n val body = body(\"fffe000068000000650000006c0000006c0000006f000000\")\n assertThat(body.string()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":99,"symbol":"stringClosesUnderlyingSource","kind":"function","lang":"kotlin","code":"@Test\n fun stringClosesUnderlyingSource() {\n val closed = AtomicBoolean()\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }\n }\n assertThat(body.string()).isEqualTo(\"hello\")\n assertThat(closed.get()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":104,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":106,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = 5"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":108,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":111,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":123,"symbol":"readerEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun readerEmpty() {\n val body = body(\"\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":129,"symbol":"readerLooksLikeBomButTooShort","kind":"function","lang":"kotlin","code":"@Test\n fun readerLooksLikeBomButTooShort() {\n val body = body(\"000048\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"\\u0000\\u0000H\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":135,"symbol":"readerDefaultsToUtf8","kind":"function","lang":"kotlin","code":"@Test\n fun readerDefaultsToUtf8() {\n val body = body(\"68656c6c6f\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":141,"symbol":"readerExplicitCharset","kind":"function","lang":"kotlin","code":"@Test\n fun readerExplicitCharset() {\n val body = body(\"00000068000000650000006c0000006c0000006f\", \"utf-32be\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":147,"symbol":"readerBomUtf8","kind":"function","lang":"kotlin","code":"@Test\n fun readerBomUtf8() {\n val body = body(\"efbbbf68656c6c6f\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":153,"symbol":"readerBomUtf16Be","kind":"function","lang":"kotlin","code":"@Test\n fun readerBomUtf16Be() {\n val body = body(\"feff00680065006c006c006f\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":159,"symbol":"readerBomUtf16Le","kind":"function","lang":"kotlin","code":"@Test\n fun readerBomUtf16Le() {\n val body = body(\"fffe680065006c006c006f00\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":165,"symbol":"readerBomUtf32Be","kind":"function","lang":"kotlin","code":"@Test\n fun readerBomUtf32Be() {\n val body = body(\"0000feff00000068000000650000006c0000006c0000006f\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":171,"symbol":"readerBomUtf32Le","kind":"function","lang":"kotlin","code":"@Test\n fun readerBomUtf32Le() {\n val body = body(\"fffe000068000000650000006c0000006c0000006f000000\")\n assertThat(exhaust(body.charStream())).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":177,"symbol":"readerClosedBeforeBomClosesUnderlyingSource","kind":"function","lang":"kotlin","code":"@Test\n fun readerClosedBeforeBomClosesUnderlyingSource() {\n val closed = AtomicBoolean()\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n val body = body(\"fffe680065006c006c006f00\")\n return object : ForwardingSource(body.source()) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }\n }\n body.charStream().close()\n assertThat(closed.get()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":182,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":184,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = 5"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":186,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource {\n val body = body(\"fffe680065006c006c006f00\")\n return object : ForwardingSource(body.source()) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":189,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":201,"symbol":"readerClosedAfterBomClosesUnderlyingSource","kind":"function","lang":"kotlin","code":"@Test\n fun readerClosedAfterBomClosesUnderlyingSource() {\n val closed = AtomicBoolean()\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n val body = body(\"fffe680065006c006c006f00\")\n return object : ForwardingSource(body.source()) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }\n }\n val reader = body.charStream()\n assertThat(reader.read()).isEqualTo('h'.code)\n reader.close()\n assertThat(closed.get()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":206,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":208,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = 5"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":210,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource {\n val body = body(\"fffe680065006c006c006f00\")\n return object : ForwardingSource(body.source()) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":213,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":227,"symbol":"sourceSeesBom","kind":"function","lang":"kotlin","code":"@Test\n fun sourceSeesBom() {\n val body = \"efbbbf68656c6c6f\".decodeHex().toResponseBody()\n val source = body.source()\n assertThat(source.readByte() and 0xff).isEqualTo(0xef)\n assertThat(source.readByte() and 0xff).isEqualTo(0xbb)\n assertThat(source.readByte() and 0xff).isEqualTo(0xbf)\n assertThat(source.readUtf8()).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":237,"symbol":"bytesEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun bytesEmpty() {\n val body = body(\"\")\n assertThat(body.bytes().size).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":243,"symbol":"bytesSeesBom","kind":"function","lang":"kotlin","code":"@Test\n fun bytesSeesBom() {\n val body = body(\"efbbbf68656c6c6f\")\n val bytes = body.bytes()\n assertThat(bytes[0] and 0xff).isEqualTo(0xef)\n assertThat(bytes[1] and 0xff).isEqualTo(0xbb)\n assertThat(bytes[2] and 0xff).isEqualTo(0xbf)\n assertThat(String(bytes, 3, 5, StandardCharsets.UTF_8)).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":253,"symbol":"bytesClosesUnderlyingSource","kind":"function","lang":"kotlin","code":"@Test\n fun bytesClosesUnderlyingSource() {\n val closed = AtomicBoolean()\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }\n }\n assertThat(body.bytes().size).isEqualTo(5)\n assertThat(closed.get()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":258,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":260,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = 5"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":262,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":265,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":277,"symbol":"bytesThrowsWhenLengthsDisagree","kind":"function","lang":"kotlin","code":"@Test\n fun bytesThrowsWhenLengthsDisagree() {\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 10\n\n override fun source(): BufferedSource = Buffer().writeUtf8(\"hello\")\n }\n assertFailsWith {\n body.bytes()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"Content-Length (10) and stream length (5) disagree\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":281,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":283,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = 10"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":285,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource = Buffer().writeUtf8(\"hello\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":296,"symbol":"bytesThrowsMoreThanIntMaxValue","kind":"function","lang":"kotlin","code":"@Test\n fun bytesThrowsMoreThanIntMaxValue() {\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = Int.MAX_VALUE + 1L\n\n override fun source(): BufferedSource = throw AssertionError()\n }\n assertFailsWith {\n body.bytes()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"Cannot buffer entire body for content length: 2147483648\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":300,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":302,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = Int.MAX_VALUE + 1L"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":304,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource = throw AssertionError()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":315,"symbol":"byteStringEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun byteStringEmpty() {\n val body = body(\"\")\n assertThat(body.byteString()).isEqualTo(ByteString.EMPTY)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":321,"symbol":"byteStringSeesBom","kind":"function","lang":"kotlin","code":"@Test\n fun byteStringSeesBom() {\n val body = body(\"efbbbf68656c6c6f\")\n val actual = body.byteString()\n val expected: ByteString = \"efbbbf68656c6c6f\".decodeHex()\n assertThat(actual).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":329,"symbol":"byteStringClosesUnderlyingSource","kind":"function","lang":"kotlin","code":"@Test\n fun byteStringClosesUnderlyingSource() {\n val closed = AtomicBoolean()\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }\n }\n assertThat(body.byteString().size).isEqualTo(5)\n assertThat(closed.get()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":334,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":336,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = 5"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":338,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }\n }.buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":341,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n closed.set(true)\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":353,"symbol":"byteStringThrowsWhenLengthsDisagree","kind":"function","lang":"kotlin","code":"@Test\n fun byteStringThrowsWhenLengthsDisagree() {\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 10\n\n override fun source(): BufferedSource = Buffer().writeUtf8(\"hello\")\n }\n assertFailsWith {\n body.byteString()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"Content-Length (10) and stream length (5) disagree\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyJvmTest.kt","line":357,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":32,"symbol":"ResponseBodyTest","kind":"class","lang":"kotlin","code":"class ResponseBodyTest {\n @Test\n fun sourceEmpty() {\n val mediaType = if (null == null) null else \"any/thing; charset=${null}\".toMediaType()\n val body = \"\".decodeHex().toResponseBody(mediaType)\n val source = body.source()\n assertThat(source.exhausted()).isTrue()\n assertThat(source.readUtf8()).isEqualTo(\"\")\n }\n\n @Test\n fun sourceClosesUnderlyingSource() {\n var closed = false\n\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n override fun close() {\n closed = true\n super.close()\n }\n }.buffer()\n }\n }\n body.source().close()\n assertThat(closed).isTrue()\n }\n\n @Test\n fun throwingUnderlyingSourceClosesQuietly() {\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":33,"symbol":"sourceEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun sourceEmpty() {\n val mediaType = if (null == null) null else \"any/thing; charset=${null}\".toMediaType()\n val body = \"\".decodeHex().toResponseBody(mediaType)\n val source = body.source()\n assertThat(source.exhausted()).isTrue()\n assertThat(source.readUtf8()).isEqualTo(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":42,"symbol":"sourceClosesUnderlyingSource","kind":"function","lang":"kotlin","code":"@Test\n fun sourceClosesUnderlyingSource() {\n var closed = false\n\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n override fun close() {\n closed = true\n super.close()\n }\n }.buffer()\n }\n }\n body.source().close()\n assertThat(closed).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":48,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":50,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = 5"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":52,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n override fun close() {\n closed = true\n super.close()\n }\n }.buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":55,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n closed = true\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":66,"symbol":"throwingUnderlyingSourceClosesQuietly","kind":"function","lang":"kotlin","code":"@Test\n fun throwingUnderlyingSourceClosesQuietly() {\n val body: ResponseBody =\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = 5\n\n override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close(): Unit = throw IOException(\"Broken!\")\n }.buffer()\n }\n }\n assertThat(body.source().readUtf8()).isEqualTo(\"hello\")\n body.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":70,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":72,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = 5"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":74,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource {\n val source = Buffer().writeUtf8(\"hello\")\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun close(): Unit = throw IOException(\"Broken!\")\n }.buffer()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":77,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close(): Unit = throw IOException(\"Broken!\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":86,"symbol":"unicodeText","kind":"function","lang":"kotlin","code":"@Test\n fun unicodeText() {\n val text = \"eile oli oliiviõli\"\n val body = text.toResponseBody()\n assertThat(body.string()).isEqualTo(text)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":93,"symbol":"unicodeTextWithCharset","kind":"function","lang":"kotlin","code":"@Test\n fun unicodeTextWithCharset() {\n val text = \"eile oli oliiviõli\"\n val body = text.toResponseBody(\"text/plain; charset=UTF-8\".toMediaType())\n assertThat(body.string()).isEqualTo(text)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":100,"symbol":"unicodeByteString","kind":"function","lang":"kotlin","code":"@Test\n fun unicodeByteString() {\n val text = \"eile oli oliiviõli\"\n val body = text.toResponseBody()\n assertThat(body.byteString()).isEqualTo(text.encodeUtf8())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":107,"symbol":"unicodeByteStringWithCharset","kind":"function","lang":"kotlin","code":"@Test\n fun unicodeByteStringWithCharset() {\n val text = \"eile oli oliiviõli\".encodeUtf8()\n val body = text.toResponseBody(\"text/plain; charset=EBCDIC\".toMediaType())\n assertThat(body.byteString()).isEqualTo(text)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":114,"symbol":"unicodeBytes","kind":"function","lang":"kotlin","code":"@Test\n fun unicodeBytes() {\n val text = \"eile oli oliiviõli\"\n val body = text.toResponseBody()\n assertThat(body.bytes()).isEqualTo(text.encodeToByteArray())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":121,"symbol":"unicodeBytesWithCharset","kind":"function","lang":"kotlin","code":"@Test\n fun unicodeBytesWithCharset() {\n val text = \"eile oli oliiviõli\".encodeToByteArray()\n val body = text.toResponseBody(\"text/plain; charset=EBCDIC\".toMediaType())\n assertThat(body.bytes()).isEqualTo(text)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":129,"symbol":"ForwardingSource","kind":"class","lang":"kotlin","code":"abstract class ForwardingSource(\n val delegate: Source,\n) : Source {\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long = delegate.read(sink, byteCount)\n\n override fun timeout() = delegate.timeout()\n\n override fun close() = delegate.close()\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":132,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long = delegate.read(sink, byteCount)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":137,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout() = delegate.timeout()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseBodyTest.kt","line":139,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() = delegate.close()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":30,"symbol":"ResponseCommonTest","kind":"class","lang":"kotlin","code":"class ResponseCommonTest {\n @Test fun peekShorterThanResponse() {\n val response = newResponse(responseBody(\"abcdef\"))\n val peekedBody = response.peekBody(3)\n assertThat(peekedBody.string()).isEqualTo(\"abc\")\n assertThat(response.body.string()).isEqualTo(\"abcdef\")\n }\n\n @Test fun peekLongerThanResponse() {\n val response = newResponse(responseBody(\"abc\"))\n val peekedBody = response.peekBody(6)\n assertThat(peekedBody.string()).isEqualTo(\"abc\")\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }\n\n @Test fun eachPeakIsIndependent() {\n val response = newResponse(responseBody(\"abcdef\"))\n val p1 = response.peekBody(4)\n val p2 = response.peekBody(2)\n assertThat(response.body.string()).isEqualTo(\"abcdef\")\n assertThat(p1.string()).isEqualTo(\"abcd\")\n assertThat(p2.string()).isEqualTo(\"ab\")\n }\n\n @Test fun negativeStatusCodeThrowsIllegalStateException() {\n assertFailsWith {\n newResponse(responseBody(\"set status code -1\"), -1)\n }\n }\n\n @Test fun zeroStatusCodeIsValid() {\n val response = newResponse(responseBody(\"set status code 0\"), 0)\n assertThat(response.code).isEqualTo(0)\n }\n\n @Test fun defaultRespons"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":31,"symbol":"peekShorterThanResponse","kind":"function","lang":"kotlin","code":"@Test fun peekShorterThanResponse() {\n val response = newResponse(responseBody(\"abcdef\"))\n val peekedBody = response.peekBody(3)\n assertThat(peekedBody.string()).isEqualTo(\"abc\")\n assertThat(response.body.string()).isEqualTo(\"abcdef\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":38,"symbol":"peekLongerThanResponse","kind":"function","lang":"kotlin","code":"@Test fun peekLongerThanResponse() {\n val response = newResponse(responseBody(\"abc\"))\n val peekedBody = response.peekBody(6)\n assertThat(peekedBody.string()).isEqualTo(\"abc\")\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":45,"symbol":"eachPeakIsIndependent","kind":"function","lang":"kotlin","code":"@Test fun eachPeakIsIndependent() {\n val response = newResponse(responseBody(\"abcdef\"))\n val p1 = response.peekBody(4)\n val p2 = response.peekBody(2)\n assertThat(response.body.string()).isEqualTo(\"abcdef\")\n assertThat(p1.string()).isEqualTo(\"abcd\")\n assertThat(p2.string()).isEqualTo(\"ab\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":54,"symbol":"negativeStatusCodeThrowsIllegalStateException","kind":"function","lang":"kotlin","code":"@Test fun negativeStatusCodeThrowsIllegalStateException() {\n assertFailsWith {\n newResponse(responseBody(\"set status code -1\"), -1)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":60,"symbol":"zeroStatusCodeIsValid","kind":"function","lang":"kotlin","code":"@Test fun zeroStatusCodeIsValid() {\n val response = newResponse(responseBody(\"set status code 0\"), 0)\n assertThat(response.code).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":65,"symbol":"defaultResponseBodyIsEmpty","kind":"function","lang":"kotlin","code":"@Test fun defaultResponseBodyIsEmpty() {\n val response =\n Response\n .Builder()\n .request(\n Request\n .Builder()\n .url(\"https://example.com/\")\n .build(),\n ).protocol(Protocol.HTTP_1_1)\n .code(200)\n .message(\"OK\")\n .build()\n assertThat(response.body.contentType()).isNull()\n assertThat(response.body.contentLength()).isEqualTo(0L)\n assertThat(response.body.byteString()).isEqualTo(EMPTY)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":87,"symbol":"responseBody","kind":"function","lang":"kotlin","doc":"Returns a new response body that refuses to be read once it has been closed. This is true of most [BufferedSource] instances, but not of [Buffer].","code":"private fun responseBody(content: String): ResponseBody {\n val data = Buffer().writeUtf8(content)\n val source: Source =\n object : Source {\n var closed = false\n\n override fun close() {\n closed = true\n }\n\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n check(!closed)\n return data.read(sink, byteCount)\n }\n\n override fun timeout(): Timeout = Timeout.NONE\n }\n return source.buffer().asResponseBody(null, -1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":93,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n closed = true\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":97,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n check(!closed)\n return data.read(sink, byteCount)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":105,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = Timeout.NONE"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseCommonTest.kt","line":110,"symbol":"newResponse","kind":"function","lang":"kotlin","code":"private fun newResponse(\n responseBody: ResponseBody,\n code: Int = 200,\n ): Response =\n Response\n .Builder()\n .request(\n Request\n .Builder()\n .url(\"https://example.com/\")\n .build(),\n ).protocol(Protocol.HTTP_1_1)\n .code(code)\n .message(\"OK\")\n .body(responseBody)\n .build()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":31,"symbol":"ResponseJvmTest","kind":"class","lang":"kotlin","code":"class ResponseJvmTest {\n @Test\n fun testEmptyByDefaultIfTrailersNotSet() {\n val response = newResponse(\"\".toResponseBody())\n\n assertThat(response.trailers()).isEmpty()\n }\n\n @Test\n fun worksIfTrailersSet() {\n val response =\n newResponse(\"\".toResponseBody()) {\n trailers(\n object : TrailersSource {\n override fun get() = Headers.headersOf(\"a\", \"b\")\n },\n )\n }\n\n assertThat(response.trailers()[\"a\"]).isEqualTo(\"b\")\n }\n\n @Test fun peekAfterReadingResponse() {\n val response = newResponse(responseBody(\"abc\"))\n assertThat(response.body.string()).isEqualTo(\"abc\")\n\n assertFailsWith {\n response.peekBody(3)\n }\n }\n\n /**\n * Returns a new response body that refuses to be read once it has been closed. This is true of\n * most [BufferedSource] instances, but not of [Buffer].\n */\n private fun responseBody(content: String): ResponseBody {\n val data = Buffer().writeUtf8(content)\n val source: Source =\n object : Source {\n var closed = false\n\n override fun close() {\n closed = true\n }\n\n override fun read(\n sink: Buffer,\n byteC"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":32,"symbol":"testEmptyByDefaultIfTrailersNotSet","kind":"function","lang":"kotlin","code":"@Test\n fun testEmptyByDefaultIfTrailersNotSet() {\n val response = newResponse(\"\".toResponseBody())\n\n assertThat(response.trailers()).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":39,"symbol":"worksIfTrailersSet","kind":"function","lang":"kotlin","code":"@Test\n fun worksIfTrailersSet() {\n val response =\n newResponse(\"\".toResponseBody()) {\n trailers(\n object : TrailersSource {\n override fun get() = Headers.headersOf(\"a\", \"b\")\n },\n )\n }\n\n assertThat(response.trailers()[\"a\"]).isEqualTo(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":45,"symbol":"get","kind":"function","lang":"kotlin","code":"override fun get() = Headers.headersOf(\"a\", \"b\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":53,"symbol":"peekAfterReadingResponse","kind":"function","lang":"kotlin","code":"@Test fun peekAfterReadingResponse() {\n val response = newResponse(responseBody(\"abc\"))\n assertThat(response.body.string()).isEqualTo(\"abc\")\n\n assertFailsWith {\n response.peekBody(3)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":66,"symbol":"responseBody","kind":"function","lang":"kotlin","doc":"Returns a new response body that refuses to be read once it has been closed. This is true of most [BufferedSource] instances, but not of [Buffer].","code":"private fun responseBody(content: String): ResponseBody {\n val data = Buffer().writeUtf8(content)\n val source: Source =\n object : Source {\n var closed = false\n\n override fun close() {\n closed = true\n }\n\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n check(!closed)\n return data.read(sink, byteCount)\n }\n\n override fun timeout(): Timeout = Timeout.NONE\n }\n return source.buffer().asResponseBody(null, -1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":72,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n closed = true\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":76,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n check(!closed)\n return data.read(sink, byteCount)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":84,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = Timeout.NONE"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ResponseJvmTest.kt","line":89,"symbol":"newResponse","kind":"function","lang":"kotlin","code":"private fun newResponse(\n responseBody: ResponseBody,\n code: Int = 200,\n fn: Response.Builder.() -> Unit = {},\n ): Response =\n Response\n .Builder()\n .request(\n Request\n .Builder()\n .url(\"https://example.com/\")\n .build(),\n ).protocol(Protocol.HTTP_1_1)\n .code(code)\n .message(\"OK\")\n .body(responseBody)\n .apply { fn() }\n .build()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":40,"symbol":"RouteFailureTest","kind":"class","lang":"kotlin","code":"@Burst\nclass RouteFailureTest {\n private lateinit var socketFactory: SpecificHostSocketFactory\n private lateinit var client: OkHttpClient\n\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n val server1 = MockWebServer()\n\n @StartStop\n val server2 = MockWebServer()\n\n private var eventRecorder = EventRecorder()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n\n val dns = FakeDns()\n\n val ipv4 = InetAddress.getByName(\"203.0.113.1\")\n val ipv6 = InetAddress.getByName(\"2001:db8:ffff:ffff:ffff:ffff:ffff:1\")\n\n val refusedStream =\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build()\n val bodyResponse = MockResponse(body = \"body\")\n\n @BeforeEach\n fun setUp() {\n socketFactory = SpecificHostSocketFactory(InetSocketAddress(server1.hostName, server1.port))\n\n client =\n clientTestRule\n .newClientBuilder()\n .dns(dns)\n .socketFactory(socketFactory)\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n }\n\n @RepeatedTest(100)\n fun http2OneBadHostOn"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":73,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n socketFactory = SpecificHostSocketFactory(InetSocketAddress(server1.hostName, server1.port))\n\n client =\n clientTestRule\n .newClientBuilder()\n .dns(dns)\n .socketFactory(socketFactory)\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":86,"symbol":"http2OneBadHostOneGoodNoRetryOnConnectionFailure","kind":"function","lang":"kotlin","code":"@RepeatedTest(100)\n fun http2OneBadHostOneGoodNoRetryOnConnectionFailure() {\n enableProtocol(Protocol.HTTP_2)\n\n val request = Request(server1.url(\"/\"))\n\n server1.enqueue(refusedStream)\n server2.enqueue(bodyResponse)\n\n dns[server1.hostName] = listOf(ipv6, ipv4)\n socketFactory[ipv6] = server1.socketAddress\n socketFactory[ipv4] = server2.socketAddress\n\n client =\n client\n .newBuilder()\n .fastFallback(false)\n .apply {\n retryOnConnectionFailure = false\n }.build()\n\n executeSynchronously(request)\n .assertFailureMatches(\"stream was reset: REFUSED_STREAM\")\n\n assertThat(client.routeDatabase.failedRoutes).isEmpty()\n server1.takeRequest()\n assertThat(server1.requestCount).isEqualTo(1)\n assertThat(server2.requestCount).isEqualTo(0)\n\n assertThat(clientTestRule.recordedConnectionEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":123,"symbol":"http2OneBadHostOneGoodRetryOnConnectionFailure","kind":"function","lang":"kotlin","code":"@Test\n fun http2OneBadHostOneGoodRetryOnConnectionFailure() {\n enableProtocol(Protocol.HTTP_2)\n\n val request = Request(server1.url(\"/\"))\n\n server1.enqueue(refusedStream)\n server1.enqueue(refusedStream)\n server2.enqueue(bodyResponse)\n\n dns[server1.hostName] = listOf(ipv6, ipv4)\n socketFactory[ipv6] = server1.socketAddress\n socketFactory[ipv4] = server2.socketAddress\n\n client =\n client\n .newBuilder()\n .fastFallback(false)\n .apply {\n retryOnConnectionFailure = true\n }.build()\n\n executeSynchronously(request)\n .assertBody(\"body\")\n\n assertThat(client.routeDatabase.failedRoutes).isEmpty()\n // TODO check if we expect a second request to server1, before attempting server2\n assertThat(server1.requestCount).isEqualTo(2)\n assertThat(server2.requestCount).isEqualTo(1)\n\n assertThat(clientTestRule.recordedConnectionEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"NoNewExchanges\",\n \"ConnectionReleased\",\n \"ConnectionClosed\",\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":167,"symbol":"http2OneBadHostOneGoodNoRetryOnConnectionFailureFastFallback","kind":"function","lang":"kotlin","code":"@RepeatedTest(100)\n fun http2OneBadHostOneGoodNoRetryOnConnectionFailureFastFallback() {\n enableProtocol(Protocol.HTTP_2)\n\n val request = Request(server1.url(\"/\"))\n\n server1.enqueue(refusedStream)\n server2.enqueue(bodyResponse)\n\n dns[server1.hostName] = listOf(ipv6, ipv4)\n socketFactory[ipv6] = server1.socketAddress\n socketFactory[ipv4] = server2.socketAddress\n\n client =\n client\n .newBuilder()\n .fastFallback(true)\n .apply {\n retryOnConnectionFailure = false\n }.build()\n\n executeSynchronously(request)\n .assertFailureMatches(\"stream was reset: REFUSED_STREAM\")\n\n assertThat(client.routeDatabase.failedRoutes).isEmpty()\n server1.takeRequest()\n assertThat(server1.requestCount).isEqualTo(1)\n assertThat(server2.requestCount).isEqualTo(0)\n\n assertThat(clientTestRule.recordedConnectionEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":204,"symbol":"http2OneBadHostOneGoodRetryOnConnectionFailureFastFallback","kind":"function","lang":"kotlin","code":"@Test\n fun http2OneBadHostOneGoodRetryOnConnectionFailureFastFallback() {\n enableProtocol(Protocol.HTTP_2)\n\n val request = Request(server1.url(\"/\"))\n\n server1.enqueue(refusedStream)\n server1.enqueue(refusedStream)\n server2.enqueue(bodyResponse)\n\n dns[server1.hostName] = listOf(ipv6, ipv4)\n socketFactory[ipv6] = server1.socketAddress\n socketFactory[ipv4] = server2.socketAddress\n\n client =\n client\n .newBuilder()\n .fastFallback(true)\n .apply {\n retryOnConnectionFailure = true\n }.build()\n\n executeSynchronously(request)\n .assertBody(\"body\")\n\n assertThat(client.routeDatabase.failedRoutes).isEmpty()\n // TODO check if we expect a second request to server1, before attempting server2\n assertThat(server1.requestCount).isEqualTo(2)\n assertThat(server2.requestCount).isEqualTo(1)\n\n assertThat(clientTestRule.recordedConnectionEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"NoNewExchanges\",\n \"ConnectionReleased\",\n \"ConnectionClosed\",\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":248,"symbol":"http2OneBadHostRetryOnConnectionFailure","kind":"function","lang":"kotlin","code":"@RepeatedTest(100)\n fun http2OneBadHostRetryOnConnectionFailure() {\n enableProtocol(Protocol.HTTP_2)\n\n val request = Request(server1.url(\"/\"))\n\n server1.enqueue(refusedStream)\n server1.enqueue(refusedStream)\n\n dns[server1.hostName] = listOf(ipv6)\n socketFactory[ipv6] = server1.socketAddress\n\n client =\n client\n .newBuilder()\n .fastFallback(false)\n .apply {\n retryOnConnectionFailure = true\n }.build()\n\n executeSynchronously(request)\n .assertFailureMatches(\"stream was reset: REFUSED_STREAM\")\n\n assertThat(client.routeDatabase.failedRoutes).isEmpty()\n server1.takeRequest()\n assertThat(server1.requestCount).isEqualTo(1)\n\n assertThat(clientTestRule.recordedConnectionEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":283,"symbol":"http2OneBadHostRetryOnConnectionFailureFastFallback","kind":"function","lang":"kotlin","code":"@RepeatedTest(100)\n fun http2OneBadHostRetryOnConnectionFailureFastFallback() {\n enableProtocol(Protocol.HTTP_2)\n\n val request = Request(server1.url(\"/\"))\n\n server1.enqueue(refusedStream)\n server1.enqueue(refusedStream)\n\n dns[server1.hostName] = listOf(ipv6)\n socketFactory[ipv6] = server1.socketAddress\n\n client =\n client\n .newBuilder()\n .fastFallback(true)\n .apply {\n retryOnConnectionFailure = true\n }.build()\n\n executeSynchronously(request)\n .assertFailureMatches(\"stream was reset: REFUSED_STREAM\")\n\n assertThat(client.routeDatabase.failedRoutes).isEmpty()\n server1.takeRequest()\n assertThat(server1.requestCount).isEqualTo(1)\n\n assertThat(clientTestRule.recordedConnectionEventTypes()).containsExactly(\n \"ConnectStart\",\n \"ConnectEnd\",\n \"ConnectionAcquired\",\n \"ConnectionReleased\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":318,"symbol":"proxyMoveTest","kind":"function","lang":"kotlin","code":"@Test\n fun proxyMoveTest(cleanClose: Boolean = true) {\n // Define a single Proxy at myproxy:8008 that will artificially move during the test\n val proxySelector = RecordingProxySelector()\n val socketAddress = InetSocketAddress.createUnresolved(\"myproxy\", 8008)\n proxySelector.proxies.add(Proxy(Proxy.Type.HTTP, socketAddress))\n\n // Define two host names for the DNS routing of fake proxy servers\n val proxyServer1 = InetAddress.getByAddress(\"proxyServer1\", byteArrayOf(127, 0, 0, 2))\n val proxyServer2 = InetAddress.getByAddress(\"proxyServer2\", byteArrayOf(127, 0, 0, 3))\n\n println(\"Proxy Server 1 is ${server1.socketAddress}\")\n println(\"Proxy Server 2 is ${server2.socketAddress}\")\n\n // Since myproxy:8008 won't resolve, redirect with DNS to proxyServer1\n // Then redirect socket connection to server1\n dns[\"myproxy\"] = listOf(proxyServer1)\n socketFactory[proxyServer1] = server1.socketAddress\n\n client = client.newBuilder().proxySelector(proxySelector).build()\n\n val request = Request(server1.url(\"/\"))\n\n server1.enqueue(MockResponse(200))\n server2.enqueue(MockResponse(200))\n server2.enqueue(MockResponse(200))\n\n println(\"\\n\\nRequest to ${s"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":383,"symbol":"enableProtocol","kind":"function","lang":"kotlin","code":"private fun enableProtocol(protocol: Protocol) {\n enableTls()\n client =\n client\n .newBuilder()\n .protocols(listOf(protocol, Protocol.HTTP_1_1))\n .build()\n server1.protocols = client.protocols\n server2.protocols = client.protocols\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":394,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n server1.useHttps(handshakeCertificates.sslSocketFactory())\n server2.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/RouteFailureTest.kt","line":407,"symbol":"executeSynchronously","kind":"function","lang":"kotlin","code":"private fun executeSynchronously(request: Request): RecordedResponse {\n val call = client.newCall(request)\n return try {\n val response = call.execute()\n val bodyString = response.body.string()\n RecordedResponse(request, response, null, bodyString, null)\n } catch (e: IOException) {\n RecordedResponse(request, null, null, null, e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":64,"symbol":"ServerTruncatesRequestTest","kind":"class","lang":"kotlin","code":"@Timeout(30)\n@Tag(\"Slowish\")\nclass ServerTruncatesRequestTest {\n @RegisterExtension\n @JvmField\n val platform = PlatformRule()\n\n @RegisterExtension\n @JvmField\n var clientTestRule = OkHttpClientTestRule()\n\n private val eventRecorder = EventRecorder()\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n\n private var client =\n clientTestRule\n .newClientBuilder()\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n platform.assumeHttp2Support()\n }\n\n @Test\n fun serverTruncatesRequestOnLongPostHttp1() {\n // \"java.net.SocketException: Socket closed\" thrown reading response after\n // \"java.net.SocketException: Connection reset by peer\" writing request\n assumeNotWindows()\n\n serverTruncatesRequestOnLongPost(https = false)\n }\n\n @Test\n fun serverTruncatesRequestOnLongPostHttp2() {\n enableProtocol(Protocol.HTTP_2)\n serverTruncatesRequestOnLongPost(https = true)\n }\n\n private fun serverTruncatesRequestOnLongPost(https: Boolean) {\n server.enqueue(\n MockResponse\n .Builder"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":87,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n platform.assumeHttp2Support()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":93,"symbol":"serverTruncatesRequestOnLongPostHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun serverTruncatesRequestOnLongPostHttp1() {\n // \"java.net.SocketException: Socket closed\" thrown reading response after\n // \"java.net.SocketException: Connection reset by peer\" writing request\n assumeNotWindows()\n\n serverTruncatesRequestOnLongPost(https = false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":102,"symbol":"serverTruncatesRequestOnLongPostHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun serverTruncatesRequestOnLongPostHttp2() {\n enableProtocol(Protocol.HTTP_2)\n serverTruncatesRequestOnLongPost(https = true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":108,"symbol":"serverTruncatesRequestOnLongPost","kind":"function","lang":"kotlin","code":"private fun serverTruncatesRequestOnLongPost(https: Boolean) {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .doNotReadRequestBody()\n .build(),\n )\n\n val call =\n client.newCall(\n Request(\n url = server.url(\"/\"),\n body = SlowRequestBody,\n ),\n )\n\n call.execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }\n\n val expectedEvents = mutableListOf>()\n // Start out with standard events...\n expectedEvents += CallStart::class\n expectedEvents += ProxySelectStart::class\n expectedEvents += ProxySelectEnd::class\n expectedEvents += DnsStart::class\n expectedEvents += DnsEnd::class\n expectedEvents += ConnectStart::class\n if (https) {\n expectedEvents += SecureConnectStart::class\n expectedEvents += SecureConnectEnd::class\n }\n expectedEvents += ConnectEnd::class\n expectedEvents += ConnectionAcquired::class\n expectedEvents += RequestHeadersStart::class\n expectedEvents += RequestHeadersEnd::class\n expectedEvents += RequestBodyStart::class\n // ... but we can read the response even after writin"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":165,"symbol":"serverTruncatesRequestHttp2OnDuplexRequest","kind":"function","lang":"kotlin","doc":"If the server returns a full response, it doesn't really matter if the HTTP/2 stream is reset. Attempts to write the request body fails fast.","code":"@Test\n fun serverTruncatesRequestHttp2OnDuplexRequest() {\n enableProtocol(Protocol.HTTP_2)\n\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .doNotReadRequestBody()\n .build(),\n )\n\n val requestBody = AsyncRequestBody()\n\n val call =\n client.newCall(\n Request(\n url = server.url(\"/\"),\n body = requestBody,\n ),\n )\n\n call.execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"abc\")\n val requestBodyOut = requestBody.takeSink()\n assertFailsWith {\n SlowRequestBody.writeTo(requestBodyOut)\n }\n assertFailsWith {\n requestBodyOut.close()\n }\n }\n\n // Confirm that the connection pool was not corrupted by making another call.\n makeSimpleCall()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":202,"symbol":"serverTruncatesRequestButTrailersCanStillBeReadHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun serverTruncatesRequestButTrailersCanStillBeReadHttp1() {\n // \"java.net.SocketException: Socket closed\" thrown reading response after\n // \"java.net.SocketException: Connection reset by peer\" writing request\n assumeNotWindows()\n\n serverTruncatesRequestButTrailersCanStillBeRead(http2 = false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":211,"symbol":"serverTruncatesRequestButTrailersCanStillBeReadHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun serverTruncatesRequestButTrailersCanStillBeReadHttp2() {\n enableProtocol(Protocol.HTTP_2)\n serverTruncatesRequestButTrailersCanStillBeRead(http2 = true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":217,"symbol":"serverTruncatesRequestButTrailersCanStillBeRead","kind":"function","lang":"kotlin","code":"private fun serverTruncatesRequestButTrailersCanStillBeRead(http2: Boolean) {\n val mockResponse =\n MockResponse\n .Builder()\n .doNotReadRequestBody()\n .trailers(headersOf(\"caboose\", \"xyz\"))\n\n // Trailers always work for HTTP/2, but only for chunked bodies in HTTP/1.\n if (http2) {\n mockResponse.body(\"abc\")\n } else {\n mockResponse.chunkedBody(\"abc\", 1)\n }\n\n server.enqueue(mockResponse.build())\n\n val call =\n client.newCall(\n Request(\n url = server.url(\"/\"),\n body = SlowRequestBody,\n ),\n )\n\n call.execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"abc\")\n assertThat(response.trailers()).isEqualTo(headersOf(\"caboose\", \"xyz\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":247,"symbol":"serverDisconnectsBeforeSecondRequestHttp1","kind":"function","lang":"kotlin","code":"@Disabled(\"Follow up with fix in https://github.com/lysine-dev/okhttp/issues/6853\")\n @Test\n fun serverDisconnectsBeforeSecondRequestHttp1() {\n enableProtocol(Protocol.HTTP_1_1)\n\n server.enqueue(MockResponse(code = 200, body = \"Req1\"))\n server.enqueue(MockResponse(code = 200, body = \"Req2\"))\n\n val eventListener =\n object : EventListener() {\n var socket: SSLSocket? = null\n var closed = false\n\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socket = connection.socket() as SSLSocket\n }\n\n override fun requestHeadersStart(call: Call) {\n if (closed) {\n throw IOException(\"fake socket failure\")\n }\n }\n }\n val localClient = client.newBuilder().eventListener(eventListener).build()\n\n val call1 = localClient.newCall(Request(server.url(\"/\")))\n\n call1.execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"Req1\")\n assertThat(response.handshake).isNotNull()\n assertThat(response.protocol == Protocol.HTTP_1_1)\n }\n\n eventListener.closed = true\n\n val call2 = localClient.newCall(Request(server.ur"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":260,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n socket = connection.socket() as SSLSocket\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":267,"symbol":"requestHeadersStart","kind":"function","lang":"kotlin","code":"override fun requestHeadersStart(call: Call) {\n if (closed) {\n throw IOException(\"fake socket failure\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":292,"symbol":"noAttemptToReadResponseIfLoadingRequestBodyIsSourceOfFailure","kind":"function","lang":"kotlin","code":"@Test\n fun noAttemptToReadResponseIfLoadingRequestBodyIsSourceOfFailure() {\n server.enqueue(MockResponse(body = \"abc\"))\n\n val requestBody =\n object : RequestBody() {\n override fun contentType(): MediaType? = null\n\n override fun writeTo(sink: BufferedSink) {\n throw IOException(\"boom\") // Despite this exception, 'sink' is healthy.\n }\n }\n\n val callA =\n client.newCall(\n Request(\n url = server.url(\"/\"),\n body = requestBody,\n ),\n )\n\n assertFailsWith {\n callA.execute()\n }.also { expected ->\n assertThat(expected).hasMessage(\"boom\")\n }\n\n assertThat(server.requestCount).isEqualTo(0)\n\n // Confirm that the connection pool was not corrupted by making another call. This doesn't use\n // makeSimpleCall() because it uses the MockResponse enqueued above.\n val callB = client.newCall(Request(server.url(\"/\")))\n callB.execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":298,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":300,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n throw IOException(\"boom\") // Despite this exception, 'sink' is healthy.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":329,"symbol":"makeSimpleCall","kind":"function","lang":"kotlin","code":"private fun makeSimpleCall() {\n server.enqueue(MockResponse(body = \"healthy\"))\n val callB = client.newCall(Request(server.url(\"/\")))\n callB.execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"healthy\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":337,"symbol":"enableProtocol","kind":"function","lang":"kotlin","code":"private fun enableProtocol(protocol: Protocol) {\n enableTls()\n client =\n client\n .newBuilder()\n .protocols(listOf(protocol, Protocol.HTTP_1_1))\n .build()\n server.protocols = client.protocols\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":347,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":360,"symbol":"SlowRequestBody","kind":"object","lang":"kotlin","doc":"A request body that slowly trickles bytes, expecting to not complete.","code":"private object SlowRequestBody : RequestBody() {\n override fun contentType(): MediaType? = null\n\n override fun writeTo(sink: BufferedSink) {\n for (i in 0 until 50) {\n sink.writeUtf8(\"abc\")\n sink.flush()\n Thread.sleep(100)\n }\n fail(\"\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":361,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/ServerTruncatesRequestTest.kt","line":363,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n for (i in 0 until 50) {\n sink.writeUtf8(\"abc\")\n sink.flush()\n Thread.sleep(100)\n }\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SessionReuseTest.kt","line":39,"symbol":"SessionReuseTest","kind":"class","lang":"kotlin","code":"@Burst\nclass SessionReuseTest {\n @JvmField @RegisterExtension\n var platform = PlatformRule()\n\n @JvmField @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n\n var client = clientTestRule.newClient()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n // Default after JDK 14, but we are avoiding tests that assume special setup.\n // System.setProperty(\"jdk.tls.client.enableSessionTicketExtension\", \"true\")\n // System.setProperty(\"jdk.tls.server.enableSessionTicketExtension\", \"true\")\n\n // IllegalStateException: Cannot resume session and session creation is disabled\n platform.assumeNotBouncyCastle()\n }\n\n @Test\n fun testSessionReuse(tlsVersion: String = burstValues(\"TLSv1.2\", \"TLSv1.3\")) {\n if (tlsVersion == TlsVersion.TLS_1_3.javaName) {\n assumeTrue(PlatformVersion.majorVersion != 8)\n }\n\n val sessionIds = mutableListOf()\n\n enableTls()\n\n val tlsVersion = TlsVersion.forJavaName(tlsVersion)\n val spec =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .tlsVersions(tlsVersion)\n .build"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SessionReuseTest.kt","line":54,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n // Default after JDK 14, but we are avoiding tests that assume special setup.\n // System.setProperty(\"jdk.tls.client.enableSessionTicketExtension\", \"true\")\n // System.setProperty(\"jdk.tls.server.enableSessionTicketExtension\", \"true\")\n\n // IllegalStateException: Cannot resume session and session creation is disabled\n platform.assumeNotBouncyCastle()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SessionReuseTest.kt","line":64,"symbol":"testSessionReuse","kind":"function","lang":"kotlin","code":"@Test\n fun testSessionReuse(tlsVersion: String = burstValues(\"TLSv1.2\", \"TLSv1.3\")) {\n if (tlsVersion == TlsVersion.TLS_1_3.javaName) {\n assumeTrue(PlatformVersion.majorVersion != 8)\n }\n\n val sessionIds = mutableListOf()\n\n enableTls()\n\n val tlsVersion = TlsVersion.forJavaName(tlsVersion)\n val spec =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .tlsVersions(tlsVersion)\n .build()\n\n var reuseSession = false\n\n val sslContext = handshakeCertificates.sslContext()\n val systemSslSocketFactory = sslContext.socketFactory\n val sslSocketFactory =\n object : DelegatingSSLSocketFactory(systemSslSocketFactory) {\n override fun configureSocket(sslSocket: SSLSocket): SSLSocket =\n sslSocket.apply {\n if (reuseSession) {\n this.enableSessionCreation = false\n }\n }\n }\n\n client =\n client\n .newBuilder()\n .connectionSpecs(listOf(spec))\n .eventListenerFactory(\n clientTestRule.wrap(\n object : EventListener() {\n override fun connectionAcquired(\n call: Call,\n connection: Conne"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SessionReuseTest.kt","line":87,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"override fun configureSocket(sslSocket: SSLSocket): SSLSocket =\n sslSocket.apply {\n if (reuseSession) {\n this.enableSessionCreation = false\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SessionReuseTest.kt","line":102,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n val sslSocket = connection.socket() as SSLSocket\n\n sessionIds.add(\n sslSocket.session.id\n .toByteString()\n .hex(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SessionReuseTest.kt","line":177,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":54,"symbol":"SocketChannelTest","kind":"class","lang":"kotlin","code":"@Suppress(\"UsePropertyAccessSyntax\")\n@Timeout(6)\n@Tag(\"slow\")\n@Burst\nclass SocketChannelTest {\n @JvmField @RegisterExtension\n val platform = PlatformRule()\n\n @JvmField @RegisterExtension\n val clientTestRule =\n OkHttpClientTestRule().apply {\n recordFrames = true\n // recordSslDebug = true\n }\n\n // https://tools.ietf.org/html/rfc6066#page-6 specifies a FQDN is required.\n val hostname = \"local.host\"\n private val handshakeCertificates =\n run {\n // Generate a self-signed cert for the server to serve and the client to trust.\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(hostname)\n .addSubjectAlternativeName(hostname)\n .build()\n HandshakeCertificates\n .Builder()\n .heldCertificate(heldCertificate)\n .addTrustedCertificate(heldCertificate.certificate)\n .build()\n }\n private var acceptedHostName: String? = null\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setUp() {\n // Test designed for Conscrypt and JSSE\n platform.assumeNotBouncyCastle()\n }\n\n @Test\n fun testHttp(socketMode: SocketMode = burstValues(Channel, Standard)) {\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":91,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n // Test designed for Conscrypt and JSSE\n platform.assumeNotBouncyCastle()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":97,"symbol":"testHttp","kind":"function","lang":"kotlin","code":"@Test\n fun testHttp(socketMode: SocketMode = burstValues(Channel, Standard)) {\n testConnection(socketMode)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":102,"symbol":"testHttps","kind":"function","lang":"kotlin","code":"@Test\n fun testHttps(\n provider: Provider = Provider.JSSE,\n protocol: Protocol = burstValues(HTTP_1_1, HTTP_2),\n tlsVersion: TlsVersion = burstValues(TLS_1_3, TLS_1_2),\n socketMode: SocketMode = burstValues(Channel, Standard),\n tlsExtensionMode: TlsExtensionMode = TlsExtensionMode.STANDARD,\n ) {\n testConnection(TlsInstance(provider, protocol, tlsVersion, socketMode, tlsExtensionMode))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":113,"symbol":"testConnection","kind":"function","lang":"kotlin","code":"private fun testConnection(socketMode: SocketMode) {\n // https://github.com/lysine-dev/okhttp/pull/6554\n assumeFalse(\n socketMode is TlsInstance &&\n socketMode.socketMode == Channel &&\n socketMode.protocol == HTTP_2 &&\n socketMode.tlsExtensionMode == STANDARD,\n \"failing for channel and h2\",\n )\n\n if (socketMode is TlsInstance) {\n assumeTrue((socketMode.provider == CONSCRYPT) == platform.isConscrypt())\n }\n\n val client =\n clientTestRule\n .newClientBuilder()\n .dns { listOf(InetAddress.getByName(\"localhost\")) }\n .callTimeout(4, SECONDS)\n .writeTimeout(2, SECONDS)\n .readTimeout(2, SECONDS)\n .apply {\n if (socketMode is TlsInstance) {\n if (socketMode.socketMode == Channel) {\n socketFactory(ChannelSocketFactory())\n }\n\n connectionSpecs(\n listOf(\n ConnectionSpec\n .Builder(ConnectionSpec.COMPATIBLE_TLS)\n .tlsVersions(socketMode.tlsVersion)\n .supportsTlsExtensions(socketMode.tlsExtensionMode == STANDARD)\n .build(),\n ),\n )\n\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":165,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"override fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n return sslSocket.apply {\n sslParameters =\n sslParameters.apply {\n sniMatchers =\n listOf(\n object : SNIMatcher(StandardConstants.SNI_HOST_NAME) {\n override fun matches(serverName: SNIServerName): Boolean {\n acceptedHostName = (serverName as SNIHostName).asciiName\n return true\n }\n },\n )\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":172,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(serverName: SNIServerName): Boolean {\n acceptedHostName = (serverName as SNIHostName).asciiName\n return true\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":209,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n promise.completeExceptionally(e)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":216,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n promise.complete(response)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":247,"symbol":"Channel","kind":"object","lang":"kotlin","code":"object Channel : SocketMode() {\n override fun toString(): String = \"Channel\"\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":248,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"Channel\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":251,"symbol":"Standard","kind":"object","lang":"kotlin","code":"object Standard : SocketMode() {\n override fun toString(): String = \"Standard\"\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":252,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"Standard\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":255,"symbol":"TlsInstance","kind":"class","lang":"kotlin","code":"data class TlsInstance(\n val provider: Provider,\n val protocol: Protocol,\n val tlsVersion: TlsVersion,\n val socketMode: SocketMode,\n val tlsExtensionMode: TlsExtensionMode,\n) : SocketMode() {\n override fun toString(): String = \"$provider/$protocol/$tlsVersion/$socketMode/$tlsExtensionMode\"\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":262,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"$provider/$protocol/$tlsVersion/$socketMode/$tlsExtensionMode\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":265,"symbol":"Provider","kind":"enum","lang":"kotlin","code":"enum class Provider {\n JSSE,\n CONSCRYPT,\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":266,"symbol":"JSSE","kind":"enum_member","lang":"kotlin","code":"JSSE"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":267,"symbol":"CONSCRYPT","kind":"enum_member","lang":"kotlin","code":"CONSCRYPT"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":270,"symbol":"TlsExtensionMode","kind":"enum","lang":"kotlin","code":"enum class TlsExtensionMode {\n DISABLED,\n STANDARD,\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":271,"symbol":"DISABLED","kind":"enum_member","lang":"kotlin","code":"DISABLED"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocketChannelTest.kt","line":272,"symbol":"STANDARD","kind":"enum_member","lang":"kotlin","code":"STANDARD"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":48,"symbol":"SocksProxy","kind":"class","lang":"kotlin","doc":"A limited implementation of SOCKS Protocol Version 5, intended to be similar to MockWebServer. See [RFC 1928](https://www.ietf.org/rfc/rfc1928.txt).","code":"class SocksProxy {\n private val executor = Executors.newCachedThreadPool(threadFactory(\"SocksProxy\"))\n private var serverSocket: ServerSocket? = null\n private val connectionCount = AtomicInteger()\n private val openSockets: MutableSet = ConcurrentHashMap.newKeySet()\n\n fun play() {\n serverSocket = ServerSocket(0)\n executor.execute {\n val threadName = \"SocksProxy ${serverSocket!!.localPort}\"\n Thread.currentThread().name = threadName\n try {\n while (true) {\n val socket = serverSocket!!.accept()\n connectionCount.incrementAndGet()\n service(socket)\n }\n } catch (e: SocketException) {\n logger.info(\"$threadName done accepting connections: ${e.message}\")\n } catch (e: IOException) {\n logger.log(Level.WARNING, \"$threadName failed unexpectedly\", e)\n } finally {\n for (socket in openSockets) {\n socket.closeQuietly()\n }\n Thread.currentThread().name = \"SocksProxy\"\n }\n }\n }\n\n fun proxy(): Proxy =\n Proxy(\n Proxy.Type.SOCKS,\n InetSocketAddress.createUnresolved(\"localhost\", serverSocket!!.localPort),\n )\n\n fun connectionCount(): Int = connectionCo"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":54,"symbol":"play","kind":"function","lang":"kotlin","code":"fun play() {\n serverSocket = ServerSocket(0)\n executor.execute {\n val threadName = \"SocksProxy ${serverSocket!!.localPort}\"\n Thread.currentThread().name = threadName\n try {\n while (true) {\n val socket = serverSocket!!.accept()\n connectionCount.incrementAndGet()\n service(socket)\n }\n } catch (e: SocketException) {\n logger.info(\"$threadName done accepting connections: ${e.message}\")\n } catch (e: IOException) {\n logger.log(Level.WARNING, \"$threadName failed unexpectedly\", e)\n } finally {\n for (socket in openSockets) {\n socket.closeQuietly()\n }\n Thread.currentThread().name = \"SocksProxy\"\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":78,"symbol":"proxy","kind":"function","lang":"kotlin","code":"fun proxy(): Proxy =\n Proxy(\n Proxy.Type.SOCKS,\n InetSocketAddress.createUnresolved(\"localhost\", serverSocket!!.localPort),\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":84,"symbol":"connectionCount","kind":"function","lang":"kotlin","code":"fun connectionCount(): Int = connectionCount.get()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":86,"symbol":"shutdown","kind":"function","lang":"kotlin","code":"fun shutdown() {\n serverSocket!!.close()\n executor.shutdown()\n if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {\n throw IOException(\"Gave up waiting for executor to shut down\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":94,"symbol":"service","kind":"function","lang":"kotlin","code":"private fun service(from: Socket) {\n val name = \"SocksProxy ${from.remoteSocketAddress}\"\n threadName(name) {\n try {\n val fromSource = from.source().buffer()\n val fromSink = from.sink().buffer()\n hello(fromSource, fromSink)\n acceptCommand(from.inetAddress, fromSource, fromSink)\n openSockets.add(from)\n } catch (e: IOException) {\n logger.log(Level.WARNING, \"$name failed\", e)\n from.closeQuietly()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":110,"symbol":"hello","kind":"function","lang":"kotlin","code":"private fun hello(\n fromSource: BufferedSource,\n fromSink: BufferedSink,\n ) {\n val version = fromSource.readByte() and 0xff\n val methodCount = fromSource.readByte() and 0xff\n var selectedMethod = METHOD_NONE\n if (version != VERSION_5) {\n throw ProtocolException(\"unsupported version: $version\")\n }\n for (i in 0 until methodCount) {\n val candidateMethod: Int = fromSource.readByte() and 0xff\n if (candidateMethod == METHOD_NO_AUTHENTICATION_REQUIRED) {\n selectedMethod = candidateMethod\n }\n }\n when (selectedMethod) {\n METHOD_NO_AUTHENTICATION_REQUIRED -> {\n fromSink.writeByte(VERSION_5)\n fromSink.writeByte(selectedMethod)\n fromSink.emit()\n }\n\n else -> {\n throw ProtocolException(\"unsupported method: $selectedMethod\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":139,"symbol":"acceptCommand","kind":"function","lang":"kotlin","code":"private fun acceptCommand(\n fromAddress: InetAddress,\n fromSource: BufferedSource,\n fromSink: BufferedSink,\n ) {\n // Read the command.\n val version = fromSource.readByte() and 0xff\n if (version != VERSION_5) throw ProtocolException(\"unexpected version: $version\")\n\n val command = fromSource.readByte() and 0xff\n\n val reserved = fromSource.readByte() and 0xff\n if (reserved != 0) throw ProtocolException(\"unexpected reserved: $reserved\")\n\n val addressType = fromSource.readByte() and 0xff\n val toAddress =\n when (addressType) {\n ADDRESS_TYPE_IPV4 -> {\n InetAddress.getByAddress(fromSource.readByteArray(4L))\n }\n\n ADDRESS_TYPE_DOMAIN_NAME -> {\n val domainNameLength: Int = fromSource.readByte() and 0xff\n val domainName = fromSource.readUtf8(domainNameLength.toLong())\n // Resolve HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS to localhost.\n when {\n domainName.equals(HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS, ignoreCase = true) -> {\n InetAddress.getByName(\"localhost\")\n }\n\n else -> {\n InetAddress.getByName(domainName)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxy.kt","line":214,"symbol":"transfer","kind":"function","lang":"kotlin","code":"private fun transfer(\n fromAddress: InetAddress,\n toAddress: InetAddress,\n source: BufferedSource,\n sink: BufferedSink,\n ) {\n executor.execute {\n val name = \"SocksProxy $fromAddress to $toAddress\"\n threadName(name) {\n val buffer = Buffer()\n try {\n sink.use {\n source.use {\n while (true) {\n val byteCount = source.read(buffer, 8192L)\n if (byteCount == -1L) break\n sink.write(buffer, byteCount)\n sink.emit()\n }\n }\n }\n } catch (e: IOException) {\n logger.log(Level.WARNING, \"$name failed\", e)\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxyTest.kt","line":33,"symbol":"SocksProxyTest","kind":"class","lang":"kotlin","code":"class SocksProxyTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private val socksProxy = SocksProxy()\n\n @BeforeEach\n fun setUp() {\n socksProxy.play()\n }\n\n @AfterEach\n fun tearDown() {\n socksProxy.shutdown()\n }\n\n @Test\n fun proxy() {\n server.enqueue(MockResponse.Builder().body(\"abc\").build())\n server.enqueue(MockResponse.Builder().body(\"def\").build())\n val client =\n clientTestRule\n .newClientBuilder()\n .proxy(socksProxy.proxy())\n .build()\n val request1 = Request.Builder().url(server.url(\"/\")).build()\n val response1 = client.newCall(request1).execute()\n assertThat(response1.body.string()).isEqualTo(\"abc\")\n val request2 = Request.Builder().url(server.url(\"/\")).build()\n val response2 = client.newCall(request2).execute()\n assertThat(response2.body.string()).isEqualTo(\"def\")\n\n // The HTTP calls should share a single connection.\n assertThat(socksProxy.connectionCount()).isEqualTo(1)\n }\n\n @Test\n fun proxySelector() {\n server.enqueue(MockResponse.Builder().body(\"abc\").build())\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxyTest.kt","line":45,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n socksProxy.play()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxyTest.kt","line":50,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n socksProxy.shutdown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxyTest.kt","line":55,"symbol":"proxy","kind":"function","lang":"kotlin","code":"@Test\n fun proxy() {\n server.enqueue(MockResponse.Builder().body(\"abc\").build())\n server.enqueue(MockResponse.Builder().body(\"def\").build())\n val client =\n clientTestRule\n .newClientBuilder()\n .proxy(socksProxy.proxy())\n .build()\n val request1 = Request.Builder().url(server.url(\"/\")).build()\n val response1 = client.newCall(request1).execute()\n assertThat(response1.body.string()).isEqualTo(\"abc\")\n val request2 = Request.Builder().url(server.url(\"/\")).build()\n val response2 = client.newCall(request2).execute()\n assertThat(response2.body.string()).isEqualTo(\"def\")\n\n // The HTTP calls should share a single connection.\n assertThat(socksProxy.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxyTest.kt","line":75,"symbol":"proxySelector","kind":"function","lang":"kotlin","code":"@Test\n fun proxySelector() {\n server.enqueue(MockResponse.Builder().body(\"abc\").build())\n val proxySelector: ProxySelector =\n object : ProxySelector() {\n override fun select(uri: URI) = listOf(socksProxy.proxy())\n\n override fun connectFailed(\n uri: URI,\n socketAddress: SocketAddress,\n e: IOException,\n ) = error(\"unexpected call\")\n }\n val client =\n clientTestRule\n .newClientBuilder()\n .proxySelector(proxySelector)\n .build()\n val request = Request.Builder().url(server.url(\"/\")).build()\n val response = client.newCall(request).execute()\n assertThat(response.body.string()).isEqualTo(\"abc\")\n assertThat(socksProxy.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxyTest.kt","line":80,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI) = listOf(socksProxy.proxy())"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxyTest.kt","line":82,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI,\n socketAddress: SocketAddress,\n e: IOException,\n ) = error(\"unexpected call\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/SocksProxyTest.kt","line":99,"symbol":"checkRemoteDNSResolve","kind":"function","lang":"kotlin","code":"@Test\n fun checkRemoteDNSResolve() {\n // This testcase will fail if the target is resolved locally instead of through the proxy.\n server.enqueue(MockResponse.Builder().body(\"abc\").build())\n val client =\n clientTestRule\n .newClientBuilder()\n .proxy(socksProxy.proxy())\n .build()\n val url =\n server\n .url(\"/\")\n .newBuilder()\n .host(SocksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS)\n .build()\n val request = Request.Builder().url(url).build()\n val response1 = client.newCall(request).execute()\n assertThat(response1.body.string()).isEqualTo(\"abc\")\n assertThat(socksProxy.connectionCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":35,"symbol":"TestLogHandler","kind":"class","lang":"kotlin","doc":"A log handler that records which log messages were published so that a calling test can make assertions about them.","code":"class TestLogHandler(\n private val logger: Logger,\n) : TestRule,\n BeforeEachCallback,\n AfterEachCallback {\n constructor(loggerName: Class<*>) : this(Logger.getLogger(loggerName.getName()))\n\n private val logs = LinkedBlockingQueue()\n\n private val handler =\n object : Handler() {\n override fun publish(logRecord: LogRecord) {\n logs += \"${logRecord.level}: ${logRecord.message}\"\n }\n\n override fun flush() {\n }\n\n override fun close() {\n }\n }\n\n private var previousLevel: Level? = null\n\n override fun beforeEach(context: ExtensionContext?) {\n previousLevel = logger.level\n logger.addHandler(handler)\n logger.setLevel(Level.FINEST)\n }\n\n override fun afterEach(context: ExtensionContext?) {\n logger.setLevel(previousLevel)\n logger.removeHandler(handler)\n }\n\n override fun apply(\n base: Statement,\n description: Description,\n ): Statement =\n object : Statement() {\n override fun evaluate() {\n beforeEach(null)\n try {\n base.evaluate()\n } finally {\n afterEach(null)\n }\n }\n }\n\n fun takeAll(): List {\n val list = mutableListOf()\n logs.drainTo"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":46,"symbol":"publish","kind":"function","lang":"kotlin","code":"override fun publish(logRecord: LogRecord) {\n logs += \"${logRecord.level}: ${logRecord.message}\"\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":50,"symbol":"flush","kind":"function","lang":"kotlin","code":"override fun flush() {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":53,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":59,"symbol":"beforeEach","kind":"function","lang":"kotlin","code":"override fun beforeEach(context: ExtensionContext?) {\n previousLevel = logger.level\n logger.addHandler(handler)\n logger.setLevel(Level.FINEST)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":65,"symbol":"afterEach","kind":"function","lang":"kotlin","code":"override fun afterEach(context: ExtensionContext?) {\n logger.setLevel(previousLevel)\n logger.removeHandler(handler)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":70,"symbol":"apply","kind":"function","lang":"kotlin","code":"override fun apply(\n base: Statement,\n description: Description,\n ): Statement =\n object : Statement() {\n override fun evaluate() {\n beforeEach(null)\n try {\n base.evaluate()\n } finally {\n afterEach(null)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":75,"symbol":"evaluate","kind":"function","lang":"kotlin","code":"override fun evaluate() {\n beforeEach(null)\n try {\n base.evaluate()\n } finally {\n afterEach(null)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":85,"symbol":"takeAll","kind":"function","lang":"kotlin","code":"fun takeAll(): List {\n val list = mutableListOf()\n logs.drainTo(list)\n return list\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestLogHandler.kt","line":91,"symbol":"take","kind":"function","lang":"kotlin","code":"fun take(): String =\n logs.poll(10, TimeUnit.SECONDS)\n ?: throw AssertionError(\"Timed out waiting for log message.\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestTls13Request.kt","line":51,"symbol":"testClient","kind":"function","lang":"kotlin","code":"private fun testClient(\n urls: List,\n client: OkHttpClient,\n) {\n try {\n for (url in urls) {\n sendRequest(client, url)\n }\n } finally {\n client.dispatcher.executorService.shutdownNow()\n client.connectionPool.evictAll()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestTls13Request.kt","line":65,"symbol":"buildClient","kind":"function","lang":"kotlin","code":"private fun buildClient(vararg specs: ConnectionSpec): OkHttpClient =\n OkHttpClient\n .Builder()\n .connectionSpecs(listOf(*specs))\n .build()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestTls13Request.kt","line":71,"symbol":"sendRequest","kind":"function","lang":"kotlin","code":"private fun sendRequest(\n client: OkHttpClient,\n url: String,\n) {\n System.out.printf(\"%-40s \", url)\n System.out.flush()\n println(Platform.get())\n val request =\n Request\n .Builder()\n .url(url)\n .build()\n try {\n client.newCall(request).execute().use { response ->\n val handshake = response.handshake\n println(\n \"${handshake!!.tlsVersion} ${handshake.cipherSuite} ${response.protocol} \" +\n \"${response.code} ${response.body.bytes().size}b\",\n )\n }\n } catch (ioe: IOException) {\n println(ioe)\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TestTls13Request.kt","line":96,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main(vararg args: String) {\n // System.setProperty(\"javax.net.debug\", \"ssl:handshake:verbose\");\n Security.insertProviderAt(Conscrypt.newProviderBuilder().provideTrustManager().build(), 1)\n println(\"Running tests using ${Platform.get()} ${System.getProperty(\"java.vm.version\")}\")\n\n // https://github.com/tlswg/tls13-spec/wiki/Implementations\n val urls =\n listOf(\n \"https://enabled.tls13.com\",\n \"https://www.howsmyssl.com/a/check\",\n \"https://tls13.cloudflare.com\",\n \"https://www.allizom.org/robots.txt\",\n \"https://tls13.crypto.mozilla.org/\",\n \"https://tls.ctf.network/robots.txt\",\n \"https://rustls.jbp.io/\",\n \"https://h2o.examp1e.net\",\n \"https://mew.org/\",\n \"https://tls13.baishancloud.com/\",\n \"https://tls13.akamai.io/\",\n \"https://swifttls.org/\",\n \"https://www.googleapis.com/robots.txt\",\n \"https://graph.facebook.com/robots.txt\",\n \"https://api.twitter.com/robots.txt\",\n \"https://connect.squareup.com/robots.txt\",\n )\n\n println(\"TLS1.3+TLS1.2\")\n testClient(urls, buildClient(ConnectionSpec.RESTRICTED_TLS))\n\n println(\"\\nTLS1.3 only\")\n testClient(urls, buildClient(TLS_13))\n\n println(\"\\nTLS1.3 then fall"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":54,"symbol":"TrailersTest","kind":"class","lang":"kotlin","code":"open class TrailersTest {\n private val fileSystem = FakeFileSystem()\n\n @JvmField\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private var client =\n clientTestRule\n .newClientBuilder()\n .cache(Cache(fileSystem, \"/cache/\".toPath(), Long.MAX_VALUE))\n .build()\n\n @Test\n fun trailersHttp1() {\n trailers(Protocol.HTTP_1_1)\n }\n\n @Test\n fun trailersHttp2() {\n trailers(Protocol.HTTP_2)\n }\n\n private fun trailers(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"h1\", \"v1\")\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, \"Hello\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n val source = response.body.source()\n assertThat(response.header(\"h1\")).isEqualTo(\"v1\")\n assertThat(source.readUtf8()).isEqualTo(\"Hello\")\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\")) // "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":73,"symbol":"trailersHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun trailersHttp1() {\n trailers(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":78,"symbol":"trailersHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun trailersHttp2() {\n trailers(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":83,"symbol":"trailers","kind":"function","lang":"kotlin","code":"private fun trailers(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"h1\", \"v1\")\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, \"Hello\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n val source = response.body.source()\n assertThat(response.header(\"h1\")).isEqualTo(\"v1\")\n assertThat(source.readUtf8()).isEqualTo(\"Hello\")\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\")) // Idempotent.\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":105,"symbol":"trailersEmptyResponseBodyHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun trailersEmptyResponseBodyHttp1() {\n trailersEmptyResponseBody(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":110,"symbol":"trailersEmptyResponseBodyHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun trailersEmptyResponseBodyHttp2() {\n trailersEmptyResponseBody(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":115,"symbol":"trailersEmptyResponseBody","kind":"function","lang":"kotlin","code":"private fun trailersEmptyResponseBody(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, \"\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n val source = response.body.source()\n assertThat(source.readUtf8()).isEqualTo(\"\")\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":134,"symbol":"trailersWithoutReadingFullResponseBodyHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun trailersWithoutReadingFullResponseBodyHttp1() {\n trailersWithoutReadingFullResponseBody(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":139,"symbol":"trailersWithoutReadingFullResponseBodyHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun trailersWithoutReadingFullResponseBodyHttp2() {\n trailersWithoutReadingFullResponseBody(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":144,"symbol":"trailersWithoutReadingFullResponseBody","kind":"function","lang":"kotlin","code":"private fun trailersWithoutReadingFullResponseBody(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, \"Hello\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n assertThat(response.body.source().exhausted()).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":162,"symbol":"trailersAndCacheHttp1","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun trailersAndCacheHttp1() {\n trailersAndCache(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":168,"symbol":"trailersAndCacheHttp2","kind":"function","lang":"kotlin","code":"@Test\n @Disabled\n fun trailersAndCacheHttp2() {\n trailersAndCache(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":174,"symbol":"trailersAndCache","kind":"function","lang":"kotlin","code":"private fun trailersAndCache(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"h1\", \"v1\")\n .addHeader(\"Cache-Control: max-age=30\")\n .body(protocol, \"Hello\")\n .trailers(headersOf(\"t1\", \"v2\"))\n .build(),\n )\n\n val call1 = client.newCall(Request(server.url(\"/\")))\n call1.execute().use { response ->\n val source = response.body.source()\n assertThat(response.header(\"h1\")).isEqualTo(\"v1\")\n assertThat(source.readUtf8()).isEqualTo(\"Hello\")\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n }\n\n val call2 = client.newCall(Request(server.url(\"/\")))\n call2.execute().use { response ->\n val source = response.body.source()\n assertThat(response.header(\"h1\")).isEqualTo(\"v1\")\n assertThat(source.readUtf8()).isEqualTo(\"Hello\")\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":204,"symbol":"delayBeforeTrailersHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun delayBeforeTrailersHttp1() {\n delayBeforeTrailers(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":209,"symbol":"delayBeforeTrailersHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun delayBeforeTrailersHttp2() {\n trailers(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":215,"symbol":"delayBeforeTrailers","kind":"function","lang":"kotlin","doc":"Confirm the client will block if necessary to consume trailers.","code":"private fun delayBeforeTrailers(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, \"Hello\")\n .trailersDelay(500, TimeUnit.MILLISECONDS)\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n val source = response.body.source()\n assertThat(source.readUtf8(5)).isEqualTo(\"Hello\")\n val trailersDelay =\n measureTime {\n val trailers = response.trailers()\n assertThat(trailers).isEqualTo(headersOf(\"t1\", \"v2\"))\n }\n assertThat(trailersDelay).isGreaterThan(250.milliseconds)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":240,"symbol":"disconnectBeforeTrailersHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun disconnectBeforeTrailersHttp1() {\n disconnectBeforeTrailers(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":245,"symbol":"disconnectBeforeTrailersHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun disconnectBeforeTrailersHttp2() {\n disconnectBeforeTrailers(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":251,"symbol":"disconnectBeforeTrailers","kind":"function","lang":"kotlin","doc":"Confirm we can get an [IOException] reading trailers.","code":"private fun disconnectBeforeTrailers(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, \"Hello\")\n .onResponseBody(CloseSocket())\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n assertFailsWith {\n response.trailers()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":271,"symbol":"cannotReadTrailersAfterEarlyResponseCloseHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun cannotReadTrailersAfterEarlyResponseCloseHttp1() {\n cannotReadTrailersAfterEarlyResponseClose(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":276,"symbol":"cannotReadTrailersAfterEarlyResponseCloseHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun cannotReadTrailersAfterEarlyResponseCloseHttp2() {\n cannotReadTrailersAfterEarlyResponseClose(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":281,"symbol":"cannotReadTrailersAfterEarlyResponseClose","kind":"function","lang":"kotlin","code":"private fun cannotReadTrailersAfterEarlyResponseClose(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .trailers(headersOf(\"t1\", \"v2\"))\n .bodyDelay(1, TimeUnit.SECONDS)\n .body(protocol, \"Hello\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n response.close()\n assertFailsWith {\n response.trailers()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":302,"symbol":"readTrailersAfterEarlyEofAndCloseHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun readTrailersAfterEarlyEofAndCloseHttp1() {\n readTrailersAfterEarlyEofAndClose(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":307,"symbol":"readTrailersAfterEarlyEofAndCloseHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun readTrailersAfterEarlyEofAndCloseHttp2() {\n readTrailersAfterEarlyEofAndClose(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":312,"symbol":"readTrailersAfterEarlyEofAndClose","kind":"function","lang":"kotlin","code":"private fun readTrailersAfterEarlyEofAndClose(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, \"Hello\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n assertThat(response.body.source().readUtf8()).isEqualTo(\"Hello\")\n response.body.source().close()\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":331,"symbol":"readEmptyTrailersHttp1EmptyFixedLengthResponse","kind":"function","lang":"kotlin","code":"@Test\n fun readEmptyTrailersHttp1EmptyFixedLengthResponse() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n assertThat(response.body.source().readUtf8()).isEqualTo(\"\")\n assertThat(response.trailers()).isEqualTo(Headers.EMPTY)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":347,"symbol":"readEmptyTrailersHttp1NonEmptyFixedLengthResponse","kind":"function","lang":"kotlin","code":"@Test\n fun readEmptyTrailersHttp1NonEmptyFixedLengthResponse() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n assertThat(response.body.source().readUtf8()).isEqualTo(\"Hello\")\n assertThat(response.trailers()).isEqualTo(Headers.EMPTY)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":363,"symbol":"readEmptyTrailersHttp1UnknownLengthResponse","kind":"function","lang":"kotlin","code":"@Test\n fun readEmptyTrailersHttp1UnknownLengthResponse() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello\")\n .removeHeader(\"Content-Length\")\n .onResponseEnd(ShutdownConnection)\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n assertThat(response.headers[\"Content-Length\"]).isNull()\n assertThat(response.body.source().readUtf8()).isEqualTo(\"Hello\")\n assertThat(response.trailers()).isEqualTo(Headers.EMPTY)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":382,"symbol":"cancelWhileReadingTrailersHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun cancelWhileReadingTrailersHttp1() {\n cancelWhileReadingTrailers(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":387,"symbol":"cancelWhileReadingTrailersHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun cancelWhileReadingTrailersHttp2() {\n cancelWhileReadingTrailers(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":392,"symbol":"cancelWhileReadingTrailers","kind":"function","lang":"kotlin","code":"private fun cancelWhileReadingTrailers(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"h1\", \"v1\")\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, \"Hello\")\n .trailersDelay(1, TimeUnit.SECONDS)\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n val source = response.body.source()\n assertThat(response.header(\"h1\")).isEqualTo(\"v1\")\n assertThat(source.readUtf8(5)).isEqualTo(\"Hello\")\n call.cancelLater(500.milliseconds)\n val trailersDelay =\n measureTime {\n val exception =\n assertFailsWith {\n response.trailers()\n }\n assertThat(exception.message).isIn(\n \"Socket closed\", // HTTP/1.1\n \"stream was reset: CANCEL\", // HTTP/2\n )\n }\n assertThat(trailersDelay).isGreaterThan(250.milliseconds)\n assertThat(trailersDelay).isLessThan(750.milliseconds)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":427,"symbol":"bufferResponseBodyAndReadTrailersHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun bufferResponseBodyAndReadTrailersHttp1() {\n bufferResponseBodyAndReadTrailers(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":432,"symbol":"bufferResponseBodyAndReadTrailersHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun bufferResponseBodyAndReadTrailersHttp2() {\n bufferResponseBodyAndReadTrailers(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":437,"symbol":"bufferResponseBodyAndReadTrailers","kind":"function","lang":"kotlin","code":"private fun bufferResponseBodyAndReadTrailers(protocol: Protocol) {\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .trailers(headersOf(\"t1\", \"v1\"))\n .body(protocol, \"Hello\")\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { originalResponse ->\n val responseBodyData = originalResponse.body.byteString()\n val responseTrailers = originalResponse.trailers()\n assertThat(responseTrailers).isEqualTo(headersOf(\"t1\", \"v1\"))\n\n val rewrittenResponse =\n originalResponse\n .newBuilder()\n .body(responseBodyData.toResponseBody())\n .build()\n assertThat(rewrittenResponse.body.string()).isEqualTo(\"Hello\")\n assertThat(rewrittenResponse.trailers()).isEqualTo(headersOf(\"t1\", \"v1\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":468,"symbol":"customTrailersDoNotUseResponseBody","kind":"function","lang":"kotlin","doc":"We had a bug where a custom `ResponseBody` interacted poorly with `Response.trailers()`. Confirm custom trailers can be read without even accessing the response body.","code":"@Test\n fun customTrailersDoNotUseResponseBody() {\n val response =\n Response\n .Builder()\n .request(Request(url = \"https://example.com\".toHttpUrl()))\n .protocol(Protocol.HTTP_1_1)\n .code(200)\n .message(\"OK\")\n .body(\n object : ResponseBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = -1L\n\n override fun source(): BufferedSource = error(\"unexpected call\")\n },\n ).trailers(\n object : TrailersSource {\n override fun get(): Headers = headersOf(\"t1\", \"v1\")\n },\n ).build()\n\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v1\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":479,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":481,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = -1L"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":483,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource = error(\"unexpected call\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":487,"symbol":"get","kind":"function","lang":"kotlin","code":"override fun get(): Headers = headersOf(\"t1\", \"v1\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":494,"symbol":"peekTrailersHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun peekTrailersHttp1() {\n peekTrailers(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":499,"symbol":"peekTrailersHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun peekTrailersHttp2() {\n peekTrailers(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":504,"symbol":"peekTrailers","kind":"function","lang":"kotlin","code":"private fun peekTrailers(protocol: Protocol) {\n val responseBody = \"a\".repeat(OKHTTP_CLIENT_WINDOW_SIZE)\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"h1\", \"v1\")\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, responseBody)\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n val source = response.body.source()\n assertThat(response.header(\"h1\")).isEqualTo(\"v1\")\n assertThat(response.peekTrailers()).isNull()\n assertThat(source.readUtf8()).isEqualTo(responseBody)\n assertThat(response.peekTrailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n assertThat(response.peekTrailers()).isEqualTo(headersOf(\"t1\", \"v2\")) // Idempotent.\n assertThat(response.trailers()).isEqualTo(headersOf(\"t1\", \"v2\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":529,"symbol":"trailersWithServerTruncatedResponseHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun trailersWithServerTruncatedResponseHttp1() {\n trailersWithServerTruncatedResponse(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":534,"symbol":"trailersWithServerTruncatedResponseHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun trailersWithServerTruncatedResponseHttp2() {\n trailersWithServerTruncatedResponse(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":543,"symbol":"trailersWithServerTruncatedResponse","kind":"function","lang":"kotlin","doc":"If the server closes the connection while the client is consuming the response body, attempts to peek or read the trailers should throw.","code":"private fun trailersWithServerTruncatedResponse(protocol: Protocol) {\n val responseBody = \"a\".repeat(OKHTTP_CLIENT_WINDOW_SIZE)\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"h1\", \"v1\")\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, responseBody)\n .onResponseBody(CloseSocket())\n .build(),\n )\n\n val call = client.newCall(Request(server.url(\"/\")))\n call.execute().use { response ->\n val source = response.body.source()\n assertThat(response.header(\"h1\")).isEqualTo(\"v1\")\n assertThat(response.peekTrailers()).isNull()\n assertFailsWith {\n source.readUtf8()\n }\n try {\n assertThat(response.peekTrailers()).isNull() // Okay. This is what HTTP/1 does.\n } catch (_: IOException) {\n // Also okay. This is what HTTP/2 does.\n }\n assertFailsWith {\n response.trailers()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":576,"symbol":"trailersWithClientPrematureCloseHttp1","kind":"function","lang":"kotlin","code":"@Test\n fun trailersWithClientPrematureCloseHttp1() {\n trailersWithClientPrematureClose(Protocol.HTTP_1_1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":581,"symbol":"trailersWithClientPrematureCloseHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun trailersWithClientPrematureCloseHttp2() {\n trailersWithClientPrematureClose(Protocol.HTTP_2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":599,"symbol":"trailersWithClientPrematureClose","kind":"function","lang":"kotlin","doc":"* Don't cache the response. The cache will try to read the entire response body so that it can successfully complete the cache entry. * Throttle the response. The HTTP/1 connection pool will attempt to read the entire response body so that it can pool the connection.","code":"private fun trailersWithClientPrematureClose(protocol: Protocol) {\n val halfResponseBody = \"a\".repeat(OKHTTP_CLIENT_WINDOW_SIZE)\n enableProtocol(protocol)\n\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"h1\", \"v1\")\n .trailers(headersOf(\"t1\", \"v2\"))\n .body(protocol, halfResponseBody + halfResponseBody)\n .throttleBody(\n OKHTTP_CLIENT_WINDOW_SIZE.toLong(),\n DISCARD_STREAM_TIMEOUT_MILLIS.toLong() + 1L,\n TimeUnit.MILLISECONDS,\n ).build(),\n )\n\n val call =\n client.newCall(\n Request(\n url = server.url(\"/\"),\n headers = headersOf(\"Cache-Control\", \"no-store\"),\n ),\n )\n call.execute().use { response ->\n val source = response.body.source()\n assertThat(response.header(\"h1\")).isEqualTo(\"v1\")\n assertThat(response.peekTrailers()).isNull()\n assertThat(source.readUtf8(halfResponseBody.length.toLong())).isEqualTo(halfResponseBody)\n source.close()\n assertFailsWith {\n source.readUtf8()\n }\n assertFailsWith {\n response.peekTrailers()\n }\n assertFailsWith {\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":641,"symbol":"body","kind":"function","lang":"kotlin","code":"private fun MockResponse.Builder.body(\n protocol: Protocol,\n body: String,\n ) = apply {\n when (protocol) {\n Protocol.HTTP_1_1 -> chunkedBody(body, 1024)\n\n // Force multiple chunks.\n else -> body(body)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":653,"symbol":"enableProtocol","kind":"function","lang":"kotlin","code":"private fun enableProtocol(protocol: Protocol) {\n if (protocol == Protocol.HTTP_2) {\n enableTls()\n client =\n client\n .newBuilder()\n .protocols(listOf(protocol, Protocol.HTTP_1_1))\n .build()\n server.protocols = client.protocols\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":665,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls() {\n val handshakeCertificates = platform.localhostHandshakeCertificates()\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/TrailersTest.kt","line":677,"symbol":"cancelLater","kind":"function","lang":"kotlin","code":"private fun Call.cancelLater(delay: Duration) {\n thread(name = \"canceler\") {\n sleep(delay.inWholeMilliseconds)\n cancel()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":131,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n server.protocolNegotiationEnabled = false\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":136,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n java.net.Authenticator.setDefault(null)\n System.clearProperty(\"proxyHost\")\n System.clearProperty(\"proxyPort\")\n System.clearProperty(\"http.proxyHost\")\n System.clearProperty(\"http.proxyPort\")\n System.clearProperty(\"https.proxyHost\")\n System.clearProperty(\"https.proxyPort\")\n if (cache != null) {\n cache!!.delete()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":150,"symbol":"requestHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun requestHeaders() {\n server.enqueue(MockResponse())\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .addHeader(\"D\", \"e\")\n .addHeader(\"D\", \"f\")\n .build()\n assertThat(request.header(\"D\")).isEqualTo(\"f\")\n assertThat(request.header(\"d\")).isEqualTo(\"f\")\n val requestHeaders = request.headers\n assertThat(LinkedHashSet(requestHeaders.values(\"D\"))).isEqualTo(newSet(\"e\", \"f\"))\n assertThat(LinkedHashSet(requestHeaders.values(\"d\"))).isEqualTo(newSet(\"e\", \"f\"))\n val response = getResponse(request)\n response.close()\n val recordedRequest = server.takeRequest()\n assertThat(recordedRequest.headers.values(\"D\")).isEqualTo(listOf(\"e\", \"f\"))\n assertThat(recordedRequest.headers[\"G\"]).isNull()\n assertThat(recordedRequest.headers[\"null\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":173,"symbol":"getRequestPropertyReturnsLastValue","kind":"function","lang":"kotlin","code":"@Test\n fun getRequestPropertyReturnsLastValue() {\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .addHeader(\"A\", \"value1\")\n .addHeader(\"A\", \"value2\")\n .build()\n assertThat(request.header(\"A\")).isEqualTo(\"value2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":185,"symbol":"responseHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun responseHeaders() {\n server.enqueue(\n MockResponse\n .Builder()\n .status(\"HTTP/1.0 200 Fantastic\")\n .addHeader(\"A: c\")\n .addHeader(\"B: d\")\n .addHeader(\"A: e\")\n .chunkedBody(\"ABCDE\\nFGHIJ\\nKLMNO\\nPQR\", 8)\n .build(),\n )\n val request = newRequest(\"/\")\n val response = getResponse(request)\n assertThat(response.code).isEqualTo(200)\n assertThat(response.message).isEqualTo(\"Fantastic\")\n val responseHeaders = response.headers\n assertThat(LinkedHashSet(responseHeaders.values(\"A\"))).isEqualTo(newSet(\"c\", \"e\"))\n assertThat(LinkedHashSet(responseHeaders.values(\"a\"))).isEqualTo(newSet(\"c\", \"e\"))\n assertThat(responseHeaders.name(0)).isEqualTo(\"A\")\n assertThat(responseHeaders.value(0)).isEqualTo(\"c\")\n assertThat(responseHeaders.name(1)).isEqualTo(\"B\")\n assertThat(responseHeaders.value(1)).isEqualTo(\"d\")\n assertThat(responseHeaders.name(2)).isEqualTo(\"A\")\n assertThat(responseHeaders.value(2)).isEqualTo(\"e\")\n response.body.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":213,"symbol":"serverSendsInvalidStatusLine","kind":"function","lang":"kotlin","code":"@Test\n fun serverSendsInvalidStatusLine() {\n server.enqueue(\n MockResponse\n .Builder()\n .status(\"HTP/1.1 200 OK\")\n .build(),\n )\n val request = newRequest(\"/\")\n assertFailsWith {\n getResponse(request)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":227,"symbol":"serverSendsInvalidCodeTooLarge","kind":"function","lang":"kotlin","code":"@Test\n fun serverSendsInvalidCodeTooLarge() {\n server.enqueue(\n MockResponse\n .Builder()\n .status(\"HTTP/1.1 2147483648 OK\")\n .build(),\n )\n val request = newRequest(\"/\")\n assertFailsWith {\n getResponse(request)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":241,"symbol":"serverSendsInvalidCodeNotANumber","kind":"function","lang":"kotlin","code":"@Test\n fun serverSendsInvalidCodeNotANumber() {\n server.enqueue(\n MockResponse\n .Builder()\n .status(\"HTTP/1.1 00a OK\")\n .build(),\n )\n val request = newRequest(\"/\")\n assertFailsWith {\n getResponse(request)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":255,"symbol":"serverSendsUnnecessaryWhitespace","kind":"function","lang":"kotlin","code":"@Test\n fun serverSendsUnnecessaryWhitespace() {\n server.enqueue(\n MockResponse\n .Builder()\n .status(\" HTTP/1.1 2147483648 OK\")\n .build(),\n )\n val request = newRequest(\"/\")\n assertFailsWith {\n getResponse(request)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":269,"symbol":"connectRetriesUntilConnectedOrFailed","kind":"function","lang":"kotlin","code":"@Test\n fun connectRetriesUntilConnectedOrFailed() {\n val request = newRequest(\"/foo\")\n server.close()\n assertFailsWith {\n getResponse(request)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":278,"symbol":"requestBodySurvivesRetriesWithFixedLength","kind":"function","lang":"kotlin","code":"@Test\n fun requestBodySurvivesRetriesWithFixedLength() {\n testRequestBodySurvivesRetries(TransferKind.FIXED_LENGTH)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":283,"symbol":"requestBodySurvivesRetriesWithChunkedStreaming","kind":"function","lang":"kotlin","code":"@Test\n fun requestBodySurvivesRetriesWithChunkedStreaming() {\n testRequestBodySurvivesRetries(TransferKind.CHUNKED)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":288,"symbol":"testRequestBodySurvivesRetries","kind":"function","lang":"kotlin","code":"private fun testRequestBodySurvivesRetries(transferKind: TransferKind) {\n server.enqueue(MockResponse(body = \"abc\"))\n\n // Use a misconfigured proxy to guarantee that the request is retried.\n client =\n client\n .newBuilder()\n .proxySelector(\n FakeProxySelector()\n .addProxy(server2.proxyAddress)\n .addProxy(Proxy.NO_PROXY),\n ).build()\n server2.close()\n val request =\n Request(\n url = server.url(\"/def\"),\n body = transferKind.newRequestBody(\"body\"),\n )\n val response = getResponse(request)\n assertContent(\"abc\", response)\n assertThat(server.takeRequest().body?.utf8()).isEqualTo(\"body\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":314,"symbol":"bug2939","kind":"function","lang":"kotlin","doc":"Check that if we don't read to the end of a response, the next request on the recycled connection doesn't get the unread tail of the first request's response. http://code.google.com/p/android/issues/detail?id=2939","code":"@Test\n fun bug2939() {\n val response =\n MockResponse\n .Builder()\n .chunkedBody(\"ABCDE\\nFGHIJ\\nKLMNO\\nPQR\", 8)\n .build()\n server.enqueue(response)\n server.enqueue(response)\n val request = newRequest(\"/\")\n val c1 = getResponse(request)\n assertContent(\"ABCDE\", c1, 5)\n val c2 = getResponse(request)\n assertContent(\"ABCDE\", c2, 5)\n c1.close()\n c2.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":332,"symbol":"connectionsArePooled","kind":"function","lang":"kotlin","code":"@Test\n fun connectionsArePooled() {\n val response =\n MockResponse(\n body = \"ABCDEFGHIJKLMNOPQR\",\n )\n server.enqueue(response)\n server.enqueue(response)\n server.enqueue(response)\n assertContent(\"ABCDEFGHIJKLMNOPQR\", getResponse(newRequest(\"/foo\")))\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertContent(\"ABCDEFGHIJKLMNOPQR\", getResponse(newRequest(\"/bar?baz=quux\")))\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n assertContent(\"ABCDEFGHIJKLMNOPQR\", getResponse(newRequest(\"/z\")))\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":349,"symbol":"chunkedConnectionsArePooled","kind":"function","lang":"kotlin","code":"@Test\n fun chunkedConnectionsArePooled() {\n val response =\n MockResponse\n .Builder()\n .chunkedBody(\"ABCDEFGHIJKLMNOPQR\", 5)\n .build()\n server.enqueue(response)\n server.enqueue(response)\n server.enqueue(response)\n assertContent(\"ABCDEFGHIJKLMNOPQR\", getResponse(newRequest(\"/foo\")))\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertContent(\"ABCDEFGHIJKLMNOPQR\", getResponse(newRequest(\"/bar?baz=quux\")))\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n assertContent(\"ABCDEFGHIJKLMNOPQR\", getResponse(newRequest(\"/z\")))\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":367,"symbol":"serverClosesSocket","kind":"function","lang":"kotlin","code":"@Test\n fun serverClosesSocket() {\n testServerClosesOutput(\n MockResponse\n .Builder()\n .body(\"This connection won't pool properly\")\n .onResponseEnd(ShutdownConnection)\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":378,"symbol":"serverShutdownInput","kind":"function","lang":"kotlin","code":"@Test\n fun serverShutdownInput() {\n testServerClosesOutput(\n MockResponse\n .Builder()\n .body(\"This connection won't pool properly\")\n .onResponseEnd(\n CloseSocket(\n closeSocket = false,\n shutdownInput = true,\n ),\n ).build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":393,"symbol":"serverShutdownOutput","kind":"function","lang":"kotlin","code":"@Test\n fun serverShutdownOutput() {\n testServerClosesOutput(\n MockResponse\n .Builder()\n .body(\"This connection won't pool properly\")\n .onResponseEnd(\n CloseSocket(\n closeSocket = false,\n shutdownOutput = true,\n ),\n ).build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":408,"symbol":"invalidHost","kind":"function","lang":"kotlin","code":"@Test\n fun invalidHost() {\n // Note that 1234.1.1.1 is an invalid host in a URI, but URL isn't as strict.\n client =\n client\n .newBuilder()\n .dns(FakeDns())\n .build()\n assertFailsWith {\n getResponse(\n Request\n .Builder()\n .url(\"http://1234.1.1.1/index.html\".toHttpUrl())\n .build(),\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":426,"symbol":"testServerClosesOutput","kind":"function","lang":"kotlin","code":"private fun testServerClosesOutput(mockResponse: MockResponse) {\n server.enqueue(mockResponse)\n val responseAfter = MockResponse(body = \"This comes after a busted connection\")\n server.enqueue(responseAfter)\n server.enqueue(responseAfter) // Enqueue 2x because the broken connection may be reused.\n val response1 = getResponse(newRequest(\"/a\"))\n response1.body\n .source()\n .timeout()\n .timeout(100, TimeUnit.MILLISECONDS)\n assertContent(\"This connection won't pool properly\", response1)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n\n // Give the server time to enact the socket policy if it's one that could happen after the\n // client has received the response.\n Thread.sleep(500)\n val response2 = getResponse(newRequest(\"/b\"))\n response1.body\n .source()\n .timeout()\n .timeout(100, TimeUnit.MILLISECONDS)\n assertContent(\"This comes after a busted connection\", response2)\n\n // Check that a fresh connection was created, either immediately or after attempting reuse.\n // We know that a fresh connection was created if the server recorded a request with sequence\n // number 0. Since the client may have att"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":462,"symbol":"WriteKind","kind":"enum","lang":"kotlin","code":"internal enum class WriteKind {\n BYTE_BY_BYTE,\n SMALL_BUFFERS,\n LARGE_BUFFERS,\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":463,"symbol":"BYTE_BY_BYTE","kind":"enum_member","lang":"kotlin","code":"BYTE_BY_BYTE"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":464,"symbol":"SMALL_BUFFERS","kind":"enum_member","lang":"kotlin","code":"SMALL_BUFFERS"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":465,"symbol":"LARGE_BUFFERS","kind":"enum_member","lang":"kotlin","code":"LARGE_BUFFERS"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":468,"symbol":"chunkedUpload_byteByByte","kind":"function","lang":"kotlin","code":"@Test\n fun chunkedUpload_byteByByte() {\n doUpload(TransferKind.CHUNKED, WriteKind.BYTE_BY_BYTE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":473,"symbol":"chunkedUpload_smallBuffers","kind":"function","lang":"kotlin","code":"@Test\n fun chunkedUpload_smallBuffers() {\n doUpload(TransferKind.CHUNKED, WriteKind.SMALL_BUFFERS)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":478,"symbol":"chunkedUpload_largeBuffers","kind":"function","lang":"kotlin","code":"@Test\n fun chunkedUpload_largeBuffers() {\n doUpload(TransferKind.CHUNKED, WriteKind.LARGE_BUFFERS)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":483,"symbol":"fixedLengthUpload_byteByByte","kind":"function","lang":"kotlin","code":"@Test\n fun fixedLengthUpload_byteByByte() {\n doUpload(TransferKind.FIXED_LENGTH, WriteKind.BYTE_BY_BYTE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":488,"symbol":"fixedLengthUpload_smallBuffers","kind":"function","lang":"kotlin","code":"@Test\n fun fixedLengthUpload_smallBuffers() {\n doUpload(TransferKind.FIXED_LENGTH, WriteKind.SMALL_BUFFERS)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":493,"symbol":"fixedLengthUpload_largeBuffers","kind":"function","lang":"kotlin","code":"@Test\n fun fixedLengthUpload_largeBuffers() {\n doUpload(TransferKind.FIXED_LENGTH, WriteKind.LARGE_BUFFERS)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":498,"symbol":"doUpload","kind":"function","lang":"kotlin","code":"private fun doUpload(\n uploadKind: TransferKind,\n writeKind: WriteKind,\n ) {\n val n = 512 * 1024\n server.bodyLimit = 0\n server.enqueue(MockResponse())\n val requestBody: RequestBody =\n object : RequestBody() {\n override fun contentType(): MediaType? = null\n\n override fun contentLength(): Long = if (uploadKind === TransferKind.CHUNKED) -1L else n.toLong()\n\n override fun writeTo(sink: BufferedSink) {\n if (writeKind == WriteKind.BYTE_BY_BYTE) {\n for (i in 0 until n) {\n sink.writeByte('x'.code)\n }\n } else {\n val buf = ByteArray(if (writeKind == WriteKind.SMALL_BUFFERS) 256 else 64 * 1024)\n Arrays.fill(buf, 'x'.code.toByte())\n var i = 0\n while (i < n) {\n sink.write(buf, 0, Math.min(buf.size, n - i))\n i += buf.size\n }\n }\n }\n }\n val response =\n getResponse(\n Request(\n url = server.url(\"/\"),\n body = requestBody,\n ),\n )\n assertThat(response.code).isEqualTo(200)\n val request = server.takeRequest()\n assertThat(request.bodySize).isEqualTo(n.toLo"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":507,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":509,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = if (uploadKind === TransferKind.CHUNKED) -1L else n.toLong()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":511,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n if (writeKind == WriteKind.BYTE_BY_BYTE) {\n for (i in 0 until n) {\n sink.writeByte('x'.code)\n }\n } else {\n val buf = ByteArray(if (writeKind == WriteKind.SMALL_BUFFERS) 256 else 64 * 1024)\n Arrays.fill(buf, 'x'.code.toByte())\n var i = 0\n while (i < n) {\n sink.write(buf, 0, Math.min(buf.size, n - i))\n i += buf.size\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":544,"symbol":"connectViaHttps","kind":"function","lang":"kotlin","code":"@Test\n fun connectViaHttps() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(MockResponse(body = \"this response comes via HTTPS\"))\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n val response = getResponse(newRequest(\"/foo\"))\n assertContent(\"this response comes via HTTPS\", response)\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"GET /foo HTTP/1.1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":562,"symbol":"connectViaHttpsReusingConnections","kind":"function","lang":"kotlin","code":"@Test\n fun connectViaHttpsReusingConnections() {\n connectViaHttpsReusingConnections(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":567,"symbol":"connectViaHttpsReusingConnectionsAfterRebuildingClient","kind":"function","lang":"kotlin","code":"@Test\n fun connectViaHttpsReusingConnectionsAfterRebuildingClient() {\n connectViaHttpsReusingConnections(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":572,"symbol":"connectViaHttpsReusingConnections","kind":"function","lang":"kotlin","code":"private fun connectViaHttpsReusingConnections(rebuildClient: Boolean) {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(MockResponse(body = \"this response comes via HTTPS\"))\n server.enqueue(MockResponse(body = \"another response via HTTPS\"))\n\n // The pool will only reuse sockets if the SSL socket factories are the same.\n val clientSocketFactory = handshakeCertificates.sslSocketFactory()\n val hostnameVerifier = RecordingHostnameVerifier()\n val cookieJar: CookieJar = JavaNetCookieJar(CookieManager())\n val connectionPool = ConnectionPool()\n client =\n OkHttpClient\n .Builder()\n .cache(cache)\n .connectionPool(connectionPool)\n .cookieJar(cookieJar)\n .sslSocketFactory(clientSocketFactory, handshakeCertificates.trustManager)\n .hostnameVerifier(hostnameVerifier)\n .build()\n val response1 = getResponse(newRequest(\"/\"))\n assertContent(\"this response comes via HTTPS\", response1)\n if (rebuildClient) {\n client =\n OkHttpClient\n .Builder()\n .cache(cache)\n .connectionPool(connectionPool)\n .cookieJar(cookieJar)\n .sslSocketFactory(c"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":610,"symbol":"connectViaHttpsReusingConnectionsDifferentFactories","kind":"function","lang":"kotlin","code":"@Test\n fun connectViaHttpsReusingConnectionsDifferentFactories() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(MockResponse(body = \"this response comes via HTTPS\"))\n server.enqueue(MockResponse(body = \"another response via HTTPS\"))\n\n // install a custom SSL socket factory so the server can be authorized\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n val response1 = getResponse(newRequest(\"/\"))\n assertContent(\"this response comes via HTTPS\", response1)\n val sslContext2 = Platform.get().newSSLContext()\n sslContext2.init(null, null, null)\n val sslSocketFactory2 = sslContext2.socketFactory\n val trustManagerFactory =\n TrustManagerFactory.getInstance(\n TrustManagerFactory.getDefaultAlgorithm(),\n )\n trustManagerFactory.init(null as KeyStore?)\n val trustManager = trustManagerFactory.trustManagers[0] as X509TrustManager\n client =\n client\n .newBuilder()\n .sslSocketFactory(sslSocketFactory2,"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":655,"symbol":"connectViaHttpsWithSSLFallback","kind":"function","lang":"kotlin","doc":"TODO(jwilson): tests below this marker need to be migrated to OkHttp's request/response API.","code":"@Test\n fun connectViaHttpsWithSSLFallback() {\n platform.assumeNotBouncyCastle()\n\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(MockResponse.Builder().failHandshake().build())\n server.enqueue(MockResponse(body = \"this response comes via SSL\"))\n client =\n client\n .newBuilder()\n .hostnameVerifier(\n RecordingHostnameVerifier(),\n ) // Attempt RESTRICTED_TLS then fall back to MODERN_TLS.\n .connectionSpecs(Arrays.asList(ConnectionSpec.RESTRICTED_TLS, ConnectionSpec.MODERN_TLS))\n .sslSocketFactory(\n suppressTlsFallbackClientSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n val response = getResponse(newRequest(\"/foo\"))\n assertContent(\"this response comes via SSL\", response)\n val failHandshakeRequest = server.takeRequest()\n assertThat(failHandshakeRequest.requestLine).isEqualTo(\"GET / HTTP/1.1\")\n val fallbackRequest = server.takeRequest()\n assertThat(fallbackRequest.requestLine).isEqualTo(\"GET /foo HTTP/1.1\")\n assertThat(fallbackRequest.handshake?.tlsVersion).isIn(TlsVersion.TLS_1_2, TlsVersion.TLS_1_3)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":682,"symbol":"connectViaHttpsWithSSLFallbackFailuresRecorded","kind":"function","lang":"kotlin","code":"@Test\n fun connectViaHttpsWithSSLFallbackFailuresRecorded() {\n platform.assumeNotBouncyCastle()\n\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(MockResponse.Builder().failHandshake().build())\n server.enqueue(MockResponse.Builder().failHandshake().build())\n client =\n client\n .newBuilder()\n .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))\n .hostnameVerifier(RecordingHostnameVerifier())\n .sslSocketFactory(\n suppressTlsFallbackClientSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n assertFailsWith {\n getResponse(newRequest(\"/foo\"))\n }.also { expected ->\n expected.assertSuppressed { throwables: List? ->\n assertThat(throwables!!.size).isEqualTo(1)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":713,"symbol":"sslFallbackNotUsedWhenRecycledConnectionFails","kind":"function","lang":"kotlin","doc":"When a pooled connection fails, don't blame the route. Otherwise pooled connection failures can cause unnecessary SSL fallbacks. https://github.com/lysine-dev/okhttp/issues/515","code":"@Test\n fun sslFallbackNotUsedWhenRecycledConnectionFails() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .onResponseEnd(ShutdownConnection)\n .build(),\n )\n server.enqueue(MockResponse(body = \"def\"))\n client =\n client\n .newBuilder()\n .hostnameVerifier(RecordingHostnameVerifier())\n .sslSocketFactory(\n suppressTlsFallbackClientSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n assertContent(\"abc\", getResponse(newRequest(\"/\")))\n\n // Give the server time to disconnect.\n Thread.sleep(500)\n assertContent(\"def\", getResponse(newRequest(\"/\")))\n val tlsVersions: Set =\n EnumSet.of(\n TlsVersion.TLS_1_0,\n TlsVersion.TLS_1_2,\n TlsVersion.TLS_1_3,\n ) // v1.2 on OpenJDK 8.\n val request1 = server.takeRequest()\n assertThat(tlsVersions).contains(request1.handshake?.tlsVersion)\n val request2 = server.takeRequest()\n assertThat(tlsVersions).contains(request2.handshake?.tlsVersion)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":754,"symbol":"connectViaHttpsToUntrustedServer","kind":"function","lang":"kotlin","doc":"Verify that we don't retry connections on certificate verification errors. http://code.google.com/p/android/issues/detail?id=13178","code":"@Flaky\n @Test\n fun connectViaHttpsToUntrustedServer() {\n // Flaky https://github.com/lysine-dev/okhttp/issues/5222\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.enqueue(MockResponse()) // unused\n assertFailsWith {\n getResponse(newRequest(\"/foo\"))\n }.also { expected ->\n when (expected) {\n is SSLHandshakeException -> {\n // Allow conscrypt to fail in different ways\n if (!platform.isConscrypt()) {\n assertThat(expected.cause!!).isInstanceOf()\n }\n }\n\n is TlsFatalAlert -> {}\n\n else -> {\n throw expected\n }\n }\n }\n assertThat(server.requestCount).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":781,"symbol":"connectViaProxyUsingProxyArg","kind":"function","lang":"kotlin","code":"@Test\n fun connectViaProxyUsingProxyArg() {\n testConnectViaProxy(ProxyConfig.CREATE_ARG)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":786,"symbol":"connectViaProxyUsingProxySystemProperty","kind":"function","lang":"kotlin","code":"@Test\n fun connectViaProxyUsingProxySystemProperty() {\n testConnectViaProxy(ProxyConfig.PROXY_SYSTEM_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":791,"symbol":"connectViaProxyUsingHttpProxySystemProperty","kind":"function","lang":"kotlin","code":"@Test\n fun connectViaProxyUsingHttpProxySystemProperty() {\n testConnectViaProxy(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":796,"symbol":"testConnectViaProxy","kind":"function","lang":"kotlin","code":"private fun testConnectViaProxy(proxyConfig: ProxyConfig) {\n server.enqueue(\n MockResponse(body = \"this response comes via a proxy\"),\n )\n val url = \"http://android.com/foo\".toHttpUrl()\n val response = proxyConfig.connect(server, client, url).execute()\n assertContent(\"this response comes via a proxy\", response)\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\n \"GET http://android.com/foo HTTP/1.1\",\n )\n assertThat(request.headers[\"Host\"]).isEqualTo(\"android.com\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":810,"symbol":"contentDisagreesWithContentLengthHeaderBodyTooLong","kind":"function","lang":"kotlin","code":"@Test\n fun contentDisagreesWithContentLengthHeaderBodyTooLong() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\\r\\nYOU SHOULD NOT SEE THIS\")\n .clearHeaders()\n .addHeader(\"Content-Length: 3\")\n .build(),\n )\n assertContent(\"abc\", getResponse(newRequest(\"/\")))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":823,"symbol":"contentDisagreesWithContentLengthHeaderBodyTooShort","kind":"function","lang":"kotlin","code":"@Test\n fun contentDisagreesWithContentLengthHeaderBodyTooShort() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .setHeader(\"Content-Length\", \"5\")\n .onResponseEnd(ShutdownConnection)\n .build(),\n )\n assertFailsWith {\n val response = getResponse(newRequest(\"/\"))\n response.body.source().readUtf8(5)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":839,"symbol":"testConnectViaSocketFactory","kind":"function","lang":"kotlin","code":"private fun testConnectViaSocketFactory(useHttps: Boolean) {\n val uselessSocketFactory: SocketFactory =\n object : SocketFactory() {\n override fun createSocket(): Socket = throw IllegalArgumentException(\"useless\")\n\n override fun createSocket(\n host: InetAddress,\n port: Int,\n ): Socket? = null\n\n override fun createSocket(\n address: InetAddress,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): Socket? = null\n\n override fun createSocket(\n host: String,\n port: Int,\n ): Socket? = null\n\n override fun createSocket(\n host: String,\n port: Int,\n localHost: InetAddress,\n localPort: Int,\n ): Socket? = null\n }\n if (useHttps) {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n }\n server.enqueue(MockResponse())\n client =\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":842,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(): Socket = throw IllegalArgumentException(\"useless\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":844,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: InetAddress,\n port: Int,\n ): Socket? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":849,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n address: InetAddress,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): Socket? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":856,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: String,\n port: Int,\n ): Socket? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":861,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: String,\n port: Int,\n localHost: InetAddress,\n localPort: Int,\n ): Socket? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":897,"symbol":"connectHttpViaSocketFactory","kind":"function","lang":"kotlin","code":"@Test\n fun connectHttpViaSocketFactory() {\n testConnectViaSocketFactory(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":902,"symbol":"connectHttpsViaSocketFactory","kind":"function","lang":"kotlin","code":"@Test\n fun connectHttpsViaSocketFactory() {\n testConnectViaSocketFactory(true)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":907,"symbol":"contentDisagreesWithChunkedHeaderBodyTooLong","kind":"function","lang":"kotlin","code":"@Test\n fun contentDisagreesWithChunkedHeaderBodyTooLong() {\n val builder =\n MockResponse\n .Builder()\n .chunkedBody(\"abc\", 3)\n val buffer = Buffer()\n builder.body!!.writeTo(buffer)\n buffer.writeUtf8(\"\\r\\nYOU SHOULD NOT SEE THIS\")\n builder.body(buffer)\n builder.clearHeaders()\n builder.addHeader(\"Transfer-encoding: chunked\")\n server.enqueue(builder.build())\n assertContent(\"abc\", getResponse(newRequest(\"/\")))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/URLConnectionTest.kt","line":923,"symbol":"contentDisagreesWithChunkedHeaderBodyTooShort","kind":"function","lang":"kotlin","code":"@Test\n fun contentDisagreesWithChunkedHeaderBodyTooShort() {\n val builder =\n MockResponse\n .Builder()\n .chunkedBody(\"abcdefg\", 5)\n val fullBody = Buffer()\n builder.body!!.writeTo(fullBody)\n val truncatedBody = Buffer()\n truncatedBody.write(fullBody, 4)\n builder.body(truncatedBody)\n builder.clearHeaders()\n builder.addHeader(\"Transfer-encoding: chunked\")\n builder.onResponseEnd(ShutdownConnection)\n server.enqueue(builder.build())\n assertFailsWith {\n val response = getResponse(newRequest(\"/\"))\n response.body.source().readUtf8(7)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":33,"symbol":"UrlComponentEncodingTester","kind":"class","lang":"kotlin","doc":"Tests how each code point is encoded and decoded in the context of each URL component. This supports [HttpUrlTest].","code":"class UrlComponentEncodingTester private constructor() {\n private val encodings: MutableMap = LinkedHashMap()\n\n private fun allAscii(encoding: Encoding) =\n apply {\n for (i in 0..127) {\n encodings[i] = encoding\n }\n }\n\n fun override(\n encoding: Encoding,\n vararg codePoints: Int,\n ) = apply {\n for (codePoint in codePoints) {\n encodings[codePoint] = encoding\n }\n }\n\n fun nonPrintableAscii(encoding: Encoding) =\n apply {\n encodings[0x0] = encoding // Null character\n encodings[0x1] = encoding // Start of Header\n encodings[0x2] = encoding // Start of Text\n encodings[0x3] = encoding // End of Text\n encodings[0x4] = encoding // End of Transmission\n encodings[0x5] = encoding // Enquiry\n encodings[0x6] = encoding // Acknowledgment\n encodings[0x7] = encoding // Bell\n encodings['\\b'.code] = encoding // Backspace\n encodings[0xb] = encoding // Vertical Tab\n encodings[0xe] = encoding // Shift Out\n encodings[0xf] = encoding // Shift In\n encodings[0x10] = encoding // Data Link Escape\n encodings[0x11] = encoding // Device Control 1 (oft. XON)\n encodings[0x12] = enco"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":36,"symbol":"allAscii","kind":"function","lang":"kotlin","code":"private fun allAscii(encoding: Encoding) =\n apply {\n for (i in 0..127) {\n encodings[i] = encoding\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":43,"symbol":"override","kind":"function","lang":"kotlin","code":"fun override(\n encoding: Encoding,\n vararg codePoints: Int,\n ) = apply {\n for (codePoint in codePoints) {\n encodings[codePoint] = encoding\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":52,"symbol":"nonPrintableAscii","kind":"function","lang":"kotlin","code":"fun nonPrintableAscii(encoding: Encoding) =\n apply {\n encodings[0x0] = encoding // Null character\n encodings[0x1] = encoding // Start of Header\n encodings[0x2] = encoding // Start of Text\n encodings[0x3] = encoding // End of Text\n encodings[0x4] = encoding // End of Transmission\n encodings[0x5] = encoding // Enquiry\n encodings[0x6] = encoding // Acknowledgment\n encodings[0x7] = encoding // Bell\n encodings['\\b'.code] = encoding // Backspace\n encodings[0xb] = encoding // Vertical Tab\n encodings[0xe] = encoding // Shift Out\n encodings[0xf] = encoding // Shift In\n encodings[0x10] = encoding // Data Link Escape\n encodings[0x11] = encoding // Device Control 1 (oft. XON)\n encodings[0x12] = encoding // Device Control 2\n encodings[0x13] = encoding // Device Control 3 (oft. XOFF)\n encodings[0x14] = encoding // Device Control 4\n encodings[0x15] = encoding // Negative Acknowledgment\n encodings[0x16] = encoding // Synchronous idle\n encodings[0x17] = encoding // End of Transmission Block\n encodings[0x18] = encoding // Cancel\n encodings[0x19] = encoding // End of Medium\n encodings"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":85,"symbol":"nonAscii","kind":"function","lang":"kotlin","code":"fun nonAscii(encoding: Encoding) =\n apply {\n encodings[UNICODE_2] = encoding\n encodings[UNICODE_3] = encoding\n encodings[UNICODE_4] = encoding\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":92,"symbol":"test","kind":"function","lang":"kotlin","code":"fun test(component: Component) =\n apply {\n for ((codePoint, encoding) in encodings) {\n val codePointString = Encoding.IDENTITY.encode(codePoint)\n if (encoding == Encoding.FORBIDDEN) {\n testForbidden(codePoint, codePointString, component)\n continue\n }\n if (encoding == Encoding.PUNYCODE) {\n testPunycode(codePointString, component)\n continue\n }\n testEncodeAndDecode(codePoint, codePointString, component)\n if (encoding == Encoding.SKIP) continue\n testParseOriginal(codePoint, codePointString, encoding, component)\n testParseAlreadyEncoded(codePoint, encoding, component)\n\n val platform = urlComponentEncodingTesterJvmPlatform(component)\n platform.test(codePoint, codePointString, encoding, component)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":114,"symbol":"testParseAlreadyEncoded","kind":"function","lang":"kotlin","code":"private fun testParseAlreadyEncoded(\n codePoint: Int,\n encoding: Encoding,\n component: Component,\n ) {\n val expected = component.canonicalize(encoding.encode(codePoint))\n val urlString = component.urlString(expected)\n val url = urlString.toHttpUrl()\n val actual = component.encodedValue(url)\n if (actual != expected) {\n fail(\"Encoding $component $codePoint using $encoding: '$actual' != '$expected'\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":128,"symbol":"testEncodeAndDecode","kind":"function","lang":"kotlin","code":"private fun testEncodeAndDecode(\n codePoint: Int,\n codePointString: String,\n component: Component,\n ) {\n val builder = \"http://host/\".toHttpUrl().newBuilder()\n component[builder] = codePointString\n val url = builder.build()\n val expected = component.canonicalize(codePointString)\n val actual = component[url]\n if (expected != actual) {\n fail(\"Roundtrip $component $codePoint $url $expected != $actual\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":143,"symbol":"testParseOriginal","kind":"function","lang":"kotlin","code":"private fun testParseOriginal(\n codePoint: Int,\n codePointString: String,\n encoding: Encoding,\n component: Component,\n ) {\n val expected = encoding.encode(codePoint)\n if (encoding !== Encoding.PERCENT) return\n val urlString = component.urlString(codePointString)\n val url = urlString.toHttpUrl()\n val actual = component.encodedValue(url)\n if (actual != expected) {\n fail(\"Encoding $component $codePoint using $encoding: '$actual' != '$expected'\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":159,"symbol":"testForbidden","kind":"function","lang":"kotlin","code":"private fun testForbidden(\n codePoint: Int,\n codePointString: String,\n component: Component,\n ) {\n val builder = \"http://host/\".toHttpUrl().newBuilder()\n assertFailsWith {\n component[builder] = codePointString\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":170,"symbol":"testPunycode","kind":"function","lang":"kotlin","code":"private fun testPunycode(\n codePointString: String,\n component: Component,\n ) {\n val builder = \"http://host/\".toHttpUrl().newBuilder()\n component[builder] = codePointString"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":180,"symbol":"Encoding","kind":"enum","lang":"kotlin","code":"enum class Encoding {\n IDENTITY {\n override fun encode(codePoint: Int): String = String(codePoint)\n },\n PERCENT {\n override fun encode(codePoint: Int): String {\n val utf8 = IDENTITY.encode(codePoint).encodeUtf8()\n val percentEncoded = Buffer()\n for (i in 0 until utf8.size) {\n percentEncoded\n .writeUtf8(\"%\")\n .writeUtf8(ByteString.of(utf8[i]).hex().uppercase())\n }\n return percentEncoded.readUtf8()\n }\n },\n\n /** URLs that contain this character in this component are invalid. */\n FORBIDDEN,\n\n /** Hostnames that contain this character are encoded with punycode. */\n PUNYCODE,\n\n /** This code point is special and should not be tested. */\n SKIP,\n\n ;\n\n open fun encode(codePoint: Int): String = throw UnsupportedOperationException()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":181,"symbol":"IDENTITY","kind":"enum_member","lang":"kotlin","code":"IDENTITY {\n override fun encode(codePoint: Int): String = String(codePoint)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":182,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(codePoint: Int): String = String(codePoint)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":184,"symbol":"PERCENT","kind":"enum_member","lang":"kotlin","code":"PERCENT {\n override fun encode(codePoint: Int): String {\n val utf8 = IDENTITY.encode(codePoint).encodeUtf8()\n val percentEncoded = Buffer()\n for (i in 0 until utf8.size) {\n percentEncoded\n .writeUtf8(\"%\")\n .writeUtf8(ByteString.of(utf8[i]).hex().uppercase())\n }\n return percentEncoded.readUtf8()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":185,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(codePoint: Int): String {\n val utf8 = IDENTITY.encode(codePoint).encodeUtf8()\n val percentEncoded = Buffer()\n for (i in 0 until utf8.size) {\n percentEncoded\n .writeUtf8(\"%\")\n .writeUtf8(ByteString.of(utf8[i]).hex().uppercase())\n }\n return percentEncoded.readUtf8()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":198,"symbol":"FORBIDDEN","kind":"enum_member","lang":"kotlin","doc":"URLs that contain this character in this component are invalid.","code":"FORBIDDEN"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":201,"symbol":"PUNYCODE","kind":"enum_member","lang":"kotlin","doc":"Hostnames that contain this character are encoded with punycode.","code":"PUNYCODE"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":204,"symbol":"SKIP","kind":"enum_member","lang":"kotlin","doc":"This code point is special and should not be tested.","code":"SKIP"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":208,"symbol":"encode","kind":"function","lang":"kotlin","code":"open fun encode(codePoint: Int): String = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":211,"symbol":"Component","kind":"enum","lang":"kotlin","code":"enum class Component {\n USER {\n override fun urlString(value: String): String = \"http://$value@example.com/\"\n\n override fun encodedValue(url: HttpUrl): String = url.encodedUsername\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.username(value)\n }\n\n override operator fun get(url: HttpUrl): String = url.username\n },\n\n PASSWORD {\n override fun urlString(value: String): String = \"http://:$value@example.com/\"\n\n override fun encodedValue(url: HttpUrl): String = url.encodedPassword\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.password(value)\n }\n\n override operator fun get(url: HttpUrl): String = url.password\n },\n\n HOST {\n override fun urlString(value: String): String = \"http://a${value}z.com/\"\n\n override fun encodedValue(url: HttpUrl): String = get(url)\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.host(\"a${value}z.com\")\n }\n\n override operator fun get(url: HttpUrl): String {\n val host = url.host\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":212,"symbol":"USER","kind":"enum_member","lang":"kotlin","code":"USER {\n override fun urlString(value: String): String = \"http://$value@example.com/\"\n\n override fun encodedValue(url: HttpUrl): String = url.encodedUsername\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.username(value)\n }\n\n override operator fun get(url: HttpUrl): String = url.username\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":213,"symbol":"urlString","kind":"function","lang":"kotlin","code":"override fun urlString(value: String): String = \"http://$value@example.com/\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":215,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"override fun encodedValue(url: HttpUrl): String = url.encodedUsername"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":217,"symbol":"set","kind":"function","lang":"kotlin","code":"override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.username(value)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":224,"symbol":"get","kind":"function","lang":"kotlin","code":"override operator fun get(url: HttpUrl): String = url.username"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":227,"symbol":"PASSWORD","kind":"enum_member","lang":"kotlin","code":"PASSWORD {\n override fun urlString(value: String): String = \"http://:$value@example.com/\"\n\n override fun encodedValue(url: HttpUrl): String = url.encodedPassword\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.password(value)\n }\n\n override operator fun get(url: HttpUrl): String = url.password\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":228,"symbol":"urlString","kind":"function","lang":"kotlin","code":"override fun urlString(value: String): String = \"http://:$value@example.com/\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":230,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"override fun encodedValue(url: HttpUrl): String = url.encodedPassword"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":232,"symbol":"set","kind":"function","lang":"kotlin","code":"override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.password(value)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":239,"symbol":"get","kind":"function","lang":"kotlin","code":"override operator fun get(url: HttpUrl): String = url.password"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":242,"symbol":"HOST","kind":"enum_member","lang":"kotlin","code":"HOST {\n override fun urlString(value: String): String = \"http://a${value}z.com/\"\n\n override fun encodedValue(url: HttpUrl): String = get(url)\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.host(\"a${value}z.com\")\n }\n\n override operator fun get(url: HttpUrl): String {\n val host = url.host\n return host.substring(1, host.length - 5).lowercase()\n }\n\n override fun canonicalize(s: String): String = s.lowercase()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":243,"symbol":"urlString","kind":"function","lang":"kotlin","code":"override fun urlString(value: String): String = \"http://a${value}z.com/\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":245,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"override fun encodedValue(url: HttpUrl): String = get(url)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":247,"symbol":"set","kind":"function","lang":"kotlin","code":"override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.host(\"a${value}z.com\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":254,"symbol":"get","kind":"function","lang":"kotlin","code":"override operator fun get(url: HttpUrl): String {\n val host = url.host\n return host.substring(1, host.length - 5).lowercase()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":259,"symbol":"canonicalize","kind":"function","lang":"kotlin","code":"override fun canonicalize(s: String): String = s.lowercase()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":262,"symbol":"PATH","kind":"enum_member","lang":"kotlin","code":"PATH {\n override fun urlString(value: String): String = \"http://example.com/a${value}z/\"\n\n override fun encodedValue(url: HttpUrl): String {\n val path = url.encodedPath\n return path.substring(2, path.length - 2)\n }\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.addPathSegment(\"a${value}z\")\n }\n\n override operator fun get(url: HttpUrl): String {\n val pathSegment = url.pathSegments[0]\n return pathSegment.substring(1, pathSegment.length - 1)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":263,"symbol":"urlString","kind":"function","lang":"kotlin","code":"override fun urlString(value: String): String = \"http://example.com/a${value}z/\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":265,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"override fun encodedValue(url: HttpUrl): String {\n val path = url.encodedPath\n return path.substring(2, path.length - 2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":270,"symbol":"set","kind":"function","lang":"kotlin","code":"override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.addPathSegment(\"a${value}z\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":277,"symbol":"get","kind":"function","lang":"kotlin","code":"override operator fun get(url: HttpUrl): String {\n val pathSegment = url.pathSegments[0]\n return pathSegment.substring(1, pathSegment.length - 1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":283,"symbol":"QUERY","kind":"enum_member","lang":"kotlin","code":"QUERY {\n override fun urlString(value: String): String = \"http://example.com/?a${value}z\"\n\n override fun encodedValue(url: HttpUrl): String {\n val query = url.encodedQuery\n return query!!.substring(1, query.length - 1)\n }\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.query(\"a${value}z\")\n }\n\n override operator fun get(url: HttpUrl): String {\n val query = url.query\n return query!!.substring(1, query.length - 1)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":284,"symbol":"urlString","kind":"function","lang":"kotlin","code":"override fun urlString(value: String): String = \"http://example.com/?a${value}z\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":286,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"override fun encodedValue(url: HttpUrl): String {\n val query = url.encodedQuery\n return query!!.substring(1, query.length - 1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":291,"symbol":"set","kind":"function","lang":"kotlin","code":"override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.query(\"a${value}z\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":298,"symbol":"get","kind":"function","lang":"kotlin","code":"override operator fun get(url: HttpUrl): String {\n val query = url.query\n return query!!.substring(1, query.length - 1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":304,"symbol":"QUERY_VALUE","kind":"enum_member","lang":"kotlin","code":"QUERY_VALUE {\n override fun urlString(value: String): String = \"http://example.com/?q=a${value}z\"\n\n override fun encodedValue(url: HttpUrl): String {\n val query = url.encodedQuery\n return query!!.substring(3, query.length - 1)\n }\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.addQueryParameter(\"q\", \"a${value}z\")\n }\n\n override operator fun get(url: HttpUrl): String {\n val value = url.queryParameter(\"q\")\n return value!!.substring(1, value.length - 1)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":305,"symbol":"urlString","kind":"function","lang":"kotlin","code":"override fun urlString(value: String): String = \"http://example.com/?q=a${value}z\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":307,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"override fun encodedValue(url: HttpUrl): String {\n val query = url.encodedQuery\n return query!!.substring(3, query.length - 1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":312,"symbol":"set","kind":"function","lang":"kotlin","code":"override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.addQueryParameter(\"q\", \"a${value}z\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":319,"symbol":"get","kind":"function","lang":"kotlin","code":"override operator fun get(url: HttpUrl): String {\n val value = url.queryParameter(\"q\")\n return value!!.substring(1, value.length - 1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":325,"symbol":"FRAGMENT","kind":"enum_member","lang":"kotlin","code":"FRAGMENT {\n override fun urlString(value: String): String = \"http://example.com/#a${value}z\"\n\n override fun encodedValue(url: HttpUrl): String {\n val fragment = url.encodedFragment\n return fragment!!.substring(1, fragment.length - 1)\n }\n\n override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.fragment(\"a${value}z\")\n }\n\n override operator fun get(url: HttpUrl): String {\n val fragment = url.fragment\n return fragment!!.substring(1, fragment.length - 1)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":326,"symbol":"urlString","kind":"function","lang":"kotlin","code":"override fun urlString(value: String): String = \"http://example.com/#a${value}z\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":328,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"override fun encodedValue(url: HttpUrl): String {\n val fragment = url.encodedFragment\n return fragment!!.substring(1, fragment.length - 1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":333,"symbol":"set","kind":"function","lang":"kotlin","code":"override operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n ) {\n builder.fragment(\"a${value}z\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":340,"symbol":"get","kind":"function","lang":"kotlin","code":"override operator fun get(url: HttpUrl): String {\n val fragment = url.fragment\n return fragment!!.substring(1, fragment.length - 1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":346,"symbol":"urlString","kind":"function","lang":"kotlin","code":"abstract fun urlString(value: String): String"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":348,"symbol":"encodedValue","kind":"function","lang":"kotlin","code":"abstract fun encodedValue(url: HttpUrl): String"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTester.kt","line":350,"symbol":"set","kind":"function","lang":"kotlin","code":"abstract operator fun set(\n builder: HttpUrl.Builder,\n value: String,\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTesterJvm.kt","line":23,"symbol":"urlComponentEncodingTesterJvmPlatform","kind":"function","lang":"kotlin","code":"fun urlComponentEncodingTesterJvmPlatform(component: Component): UrlComponentEncodingTester.Platform =\n when (component) {\n Component.USER -> {\n UrlComponentEncodingTesterJvmPlatform()\n .escapeForUri('%'.code)\n }\n\n Component.PASSWORD -> {\n UrlComponentEncodingTesterJvmPlatform()\n .escapeForUri('%'.code)\n }\n\n Component.HOST -> {\n UrlComponentEncodingTesterJvmPlatform()\n .stripForUri(\n '\\\"'.code,\n '<'.code,\n '>'.code,\n '^'.code,\n '`'.code,\n '{'.code,\n '|'.code,\n '}'.code,\n )\n }\n\n Component.PATH -> {\n UrlComponentEncodingTesterJvmPlatform()\n .escapeForUri(\n '%'.code,\n '['.code,\n ']'.code,\n )\n }\n\n Component.QUERY -> {\n UrlComponentEncodingTesterJvmPlatform()\n .escapeForUri(\n '%'.code,\n '\\\\'.code,\n '^'.code,\n '`'.code,\n '{'.code,\n '|'.code,\n '}'.code,\n )\n }\n\n Component.QUERY_VALUE -> {\n UrlComponentEncodingTesterJvmPlatform()\n .escapeForUri(\n '%'.code,\n '\\\\'.code,\n '^'.code,\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTesterJvm.kt","line":103,"symbol":"UrlComponentEncodingTesterJvmPlatform","kind":"class","lang":"kotlin","code":"private class UrlComponentEncodingTesterJvmPlatform : UrlComponentEncodingTester.Platform() {\n private val uriEscapedCodePoints = StringBuilder()\n private val uriStrippedCodePoints = StringBuilder()\n\n /**\n * Configure code points to be escaped for conversion to `java.net.URI`. That class is more\n * strict than the others.\n */\n fun escapeForUri(vararg codePoints: Int) =\n apply {\n uriEscapedCodePoints.append(String(*codePoints))\n }\n\n /**\n * Configure code points to be stripped in conversion to `java.net.URI`. That class is more\n * strict than the others.\n */\n fun stripForUri(vararg codePoints: Int) =\n apply {\n uriStrippedCodePoints.append(String(*codePoints))\n }\n\n override fun test(\n codePoint: Int,\n codePointString: String,\n encoding: UrlComponentEncodingTester.Encoding,\n component: Component,\n ) {\n testToUrl(codePoint, encoding, component)\n testFromUrl(codePoint, encoding, component)\n testUri(codePoint, codePointString, encoding, component)\n }\n\n private fun testToUrl(\n codePoint: Int,\n encoding: UrlComponentEncodingTester.Encoding,\n component: Component,\n ) {\n val encoded = encoding.encode(codePoint)\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTesterJvm.kt","line":111,"symbol":"escapeForUri","kind":"function","lang":"kotlin","doc":"Configure code points to be escaped for conversion to `java.net.URI`. That class is more strict than the others.","code":"fun escapeForUri(vararg codePoints: Int) =\n apply {\n uriEscapedCodePoints.append(String(*codePoints))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTesterJvm.kt","line":120,"symbol":"stripForUri","kind":"function","lang":"kotlin","doc":"Configure code points to be stripped in conversion to `java.net.URI`. That class is more strict than the others.","code":"fun stripForUri(vararg codePoints: Int) =\n apply {\n uriStrippedCodePoints.append(String(*codePoints))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTesterJvm.kt","line":125,"symbol":"test","kind":"function","lang":"kotlin","code":"override fun test(\n codePoint: Int,\n codePointString: String,\n encoding: UrlComponentEncodingTester.Encoding,\n component: Component,\n ) {\n testToUrl(codePoint, encoding, component)\n testFromUrl(codePoint, encoding, component)\n testUri(codePoint, codePointString, encoding, component)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTesterJvm.kt","line":136,"symbol":"testToUrl","kind":"function","lang":"kotlin","code":"private fun testToUrl(\n codePoint: Int,\n encoding: UrlComponentEncodingTester.Encoding,\n component: Component,\n ) {\n val encoded = encoding.encode(codePoint)\n val httpUrl = component.urlString(encoded).toHttpUrl()\n val javaNetUrl = httpUrl.toUrl()\n if (javaNetUrl.toString() != javaNetUrl.toString()) {\n fail(\"Encoding $component $codePoint using $encoding\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTesterJvm.kt","line":149,"symbol":"testFromUrl","kind":"function","lang":"kotlin","code":"private fun testFromUrl(\n codePoint: Int,\n encoding: UrlComponentEncodingTester.Encoding,\n component: Component,\n ) {\n val encoded = encoding.encode(codePoint)\n val httpUrl = component.urlString(encoded).toHttpUrl()\n val toAndFromJavaNetUrl = httpUrl.toUrl().toHttpUrlOrNull()\n if (toAndFromJavaNetUrl != httpUrl) {\n fail(\"Encoding $component $codePoint using $encoding\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/UrlComponentEncodingTesterJvm.kt","line":162,"symbol":"testUri","kind":"function","lang":"kotlin","code":"private fun testUri(\n codePoint: Int,\n codePointString: String,\n encoding: UrlComponentEncodingTester.Encoding,\n component: Component,\n ) {\n if (codePoint == '%'.code) return\n val encoded = encoding.encode(codePoint)\n val httpUrl = component.urlString(encoded).toHttpUrl()\n val uri = httpUrl.toUri()\n val toAndFromUri = uri.toHttpUrlOrNull()\n val uriStripped = uriStrippedCodePoints.indexOf(codePointString) != -1\n if (uriStripped) {\n if (uri.toString() != component.urlString(\"\")) {\n fail(\"Encoding $component $codePoint using $encoding\")\n }\n return\n }\n\n // If the URI has more escaping than the HttpURL, check that the decoded values still match.\n val uriEscaped = uriEscapedCodePoints.indexOf(codePointString) != -1\n if (uriEscaped) {\n if (uri.toString() == httpUrl.toString()) {\n fail(\"Encoding $component $codePoint using $encoding\")\n }\n if (component[toAndFromUri!!] != codePointString) {\n fail(\"Encoding $component $codePoint using $encoding\")\n }\n return\n }\n\n // Check that the URI and HttpURL have the exact same escaping.\n if (toAndFromUri != httpUrl) {\n fail(\"Encoding "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformToAsciiData.kt","line":27,"symbol":"WebPlatformToAsciiData","kind":"class","lang":"kotlin","doc":"A test from the [Web Platform To ASCII](https://github.com/web-platform-tests/wpt/blob/master/url/resources/toascii.json). Each test is a line of the file `toascii.json`.","code":"@Serializable\nclass WebPlatformToAsciiData {\n var input: String? = null\n var output: String? = null\n var comment: String? = null\n\n override fun toString() = \"input=$input output=$output\"\n\n companion object {\n fun load(): List {\n val path = okHttpRoot / \"okhttp/src/jvmTest/resources/web-platform-test-toascii.json\"\n return SYSTEM_FILE_SYSTEM.read(path) {\n Json.decodeFromString>(readUtf8())\n }\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformToAsciiData.kt","line":33,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"input=$input output=$output\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformToAsciiData.kt","line":36,"symbol":"load","kind":"function","lang":"kotlin","code":"fun load(): List {\n val path = okHttpRoot / \"okhttp/src/jvmTest/resources/web-platform-test-toascii.json\"\n return SYSTEM_FILE_SYSTEM.read(path) {\n Json.decodeFromString>(readUtf8())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformToAsciiTest.kt","line":24,"symbol":"WebPlatformToAsciiTest","kind":"class","lang":"kotlin","doc":"Runs the web platform ToAscii tests.","code":"class WebPlatformToAsciiTest {\n @Suppress(\"ktlint:standard:max-line-length\")\n val knownFailures =\n setOf(\n // OkHttp rejects empty labels.\n \"x..xn--zca\",\n \"x..ß\",\n // OkHttp rejects labels longer than 63 code points, the web platform tests don't.\n \"x01234567890123456789012345678901234567890123456789012345678901x.xn--zca\",\n \"x01234567890123456789012345678901234567890123456789012345678901x.ß\",\n \"x01234567890123456789012345678901234567890123456789012345678901x\",\n \"x01234567890123456789012345678901234567890123456789012345678901†\",\n // OkHttp rejects domain names longer than 253 code points, the web platform tests don't.\n \"01234567890123456789012345678901234567890123456789.01234567890123456789012345678901234567890123456789.01234567890123456789012345678901234567890123456789.01234567890123456789012345678901234567890123456789.0123456789012345678901234567890123456789012345678.x\",\n \"01234567890123456789012345678901234567890123456789.01234567890123456789012345678901234567890123456789.01234567890123456789012345678901234567890123456789.01234567890123456789012345678901234567890123456789.0123456789012345678901234567890123456789012345678."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformToAsciiTest.kt","line":55,"symbol":"test","kind":"function","lang":"kotlin","code":"@Test\n fun test() {\n val list = WebPlatformToAsciiData.load()\n val failures = mutableListOf()\n for (entry in list) {\n var failure: Throwable? = null\n try {\n testToAscii(entry.input!!, entry.output, entry.comment)\n } catch (e: Throwable) {\n failure = e\n }\n\n if (entry.input in knownFailures) {\n if (failure == null) failures += AssertionError(\"known failure didn't fail: $entry\")\n } else {\n if (failure != null) failures += failure\n }\n }\n\n if (failures.isNotEmpty()) {\n for (failure in failures) {\n println(failure)\n }\n throw failures.first()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformToAsciiTest.kt","line":82,"symbol":"testToAscii","kind":"function","lang":"kotlin","code":"private fun testToAscii(\n input: String,\n output: String?,\n comment: String?,\n ) {\n val url = \"https://$input/\".toHttpUrlOrNull()\n assertThat(url?.host, name = comment ?: input).isEqualTo(output)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTest.kt","line":31,"symbol":"WebPlatformUrlTest","kind":"class","lang":"kotlin","doc":"Runs the web platform URL tests against Java URL models.","code":"class WebPlatformUrlTest {\n class TestDataParamProvider : SimpleProvider() {\n override fun arguments() = ArrayList(loadTests())\n }\n\n /** Test how [HttpUrl] does against the web platform test suite. */\n @ArgumentsSource(TestDataParamProvider::class)\n @ParameterizedTest\n fun httpUrl(testData: WebPlatformUrlTestData) {\n if (!testData.scheme.isEmpty() && !HTTP_URL_SCHEMES.contains(testData.scheme)) {\n System.err.println(\"Ignoring unsupported scheme ${testData.scheme}\")\n return\n }\n\n if (!testData.base!!.startsWith(\"https:\") &&\n !testData.base!!.startsWith(\"http:\") &&\n testData.base != \"about:blank\"\n ) {\n System.err.println(\"Ignoring unsupported base ${testData.base}\")\n return\n }\n\n try {\n testHttpUrl(testData)\n if (KNOWN_FAILURES.contains(testData.toString())) {\n System.err.println(\"Expected failure but was success: $testData\")\n }\n } catch (e: Throwable) {\n if (KNOWN_FAILURES.contains(testData.toString())) {\n System.err.println(\"Ignoring known failure: $testData\")\n e.printStackTrace()\n } else {\n throw e\n }\n }\n }\n\n private fun testHttpUrl(testData: WebPlatformUr"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTest.kt","line":32,"symbol":"TestDataParamProvider","kind":"class","lang":"kotlin","code":"class TestDataParamProvider : SimpleProvider() {\n override fun arguments() = ArrayList(loadTests())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTest.kt","line":33,"symbol":"arguments","kind":"function","lang":"kotlin","code":"override fun arguments() = ArrayList(loadTests())"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTest.kt","line":37,"symbol":"httpUrl","kind":"function","lang":"kotlin","doc":"Test how [HttpUrl] does against the web platform test suite.","code":"@ArgumentsSource(TestDataParamProvider::class)\n @ParameterizedTest\n fun httpUrl(testData: WebPlatformUrlTestData) {\n if (!testData.scheme.isEmpty() && !HTTP_URL_SCHEMES.contains(testData.scheme)) {\n System.err.println(\"Ignoring unsupported scheme ${testData.scheme}\")\n return\n }\n\n if (!testData.base!!.startsWith(\"https:\") &&\n !testData.base!!.startsWith(\"http:\") &&\n testData.base != \"about:blank\"\n ) {\n System.err.println(\"Ignoring unsupported base ${testData.base}\")\n return\n }\n\n try {\n testHttpUrl(testData)\n if (KNOWN_FAILURES.contains(testData.toString())) {\n System.err.println(\"Expected failure but was success: $testData\")\n }\n } catch (e: Throwable) {\n if (KNOWN_FAILURES.contains(testData.toString())) {\n System.err.println(\"Ignoring known failure: $testData\")\n e.printStackTrace()\n } else {\n throw e\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTest.kt","line":68,"symbol":"testHttpUrl","kind":"function","lang":"kotlin","code":"private fun testHttpUrl(testData: WebPlatformUrlTestData) {\n val url =\n when (testData.base) {\n \"about:blank\" -> testData.input!!.toHttpUrlOrNull()\n else -> testData.base!!.toHttpUrl().resolve(testData.input!!)\n }\n\n if (testData.expectParseFailure()) {\n assertThat(url, \"Expected URL to fail parsing\").isNull()\n return\n }\n\n assertThat(url, \"Expected URL to parse successfully, but was null\")\n .isNotNull()\n val effectivePort =\n when {\n url!!.port != defaultPort(url.scheme) -> Integer.toString(url.port)\n else -> \"\"\n }\n val effectiveQuery =\n when {\n url.encodedQuery != null -> \"?\" + url.encodedQuery\n else -> \"\"\n }\n val effectiveFragment =\n when {\n url.encodedFragment != null -> \"#\" + url.encodedFragment\n else -> \"\"\n }\n val effectiveHost =\n when {\n url.host.contains(\":\") -> \"[\" + url.host + \"]\"\n else -> url.host\n }\n assertThat(url.scheme, \"scheme\").isEqualTo(testData.scheme)\n assertThat(effectiveHost, \"host\").isEqualTo(testData.host)\n assertThat(effectivePort, \"port\").isEqualTo(testData.port)\n assertThat(url.encodedPath,"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTest.kt","line":125,"symbol":"loadTests","kind":"function","lang":"kotlin","code":"private fun loadTests(): List {\n val resourceAsStream =\n WebPlatformUrlTest::class.java.getResourceAsStream(\n \"/web-platform-test-urltestdata.txt\",\n )\n val source = resourceAsStream.source().buffer()\n return WebPlatformUrlTestData.load(source)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTestData.kt","line":34,"symbol":"WebPlatformUrlTestData","kind":"class","lang":"kotlin","doc":"Each line of the `urltestdata.txt` file specifies a test. Lines look like this: ``` http://example\\t.\\norg http://example.org/foo/bar s:http h:example.org p:/ ```","code":"class WebPlatformUrlTestData {\n var input: String? = null\n var base: String? = null\n var scheme = \"\"\n var username = \"\"\n var password: String? = null\n var host = \"\"\n var port = \"\"\n var path = \"\"\n var query = \"\"\n var fragment = \"\"\n\n fun expectParseFailure() = scheme.isEmpty()\n\n private operator fun set(\n name: String,\n value: String,\n ) {\n when (name) {\n \"s\" -> scheme = value\n \"u\" -> username = value\n \"pass\" -> password = value\n \"h\" -> host = value\n \"port\" -> port = value\n \"p\" -> path = value\n \"q\" -> query = value\n \"f\" -> fragment = value\n else -> throw IllegalArgumentException(\"unexpected attribute: $value\")\n }\n }\n\n override fun toString(): String = format(\"Parsing: <%s> against <%s>\", input!!, base!!)\n\n companion object {\n fun load(source: BufferedSource): List {\n val list = mutableListOf()\n while (true) {\n val line = source.readUtf8Line() ?: break\n if (line.isEmpty() || line.startsWith(\"#\")) continue\n\n var i = 0\n val parts = line.split(Regex(\" \")).toTypedArray()\n\n val element = WebPlatformUrlTestData()\n ele"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTestData.kt","line":46,"symbol":"expectParseFailure","kind":"function","lang":"kotlin","code":"fun expectParseFailure() = scheme.isEmpty()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTestData.kt","line":48,"symbol":"set","kind":"function","lang":"kotlin","code":"private operator fun set(\n name: String,\n value: String,\n ) {\n when (name) {\n \"s\" -> scheme = value\n \"u\" -> username = value\n \"pass\" -> password = value\n \"h\" -> host = value\n \"port\" -> port = value\n \"p\" -> path = value\n \"q\" -> query = value\n \"f\" -> fragment = value\n else -> throw IllegalArgumentException(\"unexpected attribute: $value\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTestData.kt","line":65,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = format(\"Parsing: <%s> against <%s>\", input!!, base!!)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTestData.kt","line":68,"symbol":"load","kind":"function","lang":"kotlin","code":"fun load(source: BufferedSource): List {\n val list = mutableListOf()\n while (true) {\n val line = source.readUtf8Line() ?: break\n if (line.isEmpty() || line.startsWith(\"#\")) continue\n\n var i = 0\n val parts = line.split(Regex(\" \")).toTypedArray()\n\n val element = WebPlatformUrlTestData()\n element.input = unescape(parts[i++])\n\n val base = if (i < parts.size) parts[i++] else null\n element.base =\n when {\n base == null || base.isEmpty() -> list[list.size - 1].base\n else -> unescape(base)\n }\n\n while (i < parts.size) {\n val piece = parts[i]\n if (piece.startsWith(\"#\")) {\n i++\n continue\n }\n val nameAndValue = piece.split(Regex(\":\"), 2).toTypedArray()\n element[nameAndValue[0]] = unescape(nameAndValue[1])\n i++\n }\n\n list += element\n }\n return list\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WebPlatformUrlTestData.kt","line":103,"symbol":"unescape","kind":"function","lang":"kotlin","code":"private fun unescape(s: String): String =\n buildString {\n val buffer = Buffer().writeUtf8(s)\n while (!buffer.exhausted()) {\n val c = buffer.readUtf8CodePoint()\n if (c != '\\\\'.code) {\n append(c.toChar())\n continue\n }\n when (buffer.readUtf8CodePoint()) {\n '\\\\'.code -> append('\\\\')\n '#'.code -> append('#')\n 'n'.code -> append('\\n')\n 'r'.code -> append('\\r')\n 's'.code -> append(' ')\n 't'.code -> append('\\t')\n 'f'.code -> append('\\u000c')\n 'u'.code -> append(buffer.readUtf8(4).toInt(16).toChar())\n else -> throw IllegalArgumentException(\"unexpected escape character in $s\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":43,"symbol":"WholeOperationTimeoutTest","kind":"class","lang":"kotlin","code":"@Timeout(30)\n@Tag(\"Slow\")\nclass WholeOperationTimeoutTest {\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n private val client = clientTestRule.newClient()\n\n @StartStop\n private val server = MockWebServer()\n\n @Test\n fun defaultConfigIsNoTimeout() {\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val call = client.newCall(request)\n assertThat(call.timeout().timeoutNanos()).isEqualTo(0)\n }\n\n @Test\n fun configureClientDefault() {\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val timeoutClient =\n client\n .newBuilder()\n .callTimeout(Duration.ofMillis(456))\n .build()\n val call = timeoutClient.newCall(request)\n assertThat(call.timeout().timeoutNanos())\n .isEqualTo(TimeUnit.MILLISECONDS.toNanos(456))\n }\n\n @Test\n fun timeoutWritingRequest() {\n server.enqueue(MockResponse())\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(sleepingRequestBody(500))\n .build()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n asse"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":53,"symbol":"defaultConfigIsNoTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun defaultConfigIsNoTimeout() {\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val call = client.newCall(request)\n assertThat(call.timeout().timeoutNanos()).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":64,"symbol":"configureClientDefault","kind":"function","lang":"kotlin","code":"@Test\n fun configureClientDefault() {\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val timeoutClient =\n client\n .newBuilder()\n .callTimeout(Duration.ofMillis(456))\n .build()\n val call = timeoutClient.newCall(request)\n assertThat(call.timeout().timeoutNanos())\n .isEqualTo(TimeUnit.MILLISECONDS.toNanos(456))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":81,"symbol":"timeoutWritingRequest","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutWritingRequest() {\n server.enqueue(MockResponse())\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(sleepingRequestBody(500))\n .build()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n assertThat(call.isCanceled()).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":100,"symbol":"timeoutWritingRequestWithEnqueue","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutWritingRequestWithEnqueue() {\n server.enqueue(MockResponse())\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(sleepingRequestBody(500))\n .build()\n val latch = CountDownLatch(1)\n val exceptionRef = AtomicReference()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n call.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n exceptionRef.set(e)\n latch.countDown()\n }\n\n @Throws(IOException::class)\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n latch.countDown()\n }\n },\n )\n latch.await()\n assertThat(call.isCanceled()).isTrue()\n assertThat(exceptionRef.get()).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":115,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n exceptionRef.set(e)\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":123,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":138,"symbol":"timeoutProcessing","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutProcessing() {\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(500, TimeUnit.MILLISECONDS)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n assertThat(call.isCanceled()).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":161,"symbol":"timeoutProcessingWithEnqueue","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutProcessingWithEnqueue() {\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(500, TimeUnit.MILLISECONDS)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val latch = CountDownLatch(1)\n val exceptionRef = AtomicReference()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n call.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n exceptionRef.set(e)\n latch.countDown()\n }\n\n @Throws(IOException::class)\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n latch.countDown()\n }\n },\n )\n latch.await()\n assertThat(call.isCanceled()).isTrue()\n assertThat(exceptionRef.get()).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":180,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n exceptionRef.set(e)\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":188,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.close()\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":203,"symbol":"timeoutReadingResponse","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutReadingResponse() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(BIG_ENOUGH_BODY)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n val response = call.execute()\n Thread.sleep(500)\n assertFailsWith {\n response.body.source().readUtf8()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n assertThat(call.isCanceled()).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":228,"symbol":"timeoutReadingResponseWithEnqueue","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutReadingResponseWithEnqueue() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(BIG_ENOUGH_BODY)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build()\n val latch = CountDownLatch(1)\n val exceptionRef = AtomicReference()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n call.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n latch.countDown()\n }\n\n @Throws(IOException::class)\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n try {\n Thread.sleep(500)\n } catch (e: InterruptedException) {\n throw AssertionError()\n }\n assertFailsWith {\n response.body.source().readUtf8()\n }.also { expected ->\n exceptionRef.set(expected)\n latch.countDown()\n }\n }\n },\n )\n latch.await()\n assertThat(call.isCanceled()).isTrue()\n assertThat(exceptionRef"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":247,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":254,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n try {\n Thread.sleep(500)\n } catch (e: InterruptedException) {\n throw AssertionError()\n }\n assertFailsWith {\n response.body.source().readUtf8()\n }.also { expected ->\n exceptionRef.set(expected)\n latch.countDown()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":278,"symbol":"singleTimeoutForAllFollowUpRequests","kind":"function","lang":"kotlin","code":"@Test\n fun singleTimeoutForAllFollowUpRequests() {\n server.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_MOVED_TEMP)\n .setHeader(\"Location\", \"/b\")\n .headersDelay(100, TimeUnit.MILLISECONDS)\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_MOVED_TEMP)\n .setHeader(\"Location\", \"/c\")\n .headersDelay(100, TimeUnit.MILLISECONDS)\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_MOVED_TEMP)\n .setHeader(\"Location\", \"/d\")\n .headersDelay(100, TimeUnit.MILLISECONDS)\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_MOVED_TEMP)\n .setHeader(\"Location\", \"/e\")\n .headersDelay(100, TimeUnit.MILLISECONDS)\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_MOVED_TEMP)\n .setHeader(\"Location\", \"/f\")\n .headersDelay(100, TimeUnit.MILLISECONDS)\n .build(),\n )\n server.enqueue(MockResponse())\n val request =\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":336,"symbol":"timeoutFollowingRedirectOnNewConnection","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutFollowingRedirectOnNewConnection() {\n val otherServer = MockWebServer()\n otherServer.start()\n server.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_MOVED_TEMP)\n .setHeader(\"Location\", otherServer.url(\"/\"))\n .build(),\n )\n otherServer.enqueue(\n MockResponse\n .Builder()\n .headersDelay(500, TimeUnit.MILLISECONDS)\n .build(),\n )\n val request = Request.Builder().url(server.url(\"/\")).build()\n val call = client.newCall(request)\n call.timeout().timeout(250, TimeUnit.MILLISECONDS)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n assertThat(call.isCanceled()).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":364,"symbol":"noTimeout","kind":"function","lang":"kotlin","code":"@Flaky\n @Test\n fun noTimeout() {\n // Flaky https://github.com/lysine-dev/okhttp/issues/5304\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(250, TimeUnit.MILLISECONDS)\n .body(BIG_ENOUGH_BODY)\n .build(),\n )\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(sleepingRequestBody(250))\n .build()\n val call = client.newCall(request)\n call.timeout().timeout(2000, TimeUnit.MILLISECONDS)\n val response = call.execute()\n Thread.sleep(250)\n response.body.source().readUtf8()\n response.close()\n assertThat(call.isCanceled()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":390,"symbol":"sleepingRequestBody","kind":"function","lang":"kotlin","code":"private fun sleepingRequestBody(sleepMillis: Int): RequestBody =\n object : RequestBody() {\n override fun contentType(): MediaType? = \"text/plain\".toMediaTypeOrNull()\n\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n try {\n sink.writeUtf8(\"abc\")\n sink.flush()\n Thread.sleep(sleepMillis.toLong())\n sink.writeUtf8(\"def\")\n } catch (e: InterruptedException) {\n throw InterruptedIOException()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":392,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = \"text/plain\".toMediaTypeOrNull()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WholeOperationTimeoutTest.kt","line":394,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n try {\n sink.writeUtf8(\"abc\")\n sink.flush()\n Thread.sleep(sleepMillis.toLong())\n sink.writeUtf8(\"def\")\n } catch (e: InterruptedException) {\n throw InterruptedIOException()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WriteTimeoutDuringWriteToTest.kt","line":35,"symbol":"WriteTimeoutDuringWriteToTest","kind":"class","lang":"kotlin","code":"class WriteTimeoutDuringWriteToTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @Tag(\"Slowish\")\n @Test\n fun delayedSocketWritesHonorWriteTimeout() {\n server.enqueue(MockResponse())\n\n val writeTimeoutMillis = 200L\n val client =\n clientTestRule\n .newClientBuilder()\n .writeTimeout(writeTimeoutMillis, TimeUnit.MILLISECONDS)\n .socketFactory(\n object : DelegatingSocketFactory(SocketFactory.getDefault()) {\n override fun createSocket(): Socket =\n object : Socket() {\n override fun getOutputStream(): OutputStream =\n object : FilterOutputStream(super.getOutputStream()) {\n override fun write(\n b: ByteArray,\n off: Int,\n len: Int,\n ) {\n Thread.sleep(writeTimeoutMillis + 150)\n super.write(b, off, len)\n }\n }\n }\n },\n ).build()\n\n val request =\n Request(\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WriteTimeoutDuringWriteToTest.kt","line":45,"symbol":"delayedSocketWritesHonorWriteTimeout","kind":"function","lang":"kotlin","code":"@Tag(\"Slowish\")\n @Test\n fun delayedSocketWritesHonorWriteTimeout() {\n server.enqueue(MockResponse())\n\n val writeTimeoutMillis = 200L\n val client =\n clientTestRule\n .newClientBuilder()\n .writeTimeout(writeTimeoutMillis, TimeUnit.MILLISECONDS)\n .socketFactory(\n object : DelegatingSocketFactory(SocketFactory.getDefault()) {\n override fun createSocket(): Socket =\n object : Socket() {\n override fun getOutputStream(): OutputStream =\n object : FilterOutputStream(super.getOutputStream()) {\n override fun write(\n b: ByteArray,\n off: Int,\n len: Int,\n ) {\n Thread.sleep(writeTimeoutMillis + 150)\n super.write(b, off, len)\n }\n }\n }\n },\n ).build()\n\n val request =\n Request(\n url = server.url(\"/\"),\n body = \"test\".toRequestBody(),\n )\n\n assertFailsWith {\n client.newCall(request).execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WriteTimeoutDuringWriteToTest.kt","line":57,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(): Socket =\n object : Socket() {\n override fun getOutputStream(): OutputStream =\n object : FilterOutputStream(super.getOutputStream()) {\n override fun write(\n b: ByteArray,\n off: Int,\n len: Int,\n ) {\n Thread.sleep(writeTimeoutMillis + 150)\n super.write(b, off, len)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WriteTimeoutDuringWriteToTest.kt","line":59,"symbol":"getOutputStream","kind":"function","lang":"kotlin","code":"override fun getOutputStream(): OutputStream =\n object : FilterOutputStream(super.getOutputStream()) {\n override fun write(\n b: ByteArray,\n off: Int,\n len: Int,\n ) {\n Thread.sleep(writeTimeoutMillis + 150)\n super.write(b, off, len)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/WriteTimeoutDuringWriteToTest.kt","line":61,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n b: ByteArray,\n off: Int,\n len: Int,\n ) {\n Thread.sleep(writeTimeoutMillis + 150)\n super.write(b, off, len)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/DoubleInetAddressDns.kt","line":25,"symbol":"DoubleInetAddressDns","kind":"class","lang":"kotlin","doc":"A network that always resolves two IP addresses per host. Use this when testing route selection fallbacks to guarantee that a fallback address is available.","code":"class DoubleInetAddressDns : Dns {\n override fun lookup(hostname: String): List {\n val addresses = Dns.SYSTEM.lookup(hostname)\n return listOf(addresses[0], addresses[0])\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/DoubleInetAddressDns.kt","line":26,"symbol":"lookup","kind":"function","lang":"kotlin","code":"override fun lookup(hostname: String): List {\n val addresses = Dns.SYSTEM.lookup(hostname)\n return listOf(addresses[0], addresses[0])\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/HostnamesTest.kt","line":22,"symbol":"HostnamesTest","kind":"class","lang":"kotlin","code":"class HostnamesTest {\n @Test\n fun canonicalizeInetAddressNotMapped() {\n val addressA = decodeIpv6(\"::1\")!!\n assertThat(canonicalizeInetAddress(addressA)).isEqualTo(addressA)\n\n val addressB = byteArrayOf(127, 0, 0, 1)\n assertThat(canonicalizeInetAddress(addressB)).isEqualTo(addressB)\n\n val addressC = byteArrayOf(192.toByte(), 168.toByte(), 0, 1)\n assertThat(canonicalizeInetAddress(addressC)).isEqualTo(addressC)\n\n val addressD = decodeIpv6(\"abcd:ef01:2345:6789:abcd:ef01:2345:6789\")!!\n assertThat(canonicalizeInetAddress(addressD)).isEqualTo(addressD)\n\n val addressE = decodeIpv6(\"2001:db8::1:0:0:1\")!!\n assertThat(canonicalizeInetAddress(addressE)).isEqualTo(addressE)\n\n val addressF = decodeIpv6(\"0:0:0:0:0:ffff:7f00:1\")!!\n assertThat(canonicalizeInetAddress(addressF)).isEqualTo(addressB)\n\n val addressG = decodeIpv6(\"0:0:0:0:0:ffff:c0a8:1\")!!\n assertThat(canonicalizeInetAddress(addressG)).isEqualTo(addressC)\n }\n\n @Test\n fun canonicalizeInetAddressMapped() {\n val addressAIpv6 = decodeIpv6(\"0:0:0:0:0:ffff:7f00:1\")!!\n val addressAIpv4 = byteArrayOf(127, 0, 0, 1)\n assertThat(canonicalizeInetAddress(addressAIpv6)).isEqualTo(addressAIpv4)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/HostnamesTest.kt","line":23,"symbol":"canonicalizeInetAddressNotMapped","kind":"function","lang":"kotlin","code":"@Test\n fun canonicalizeInetAddressNotMapped() {\n val addressA = decodeIpv6(\"::1\")!!\n assertThat(canonicalizeInetAddress(addressA)).isEqualTo(addressA)\n\n val addressB = byteArrayOf(127, 0, 0, 1)\n assertThat(canonicalizeInetAddress(addressB)).isEqualTo(addressB)\n\n val addressC = byteArrayOf(192.toByte(), 168.toByte(), 0, 1)\n assertThat(canonicalizeInetAddress(addressC)).isEqualTo(addressC)\n\n val addressD = decodeIpv6(\"abcd:ef01:2345:6789:abcd:ef01:2345:6789\")!!\n assertThat(canonicalizeInetAddress(addressD)).isEqualTo(addressD)\n\n val addressE = decodeIpv6(\"2001:db8::1:0:0:1\")!!\n assertThat(canonicalizeInetAddress(addressE)).isEqualTo(addressE)\n\n val addressF = decodeIpv6(\"0:0:0:0:0:ffff:7f00:1\")!!\n assertThat(canonicalizeInetAddress(addressF)).isEqualTo(addressB)\n\n val addressG = decodeIpv6(\"0:0:0:0:0:ffff:c0a8:1\")!!\n assertThat(canonicalizeInetAddress(addressG)).isEqualTo(addressC)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/HostnamesTest.kt","line":47,"symbol":"canonicalizeInetAddressMapped","kind":"function","lang":"kotlin","code":"@Test\n fun canonicalizeInetAddressMapped() {\n val addressAIpv6 = decodeIpv6(\"0:0:0:0:0:ffff:7f00:1\")!!\n val addressAIpv4 = byteArrayOf(127, 0, 0, 1)\n assertThat(canonicalizeInetAddress(addressAIpv6)).isEqualTo(addressAIpv4)\n\n val addressBIpv6 = decodeIpv6(\"0:0:0:0:0:ffff:c0a8:1\")!!\n val addressBIpv4 = byteArrayOf(192.toByte(), 168.toByte(), 0, 1)\n assertThat(canonicalizeInetAddress(addressBIpv6)).isEqualTo(addressBIpv4)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/HostnamesTest.kt","line":58,"symbol":"canonicalizeInetAddressIPv6RepresentationOfCompatibleIPV4","kind":"function","lang":"kotlin","code":"@Test\n fun canonicalizeInetAddressIPv6RepresentationOfCompatibleIPV4() {\n val addressAIpv6 = decodeIpv6(\"::192.168.0.1\")!!\n assertThat(canonicalizeInetAddress(addressAIpv6)).isEqualTo(\n ByteArray(12) +\n byteArrayOf(\n 192.toByte(),\n 168.toByte(),\n 0,\n 1,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/HostnamesTest.kt","line":72,"symbol":"canonicalizeInetAddressIPv6RepresentationOfMappedIPV4","kind":"function","lang":"kotlin","code":"@Test\n fun canonicalizeInetAddressIPv6RepresentationOfMappedIPV4() {\n val addressAIpv6 = decodeIpv6(\"::FFFF:192.168.0.1\")!!\n assertThat(canonicalizeInetAddress(addressAIpv6)).isEqualTo(byteArrayOf(192.toByte(), 168.toByte(), 0, 1))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/HostnamesTest.kt","line":78,"symbol":"inet4AddressToAscii","kind":"function","lang":"kotlin","code":"@Test\n fun inet4AddressToAscii() {\n assertThat(\n inet4AddressToAscii(\n byteArrayOf(0, 0, 0, 0),\n ),\n ).isEqualTo(\"0.0.0.0\")\n\n assertThat(\n inet4AddressToAscii(\n byteArrayOf(1, 2, 3, 4),\n ),\n ).isEqualTo(\"1.2.3.4\")\n\n assertThat(\n inet4AddressToAscii(\n byteArrayOf(127, 0, 0, 1),\n ),\n ).isEqualTo(\"127.0.0.1\")\n\n assertThat(\n inet4AddressToAscii(\n byteArrayOf(192.toByte(), 168.toByte(), 0, 1),\n ),\n ).isEqualTo(\"192.168.0.1\")\n\n assertThat(\n inet4AddressToAscii(\n byteArrayOf(252.toByte(), 253.toByte(), 254.toByte(), 255.toByte()),\n ),\n ).isEqualTo(\"252.253.254.255\")\n\n assertThat(\n inet4AddressToAscii(\n byteArrayOf(255.toByte(), 255.toByte(), 255.toByte(), 255.toByte()),\n ),\n ).isEqualTo(\"255.255.255.255\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/HostnamesTest.kt","line":117,"symbol":"decodeIpv6","kind":"function","lang":"kotlin","code":"private fun decodeIpv6(input: String): ByteArray? = decodeIpv6(input, 0, input.length)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/HostnamesTest.kt","line":119,"symbol":"testToCanonicalHost","kind":"function","lang":"kotlin","code":"@Test\n fun testToCanonicalHost() {\n // IPv4\n assertThat(\"127.0.0.1\".toCanonicalHost()).isEqualTo(\"127.0.0.1\")\n assertThat(\"1.2.3.4\".toCanonicalHost()).isEqualTo(\"1.2.3.4\")\n\n // IPv6\n assertThat(\"::1\".toCanonicalHost()).isEqualTo(\"::1\")\n assertThat(\"2001:db8::1\".toCanonicalHost()).isEqualTo(\"2001:db8::1\")\n assertThat(\"::ffff:192.168.0.1\".toCanonicalHost()).isEqualTo(\"192.168.0.1\")\n assertThat(\n \"FEDC:BA98:7654:3210:FEDC:BA98:7654:3210\".toCanonicalHost(),\n ).isEqualTo(\n \"fedc:ba98:7654:3210:fedc:ba98:7654:3210\",\n )\n\n assertThat(\n \"1080:0:0:0:8:800:200C:417A\".toCanonicalHost(),\n ).isEqualTo(\"1080::8:800:200c:417a\")\n\n assertThat(\"1080::8:800:200C:417A\".toCanonicalHost()).isEqualTo(\"1080::8:800:200c:417a\")\n assertThat(\"FF01::101\".toCanonicalHost()).isEqualTo(\"ff01::101\")\n assertThat(\n \"0:0:0:0:0:FFFF:129.144.52.38\".toCanonicalHost(),\n ).isEqualTo(\"129.144.52.38\")\n\n assertThat(\"::FFFF:129.144.52.38\".toCanonicalHost()).isEqualTo(\"129.144.52.38\")\n\n // Hostnames\n assertThat(\"WwW.GoOgLe.cOm\".toCanonicalHost()).isEqualTo(\"www.google.com\")\n assertThat(\"localhost\".toCanonicalHost()).isEqualTo(\"localhost\")\n asser"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/RecordingAuthenticator.kt","line":21,"symbol":"RecordingAuthenticator","kind":"class","lang":"kotlin","code":"class RecordingAuthenticator(\n private val authentication: PasswordAuthentication? =\n PasswordAuthentication(\n \"username\",\n \"password\".toCharArray(),\n ),\n) : Authenticator() {\n val calls = mutableListOf()\n\n override fun getPasswordAuthentication(): PasswordAuthentication? {\n calls.add(\n \"host=$requestingHost port=$requestingPort site=${requestingSite.hostName} \" +\n \"url=$requestingURL type=$requestorType prompt=$requestingPrompt \" +\n \"protocol=$requestingProtocol scheme=$requestingScheme\",\n )\n return authentication\n }\n\n companion object {\n /** base64(\"username:password\") */\n const val BASE_64_CREDENTIALS = \"dXNlcm5hbWU6cGFzc3dvcmQ=\"\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/RecordingAuthenticator.kt","line":30,"symbol":"getPasswordAuthentication","kind":"function","lang":"kotlin","code":"override fun getPasswordAuthentication(): PasswordAuthentication? {\n calls.add(\n \"host=$requestingHost port=$requestingPort site=${requestingSite.hostName} \" +\n \"url=$requestingURL type=$requestorType prompt=$requestingPrompt \" +\n \"protocol=$requestingProtocol scheme=$requestingScheme\",\n )\n return authentication\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":24,"symbol":"TagsTest","kind":"class","lang":"kotlin","code":"class TagsTest {\n @Test\n fun emptyTags() {\n val tags = EmptyTags\n assertThat(tags[String::class]).isNull()\n }\n\n @Test\n fun singleElement() {\n val tags = EmptyTags.plus(String::class, \"hello\")\n assertThat(tags[String::class]).isEqualTo(\"hello\")\n }\n\n @Test\n fun multipleElements() {\n val tags =\n EmptyTags\n .plus(String::class, \"hello\")\n .plus(Integer::class, 5 as Integer)\n assertThat(tags[String::class]).isEqualTo(\"hello\")\n assertThat(tags[Integer::class]).isEqualTo(5)\n }\n\n /** The implementation retains no nodes from the original linked list. */\n @Test\n fun replaceFirstElement() {\n val tags =\n EmptyTags\n .plus(String::class, \"a\")\n .plus(Integer::class, 5 as Integer)\n .plus(Boolean::class, true)\n .plus(String::class, \"b\")\n assertThat(tags[String::class]).isEqualTo(\"b\")\n assertThat(tags.toString())\n .isEqualTo(\"{class kotlin.Int=5, class kotlin.Boolean=true, class kotlin.String=b}\")\n }\n\n /** The implementation retains only the first node from the original linked list. */\n @Test\n fun replaceMiddleElement() {\n val tags =\n EmptyTags\n .plus(Integer::class, 5 as Integer)\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":25,"symbol":"emptyTags","kind":"function","lang":"kotlin","code":"@Test\n fun emptyTags() {\n val tags = EmptyTags\n assertThat(tags[String::class]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":31,"symbol":"singleElement","kind":"function","lang":"kotlin","code":"@Test\n fun singleElement() {\n val tags = EmptyTags.plus(String::class, \"hello\")\n assertThat(tags[String::class]).isEqualTo(\"hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":37,"symbol":"multipleElements","kind":"function","lang":"kotlin","code":"@Test\n fun multipleElements() {\n val tags =\n EmptyTags\n .plus(String::class, \"hello\")\n .plus(Integer::class, 5 as Integer)\n assertThat(tags[String::class]).isEqualTo(\"hello\")\n assertThat(tags[Integer::class]).isEqualTo(5)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":48,"symbol":"replaceFirstElement","kind":"function","lang":"kotlin","doc":"The implementation retains no nodes from the original linked list.","code":"@Test\n fun replaceFirstElement() {\n val tags =\n EmptyTags\n .plus(String::class, \"a\")\n .plus(Integer::class, 5 as Integer)\n .plus(Boolean::class, true)\n .plus(String::class, \"b\")\n assertThat(tags[String::class]).isEqualTo(\"b\")\n assertThat(tags.toString())\n .isEqualTo(\"{class kotlin.Int=5, class kotlin.Boolean=true, class kotlin.String=b}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":62,"symbol":"replaceMiddleElement","kind":"function","lang":"kotlin","doc":"The implementation retains only the first node from the original linked list.","code":"@Test\n fun replaceMiddleElement() {\n val tags =\n EmptyTags\n .plus(Integer::class, 5 as Integer)\n .plus(String::class, \"a\")\n .plus(Boolean::class, true)\n .plus(String::class, \"b\")\n assertThat(tags[String::class]).isEqualTo(\"b\")\n assertThat(tags.toString())\n .isEqualTo(\"{class kotlin.Int=5, class kotlin.Boolean=true, class kotlin.String=b}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":76,"symbol":"replaceLastElement","kind":"function","lang":"kotlin","doc":"The implementation retains all but the first node from the original linked list.","code":"@Test\n fun replaceLastElement() {\n val tags =\n EmptyTags\n .plus(Integer::class, 5 as Integer)\n .plus(Boolean::class, true)\n .plus(String::class, \"a\")\n .plus(String::class, \"b\")\n assertThat(tags[String::class]).isEqualTo(\"b\")\n assertThat(tags.toString())\n .isEqualTo(\"{class kotlin.Int=5, class kotlin.Boolean=true, class kotlin.String=b}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":90,"symbol":"removeFirstElement","kind":"function","lang":"kotlin","doc":"The implementation retains no nodes from the original linked list.","code":"@Test\n fun removeFirstElement() {\n val tags =\n EmptyTags\n .plus(String::class, \"a\")\n .plus(Integer::class, 5 as Integer)\n .plus(Boolean::class, true)\n .plus(String::class, null)\n assertThat(tags[String::class]).isNull()\n assertThat(tags.toString())\n .isEqualTo(\"{class kotlin.Int=5, class kotlin.Boolean=true}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":104,"symbol":"removeMiddleElement","kind":"function","lang":"kotlin","doc":"The implementation retains only the first node from the original linked list.","code":"@Test\n fun removeMiddleElement() {\n val tags =\n EmptyTags\n .plus(Integer::class, 5 as Integer)\n .plus(String::class, \"a\")\n .plus(Boolean::class, true)\n .plus(String::class, null)\n assertThat(tags[String::class]).isNull()\n assertThat(tags.toString())\n .isEqualTo(\"{class kotlin.Int=5, class kotlin.Boolean=true}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":118,"symbol":"removeLastElement","kind":"function","lang":"kotlin","doc":"The implementation retains all but the first node from the original linked list.","code":"@Test\n fun removeLastElement() {\n val tags =\n EmptyTags\n .plus(Integer::class, 5 as Integer)\n .plus(Boolean::class, true)\n .plus(String::class, \"a\")\n .plus(String::class, null)\n assertThat(tags[String::class]).isNull()\n assertThat(tags.toString())\n .isEqualTo(\"{class kotlin.Int=5, class kotlin.Boolean=true}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":131,"symbol":"removeUntilEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun removeUntilEmpty() {\n val tags =\n EmptyTags\n .plus(Integer::class, 5 as Integer)\n .plus(Boolean::class, true)\n .plus(String::class, \"a\")\n .plus(String::class, null)\n .plus(Integer::class, null)\n .plus(Boolean::class, null)\n assertThat(tags).isEqualTo(EmptyTags)\n assertThat(tags.toString()).isEqualTo(\"{}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":145,"symbol":"removeAbsentFromEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun removeAbsentFromEmpty() {\n val tags = EmptyTags.plus(String::class, null)\n assertThat(tags).isEqualTo(EmptyTags)\n assertThat(tags.toString()).isEqualTo(\"{}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":152,"symbol":"removeAbsentFromNonEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun removeAbsentFromNonEmpty() {\n val tags =\n EmptyTags\n .plus(String::class, \"a\")\n .plus(Integer::class, null)\n assertThat(tags[String::class]).isEqualTo(\"a\")\n assertThat(tags.toString()).isEqualTo(\"{class kotlin.String=a}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":162,"symbol":"computeIfAbsentWhenEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun computeIfAbsentWhenEmpty() {\n val tags = EmptyTags\n val atomicTags = AtomicReference(tags)\n assertThat(atomicTags.computeIfAbsent(String::class) { \"a\" }).isEqualTo(\"a\")\n assertThat(atomicTags.get()[String::class]).isEqualTo(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":170,"symbol":"computeIfAbsentWhenPresent","kind":"function","lang":"kotlin","code":"@Test\n fun computeIfAbsentWhenPresent() {\n val tags = EmptyTags.plus(String::class, \"a\")\n val atomicTags = AtomicReference(tags)\n assertThat(atomicTags.computeIfAbsent(String::class) { \"b\" }).isEqualTo(\"a\")\n assertThat(atomicTags.get()[String::class]).isEqualTo(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":178,"symbol":"computeIfAbsentWhenDifferentKeyRaceLostDuringCompute","kind":"function","lang":"kotlin","code":"@Test\n fun computeIfAbsentWhenDifferentKeyRaceLostDuringCompute() {\n val tags = EmptyTags\n val atomicTags = AtomicReference(tags)\n val result =\n atomicTags.computeIfAbsent(String::class) {\n // 'Race' by making another computeIfAbsent call. In practice this would be another thread.\n assertThat(atomicTags.computeIfAbsent(Integer::class) { 5 as Integer }).isEqualTo(5)\n \"a\"\n }\n assertThat(result).isEqualTo(\"a\")\n assertThat(atomicTags.get()[String::class]).isEqualTo(\"a\")\n assertThat(atomicTags.get()[Integer::class]).isEqualTo(5)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":193,"symbol":"computeIfAbsentWhenSameKeyRaceLostDuringCompute","kind":"function","lang":"kotlin","code":"@Test\n fun computeIfAbsentWhenSameKeyRaceLostDuringCompute() {\n val tags = EmptyTags\n val atomicTags = AtomicReference(tags)\n val result =\n atomicTags.computeIfAbsent(String::class) {\n // 'Race' by making another computeIfAbsent call. In practice this would be another thread.\n assertThat(atomicTags.computeIfAbsent(String::class) { \"b\" }).isEqualTo(\"b\")\n \"a\"\n }\n assertThat(result).isEqualTo(\"b\")\n assertThat(atomicTags.get()[String::class]).isEqualTo(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TagsTest.kt","line":207,"symbol":"computeIfAbsentOnlyComputesOnceAfterRaceLost","kind":"function","lang":"kotlin","code":"@Test\n fun computeIfAbsentOnlyComputesOnceAfterRaceLost() {\n var computeCount = 0\n val tags = EmptyTags\n val atomicTags = AtomicReference(tags)\n val result =\n atomicTags.computeIfAbsent(String::class) {\n computeCount++\n // 'Race' by making another computeIfAbsent call. In practice this would be another thread.\n assertThat(atomicTags.computeIfAbsent(Integer::class) { 5 as Integer }).isEqualTo(5)\n \"a\"\n }\n assertThat(result).isEqualTo(\"a\")\n assertThat(computeCount).isEqualTo(1)\n assertThat(atomicTags.get()[Integer::class]).isEqualTo(5)\n assertThat(atomicTags.get()[String::class]).isEqualTo(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TestAndSetTest.kt","line":23,"symbol":"TestAndSetTest","kind":"class","lang":"kotlin","code":"class TestAndSetTest {\n @Test\n fun `happy path`() {\n val value = AtomicReference(\"a\")\n val previous = value.testAndSet(\"b\") { true }\n assertThat(previous).isEqualTo(\"a\")\n assertThat(value.get()).isEqualTo(\"b\")\n }\n\n @Test\n fun `condition does not match`() {\n val value = AtomicReference(\"a\")\n val previous = value.testAndSet(\"b\") { false }\n assertThat(previous).isEqualTo(\"a\")\n assertThat(value.get()).isEqualTo(\"a\")\n }\n\n @Test\n fun `value is updated to a matching value between test and set`() {\n val value = AtomicReference(\"a\")\n val previous =\n value.testAndSet(\"b\") {\n value.set(\"c\")\n true\n }\n assertThat(previous).isEqualTo(\"c\")\n assertThat(value.get()).isEqualTo(\"b\")\n }\n\n @Test\n fun `value is updated to a non-matching value between test and set`() {\n val value = AtomicReference(\"a\")\n val previous =\n value.testAndSet(\"b\") {\n value.set(\"c\")\n it == \"a\"\n }\n assertThat(previous).isEqualTo(\"c\")\n assertThat(value.get()).isEqualTo(\"c\")\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TestAndSetTest.kt","line":24,"symbol":"`happy path`","kind":"function","lang":"kotlin","code":"@Test\n fun `happy path`() {\n val value = AtomicReference(\"a\")\n val previous = value.testAndSet(\"b\") { true }\n assertThat(previous).isEqualTo(\"a\")\n assertThat(value.get()).isEqualTo(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TestAndSetTest.kt","line":32,"symbol":"`condition does not match`","kind":"function","lang":"kotlin","code":"@Test\n fun `condition does not match`() {\n val value = AtomicReference(\"a\")\n val previous = value.testAndSet(\"b\") { false }\n assertThat(previous).isEqualTo(\"a\")\n assertThat(value.get()).isEqualTo(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TestAndSetTest.kt","line":40,"symbol":"`value is updated to a matching value between test and set`","kind":"function","lang":"kotlin","code":"@Test\n fun `value is updated to a matching value between test and set`() {\n val value = AtomicReference(\"a\")\n val previous =\n value.testAndSet(\"b\") {\n value.set(\"c\")\n true\n }\n assertThat(previous).isEqualTo(\"c\")\n assertThat(value.get()).isEqualTo(\"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/TestAndSetTest.kt","line":52,"symbol":"`value is updated to a non-matching value between test and set`","kind":"function","lang":"kotlin","code":"@Test\n fun `value is updated to a non-matching value between test and set`() {\n val value = AtomicReference(\"a\")\n val previous =\n value.testAndSet(\"b\") {\n value.set(\"c\")\n it == \"a\"\n }\n assertThat(previous).isEqualTo(\"c\")\n assertThat(value.get()).isEqualTo(\"c\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/UtilTest.kt","line":34,"symbol":"UtilTest","kind":"class","lang":"kotlin","code":"class UtilTest {\n @Test\n fun socketIsHealthy() {\n val localhost = InetAddress.getLoopbackAddress()\n val serverSocket = ServerSocket(0, 1, localhost)\n\n val socket = Socket()\n socket.connect(serverSocket.localSocketAddress)\n val socketSource = socket.source().buffer()\n\n assertThat(socket.isHealthy(socketSource)).isTrue()\n\n serverSocket.close()\n assertThat(socket.isHealthy(socketSource)).isFalse()\n }\n\n @Test\n fun testDurationTimeUnit() {\n assertThat(checkDuration(\"timeout\", 0, TimeUnit.MILLISECONDS)).isEqualTo(0)\n assertThat(checkDuration(\"timeout\", 1, TimeUnit.MILLISECONDS)).isEqualTo(1)\n\n assertThat(\n assertThrows {\n checkDuration(\"timeout\", -1, TimeUnit.MILLISECONDS)\n },\n ).hasMessage(\"timeout < 0\")\n assertThat(\n assertThrows {\n checkDuration(\"timeout\", 1, TimeUnit.NANOSECONDS)\n },\n ).hasMessage(\"timeout too small\")\n assertThat(\n assertThrows {\n checkDuration(\n \"timeout\",\n 1L + Int.MAX_VALUE.toLong(),\n TimeUnit.MILLISECONDS,\n )\n },\n ).hasMessage(\"timeout too large\")\n }\n\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/UtilTest.kt","line":35,"symbol":"socketIsHealthy","kind":"function","lang":"kotlin","code":"@Test\n fun socketIsHealthy() {\n val localhost = InetAddress.getLoopbackAddress()\n val serverSocket = ServerSocket(0, 1, localhost)\n\n val socket = Socket()\n socket.connect(serverSocket.localSocketAddress)\n val socketSource = socket.source().buffer()\n\n assertThat(socket.isHealthy(socketSource)).isTrue()\n\n serverSocket.close()\n assertThat(socket.isHealthy(socketSource)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/UtilTest.kt","line":50,"symbol":"testDurationTimeUnit","kind":"function","lang":"kotlin","code":"@Test\n fun testDurationTimeUnit() {\n assertThat(checkDuration(\"timeout\", 0, TimeUnit.MILLISECONDS)).isEqualTo(0)\n assertThat(checkDuration(\"timeout\", 1, TimeUnit.MILLISECONDS)).isEqualTo(1)\n\n assertThat(\n assertThrows {\n checkDuration(\"timeout\", -1, TimeUnit.MILLISECONDS)\n },\n ).hasMessage(\"timeout < 0\")\n assertThat(\n assertThrows {\n checkDuration(\"timeout\", 1, TimeUnit.NANOSECONDS)\n },\n ).hasMessage(\"timeout too small\")\n assertThat(\n assertThrows {\n checkDuration(\n \"timeout\",\n 1L + Int.MAX_VALUE.toLong(),\n TimeUnit.MILLISECONDS,\n )\n },\n ).hasMessage(\"timeout too large\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/UtilTest.kt","line":76,"symbol":"testDurationDuration","kind":"function","lang":"kotlin","code":"@Test\n fun testDurationDuration() {\n assertThat(checkDuration(\"timeout\", 0.milliseconds)).isEqualTo(0)\n assertThat(checkDuration(\"timeout\", 1.milliseconds)).isEqualTo(1)\n\n assertThat(\n assertThrows {\n checkDuration(\"timeout\", (-1).milliseconds)\n },\n ).hasMessage(\"timeout < 0\")\n assertThat(\n assertThrows {\n checkDuration(\"timeout\", 1.nanoseconds)\n },\n ).hasMessage(\"timeout too small\")\n assertThat(\n assertThrows {\n checkDuration(\n \"timeout\",\n (1L + Int.MAX_VALUE).milliseconds,\n )\n },\n ).hasMessage(\"timeout too large\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/authenticator/JavaNetAuthenticatorTest.kt","line":33,"symbol":"JavaNetAuthenticatorTest","kind":"class","lang":"kotlin","doc":"Most tests from URLConnectionTest","code":"class JavaNetAuthenticatorTest {\n private var authenticator = JavaNetAuthenticator()\n private val fakeDns = FakeDns()\n private val recordingAuthenticator = RecordingAuthenticator()\n private val factory =\n TestValueFactory()\n .apply {\n dns = fakeDns\n }\n\n @BeforeEach\n fun setup() {\n Authenticator.setDefault(recordingAuthenticator)\n }\n\n @AfterEach\n fun tearDown() {\n Authenticator.setDefault(null)\n factory.close()\n }\n\n @Test\n fun testBasicAuth() {\n fakeDns[\"server\"] = listOf(InetAddress.getLocalHost())\n\n val route = factory.newRoute()\n\n val request =\n Request\n .Builder()\n .url(\"https://server/robots.txt\")\n .build()\n val response =\n Response\n .Builder()\n .request(request)\n .code(401)\n .header(\"WWW-Authenticate\", \"Basic realm=\\\"User Visible Realm\\\"\")\n .protocol(HTTP_2)\n .message(\"Unauthorized\")\n .build()\n val authRequest = authenticator.authenticate(route, response)\n\n assertEquals(\n \"Basic ${RecordingAuthenticator.BASE_64_CREDENTIALS}\",\n authRequest!!.header(\"Authorization\"),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/authenticator/JavaNetAuthenticatorTest.kt","line":43,"symbol":"setup","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setup() {\n Authenticator.setDefault(recordingAuthenticator)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/authenticator/JavaNetAuthenticatorTest.kt","line":48,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n Authenticator.setDefault(null)\n factory.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/authenticator/JavaNetAuthenticatorTest.kt","line":54,"symbol":"testBasicAuth","kind":"function","lang":"kotlin","code":"@Test\n fun testBasicAuth() {\n fakeDns[\"server\"] = listOf(InetAddress.getLocalHost())\n\n val route = factory.newRoute()\n\n val request =\n Request\n .Builder()\n .url(\"https://server/robots.txt\")\n .build()\n val response =\n Response\n .Builder()\n .request(request)\n .code(401)\n .header(\"WWW-Authenticate\", \"Basic realm=\\\"User Visible Realm\\\"\")\n .protocol(HTTP_2)\n .message(\"Unauthorized\")\n .build()\n val authRequest = authenticator.authenticate(route, response)\n\n assertEquals(\n \"Basic ${RecordingAuthenticator.BASE_64_CREDENTIALS}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/authenticator/JavaNetAuthenticatorTest.kt","line":82,"symbol":"noSupportForNonBasicAuth","kind":"function","lang":"kotlin","code":"@Test\n fun noSupportForNonBasicAuth() {\n val request =\n Request\n .Builder()\n .url(\"https://server/robots.txt\")\n .build()\n\n val response =\n Response\n .Builder()\n .request(request)\n .code(401)\n .header(\"WWW-Authenticate\", \"UnsupportedScheme realm=\\\"User Visible Realm\\\"\")\n .protocol(HTTP_2)\n .message(\"Unauthorized\")\n .build()\n\n val authRequest = authenticator.authenticate(null, response)\n assertNull(authRequest)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":50,"symbol":"DiskLruCacheTest","kind":"class","lang":"kotlin","code":"@Timeout(60)\n@Tag(\"Slow\")\n@Burst\nclass DiskLruCacheTest(\n subject: Subject = Subject.System,\n) {\n private val baseFilesystem: FileSystem = subject.create()\n private val filesystem = FaultyFileSystem(baseFilesystem)\n private val windows = subject.windows\n\n @TempDir\n lateinit var cacheDirFile: File\n private val cacheDir: Path\n get() =\n when (baseFilesystem) {\n is FakeFileSystem -> \"/cache\".toPath()\n else -> cacheDirFile.path.toPath()\n }\n private val appVersion = 100\n private lateinit var journalFile: Path\n private lateinit var journalBkpFile: Path\n private val taskFaker = TaskFaker()\n private val taskRunner = taskFaker.taskRunner\n private lateinit var cache: DiskLruCache\n private val toClose = ArrayDeque()\n\n private fun createNewCache() {\n createNewCacheWithSize(Int.MAX_VALUE)\n }\n\n private fun createNewCacheWithSize(maxSize: Int) {\n cache =\n DiskLruCache(filesystem, cacheDir, appVersion, 2, maxSize.toLong(), taskRunner).also {\n toClose.add(it)\n }\n synchronized(cache) { cache.initialize() }\n }\n\n @BeforeEach\n fun setUp() {\n if (filesystem.exists(cacheDir)) {\n filesystem.deleteRecursively(cach"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":76,"symbol":"createNewCache","kind":"function","lang":"kotlin","code":"private fun createNewCache() {\n createNewCacheWithSize(Int.MAX_VALUE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":80,"symbol":"createNewCacheWithSize","kind":"function","lang":"kotlin","code":"private fun createNewCacheWithSize(maxSize: Int) {\n cache =\n DiskLruCache(filesystem, cacheDir, appVersion, 2, maxSize.toLong(), taskRunner).also {\n toClose.add(it)\n }\n synchronized(cache) { cache.initialize() }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":88,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n if (filesystem.exists(cacheDir)) {\n filesystem.deleteRecursively(cacheDir)\n }\n journalFile = cacheDir / DiskLruCache.JOURNAL_FILE\n journalBkpFile = cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP\n createNewCache()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":98,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n while (!toClose.isEmpty()) {\n toClose.pop().close()\n }\n taskFaker.close()\n\n (filesystem.delegate as? FakeFileSystem)?.checkNoOpenFiles()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":107,"symbol":"emptyCache","kind":"function","lang":"kotlin","code":"@Test\n fun emptyCache() {\n cache.close()\n assertJournalEquals()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":113,"symbol":"recoverFromInitializationFailure","kind":"function","lang":"kotlin","code":"@Test\n fun recoverFromInitializationFailure() {\n // Add an uncommitted entry. This will get detected on initialization, and the cache will\n // attempt to delete the file. Do not explicitly close the cache here so the entry is left as\n // incomplete.\n val creator = cache.edit(\"k1\")!!\n creator.newSink(0).buffer().use {\n it.writeUtf8(\"Hello\")\n }\n\n // Simulate a severe Filesystem failure on the first initialization.\n filesystem.setFaultyDelete(cacheDir / \"k1.0.tmp\", true)\n filesystem.setFaultyDelete(cacheDir, true)\n cache =\n DiskLruCache(filesystem, cacheDir, appVersion, 2, Int.MAX_VALUE.toLong(), taskRunner).also {\n toClose.add(it)\n }\n assertFailsWith {\n cache[\"k1\"]\n }\n\n // Now let it operate normally.\n filesystem.setFaultyDelete(cacheDir / \"k1.0.tmp\", false)\n filesystem.setFaultyDelete(cacheDir, false)\n val snapshot = cache[\"k1\"]\n assertThat(snapshot).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":141,"symbol":"validateKey","kind":"function","lang":"kotlin","code":"@Test\n fun validateKey() {\n var key = \"\"\n assertFailsWith {\n key = \"has_space \"\n cache.edit(key)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"keys must match regex [a-z0-9_-]{1,120}: \\\"$key\\\"\")\n }\n assertFailsWith {\n key = \"has_CR\\r\"\n cache.edit(key)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"keys must match regex [a-z0-9_-]{1,120}: \\\"$key\\\"\")\n }\n assertFailsWith {\n key = \"has_LF\\n\"\n cache.edit(key)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"keys must match regex [a-z0-9_-]{1,120}: \\\"$key\\\"\")\n }\n assertFailsWith {\n key = \"has_invalid/\"\n cache.edit(key)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"keys must match regex [a-z0-9_-]{1,120}: \\\"$key\\\"\")\n }\n assertFailsWith {\n key = \"has_invalid\\u2603\"\n cache.edit(key)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":200,"symbol":"writeAndReadEntry","kind":"function","lang":"kotlin","code":"@Test\n fun writeAndReadEntry() {\n val creator = cache.edit(\"k1\")!!\n creator.setString(0, \"ABC\")\n creator.setString(1, \"DE\")\n assertThat(creator.newSource(0)).isNull()\n assertThat(creator.newSource(1)).isNull()\n creator.commit()\n val snapshot = cache[\"k1\"]!!\n snapshot.assertValue(0, \"ABC\")\n snapshot.assertValue(1, \"DE\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":213,"symbol":"readAndWriteEntryAcrossCacheOpenAndClose","kind":"function","lang":"kotlin","code":"@Test\n fun readAndWriteEntryAcrossCacheOpenAndClose() {\n val creator = cache.edit(\"k1\")!!\n creator.setString(0, \"A\")\n creator.setString(1, \"B\")\n creator.commit()\n cache.close()\n createNewCache()\n val snapshot = cache[\"k1\"]!!\n snapshot.assertValue(0, \"A\")\n snapshot.assertValue(1, \"B\")\n snapshot.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":227,"symbol":"readAndWriteEntryWithoutProperClose","kind":"function","lang":"kotlin","code":"@Test\n fun readAndWriteEntryWithoutProperClose() {\n val creator = cache.edit(\"k1\")!!\n creator.setString(0, \"A\")\n creator.setString(1, \"B\")\n creator.commit()\n\n // Simulate a dirty close of 'cache' by opening the cache directory again.\n createNewCache()\n cache[\"k1\"]!!.use {\n it.assertValue(0, \"A\")\n it.assertValue(1, \"B\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":242,"symbol":"journalWithEditAndPublish","kind":"function","lang":"kotlin","code":"@Test\n fun journalWithEditAndPublish() {\n val creator = cache.edit(\"k1\")!!\n assertJournalEquals(\"DIRTY k1\") // DIRTY must always be flushed.\n creator.setString(0, \"AB\")\n creator.setString(1, \"C\")\n creator.commit()\n cache.close()\n assertJournalEquals(\"DIRTY k1\", \"CLEAN k1 2 1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":253,"symbol":"revertedNewFileIsRemoveInJournal","kind":"function","lang":"kotlin","code":"@Test\n fun revertedNewFileIsRemoveInJournal() {\n val creator = cache.edit(\"k1\")!!\n assertJournalEquals(\"DIRTY k1\") // DIRTY must always be flushed.\n creator.setString(0, \"AB\")\n creator.setString(1, \"C\")\n creator.abort()\n cache.close()\n assertJournalEquals(\"DIRTY k1\", \"REMOVE k1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":265,"symbol":"`unterminated edit is reverted on cache close`","kind":"function","lang":"kotlin","doc":"On Windows we have to wait until the edit is committed before we can delete its files.","code":"@Test\n fun `unterminated edit is reverted on cache close`() {\n val editor = cache.edit(\"k1\")!!\n editor.setString(0, \"AB\")\n editor.setString(1, \"C\")\n cache.close()\n val expected = if (windows) arrayOf(\"DIRTY k1\") else arrayOf(\"DIRTY k1\", \"REMOVE k1\")\n assertJournalEquals(*expected)\n editor.commit()\n assertJournalEquals(*expected) // 'REMOVE k1' not written because journal is closed.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":277,"symbol":"journalDoesNotIncludeReadOfYetUnpublishedValue","kind":"function","lang":"kotlin","code":"@Test\n fun journalDoesNotIncludeReadOfYetUnpublishedValue() {\n val creator = cache.edit(\"k1\")!!\n assertThat(cache[\"k1\"]).isNull()\n creator.setString(0, \"A\")\n creator.setString(1, \"BC\")\n creator.commit()\n cache.close()\n assertJournalEquals(\"DIRTY k1\", \"CLEAN k1 1 2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":288,"symbol":"journalWithEditAndPublishAndRead","kind":"function","lang":"kotlin","code":"@Test\n fun journalWithEditAndPublishAndRead() {\n val k1Creator = cache.edit(\"k1\")!!\n k1Creator.setString(0, \"AB\")\n k1Creator.setString(1, \"C\")\n k1Creator.commit()\n val k2Creator = cache.edit(\"k2\")!!\n k2Creator.setString(0, \"DEF\")\n k2Creator.setString(1, \"G\")\n k2Creator.commit()\n val k1Snapshot = cache[\"k1\"]!!\n k1Snapshot.close()\n cache.close()\n assertJournalEquals(\"DIRTY k1\", \"CLEAN k1 2 1\", \"DIRTY k2\", \"CLEAN k2 3 1\", \"READ k1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":304,"symbol":"cannotOperateOnEditAfterPublish","kind":"function","lang":"kotlin","code":"@Test\n fun cannotOperateOnEditAfterPublish() {\n val editor = cache.edit(\"k1\")!!\n editor.setString(0, \"A\")\n editor.setString(1, \"B\")\n editor.commit()\n editor.assertInoperable()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":313,"symbol":"cannotOperateOnEditAfterRevert","kind":"function","lang":"kotlin","code":"@Test\n fun cannotOperateOnEditAfterRevert() {\n val editor = cache.edit(\"k1\")!!\n editor.setString(0, \"A\")\n editor.setString(1, \"B\")\n editor.abort()\n editor.assertInoperable()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":322,"symbol":"explicitRemoveAppliedToDiskImmediately","kind":"function","lang":"kotlin","code":"@Test\n fun explicitRemoveAppliedToDiskImmediately() {\n val editor = cache.edit(\"k1\")!!\n editor.setString(0, \"ABC\")\n editor.setString(1, \"B\")\n editor.commit()\n val k1 = getCleanFile(\"k1\", 0)\n assertThat(readFile(k1)).isEqualTo(\"ABC\")\n cache.remove(\"k1\")\n assertThat(filesystem.exists(k1)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":334,"symbol":"removePreventsActiveEditFromStoringAValue","kind":"function","lang":"kotlin","code":"@Test\n fun removePreventsActiveEditFromStoringAValue() {\n set(\"a\", \"a\", \"a\")\n val a = cache.edit(\"a\")!!\n a.setString(0, \"a1\")\n assertThat(cache.remove(\"a\")).isTrue()\n a.setString(1, \"a2\")\n a.commit()\n assertAbsent(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":349,"symbol":"readAndWriteOverlapsMaintainConsistency","kind":"function","lang":"kotlin","doc":"Each read sees a snapshot of the file at the time read was called. This means that two reads of the same key can see different data.","code":"@Test\n fun readAndWriteOverlapsMaintainConsistency() {\n Assumptions.assumeFalse(windows) // Can't edit while a read is in progress.\n\n val v1Creator = cache.edit(\"k1\")!!\n v1Creator.setString(0, \"AAaa\")\n v1Creator.setString(1, \"BBbb\")\n v1Creator.commit()\n\n cache[\"k1\"]!!.use { snapshot1 ->\n val inV1 = snapshot1.getSource(0).buffer()\n assertThat(inV1.readByte()).isEqualTo('A'.code.toByte())\n assertThat(inV1.readByte()).isEqualTo('A'.code.toByte())\n\n val v1Updater = cache.edit(\"k1\")!!\n v1Updater.setString(0, \"CCcc\")\n v1Updater.setString(1, \"DDdd\")\n v1Updater.commit()\n\n cache[\"k1\"]!!.use { snapshot2 ->\n snapshot2.assertValue(0, \"CCcc\")\n snapshot2.assertValue(1, \"DDdd\")\n }\n\n assertThat(inV1.readByte()).isEqualTo('a'.code.toByte())\n assertThat(inV1.readByte()).isEqualTo('a'.code.toByte())\n snapshot1.assertValue(1, \"BBbb\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":379,"symbol":"openWithDirtyKeyDeletesAllFilesForThatKey","kind":"function","lang":"kotlin","code":"@Test\n fun openWithDirtyKeyDeletesAllFilesForThatKey() {\n cache.close()\n val cleanFile0 = getCleanFile(\"k1\", 0)\n val cleanFile1 = getCleanFile(\"k1\", 1)\n val dirtyFile0 = getDirtyFile(\"k1\", 0)\n val dirtyFile1 = getDirtyFile(\"k1\", 1)\n writeFile(cleanFile0, \"A\")\n writeFile(cleanFile1, \"B\")\n writeFile(dirtyFile0, \"C\")\n writeFile(dirtyFile1, \"D\")\n createJournal(\"CLEAN k1 1 1\", \"DIRTY k1\")\n createNewCache()\n assertThat(filesystem.exists(cleanFile0)).isFalse()\n assertThat(filesystem.exists(cleanFile1)).isFalse()\n assertThat(filesystem.exists(dirtyFile0)).isFalse()\n assertThat(filesystem.exists(dirtyFile1)).isFalse()\n assertThat(cache[\"k1\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":399,"symbol":"openWithInvalidVersionClearsDirectory","kind":"function","lang":"kotlin","code":"@Test\n fun openWithInvalidVersionClearsDirectory() {\n cache.close()\n generateSomeGarbageFiles()\n createJournalWithHeader(DiskLruCache.MAGIC, \"0\", \"100\", \"2\", \"\")\n createNewCache()\n assertGarbageFilesAllDeleted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":408,"symbol":"openWithInvalidAppVersionClearsDirectory","kind":"function","lang":"kotlin","code":"@Test\n fun openWithInvalidAppVersionClearsDirectory() {\n cache.close()\n generateSomeGarbageFiles()\n createJournalWithHeader(DiskLruCache.MAGIC, \"1\", \"101\", \"2\", \"\")\n createNewCache()\n assertGarbageFilesAllDeleted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":417,"symbol":"openWithInvalidValueCountClearsDirectory","kind":"function","lang":"kotlin","code":"@Test\n fun openWithInvalidValueCountClearsDirectory() {\n cache.close()\n generateSomeGarbageFiles()\n createJournalWithHeader(DiskLruCache.MAGIC, \"1\", \"100\", \"1\", \"\")\n createNewCache()\n assertGarbageFilesAllDeleted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":426,"symbol":"openWithInvalidBlankLineClearsDirectory","kind":"function","lang":"kotlin","code":"@Test\n fun openWithInvalidBlankLineClearsDirectory() {\n cache.close()\n generateSomeGarbageFiles()\n createJournalWithHeader(DiskLruCache.MAGIC, \"1\", \"100\", \"2\", \"x\")\n createNewCache()\n assertGarbageFilesAllDeleted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":435,"symbol":"openWithInvalidJournalLineClearsDirectory","kind":"function","lang":"kotlin","code":"@Test\n fun openWithInvalidJournalLineClearsDirectory() {\n cache.close()\n generateSomeGarbageFiles()\n createJournal(\"CLEAN k1 1 1\", \"BOGUS\")\n createNewCache()\n assertGarbageFilesAllDeleted()\n assertThat(cache[\"k1\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":445,"symbol":"openWithInvalidFileSizeClearsDirectory","kind":"function","lang":"kotlin","code":"@Test\n fun openWithInvalidFileSizeClearsDirectory() {\n cache.close()\n generateSomeGarbageFiles()\n createJournal(\"CLEAN k1 0000x001 1\")\n createNewCache()\n assertGarbageFilesAllDeleted()\n assertThat(cache[\"k1\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":455,"symbol":"openWithTruncatedLineDiscardsThatLine","kind":"function","lang":"kotlin","code":"@Test\n fun openWithTruncatedLineDiscardsThatLine() {\n cache.close()\n writeFile(getCleanFile(\"k1\", 0), \"A\")\n writeFile(getCleanFile(\"k1\", 1), \"B\")\n filesystem.write(journalFile) {\n writeUtf8(\n // No trailing newline.\n \"\"\"\n |${DiskLruCache.MAGIC}\n |${DiskLruCache.VERSION_1}\n |100\n |2\n |\n |CLEAN k1 1 1\n \"\"\".trimMargin(),\n )\n }\n createNewCache()\n assertThat(cache[\"k1\"]).isNull()\n\n // The journal is not corrupt when editing after a truncated line.\n set(\"k1\", \"C\", \"D\")\n cache.close()\n createNewCache()\n assertValue(\"k1\", \"C\", \"D\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":483,"symbol":"openWithTooManyFileSizesClearsDirectory","kind":"function","lang":"kotlin","code":"@Test\n fun openWithTooManyFileSizesClearsDirectory() {\n cache.close()\n generateSomeGarbageFiles()\n createJournal(\"CLEAN k1 1 1 1\")\n createNewCache()\n assertGarbageFilesAllDeleted()\n assertThat(cache[\"k1\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":493,"symbol":"keyWithSpaceNotPermitted","kind":"function","lang":"kotlin","code":"@Test\n fun keyWithSpaceNotPermitted() {\n assertFailsWith {\n cache.edit(\"my key\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":500,"symbol":"keyWithNewlineNotPermitted","kind":"function","lang":"kotlin","code":"@Test\n fun keyWithNewlineNotPermitted() {\n assertFailsWith {\n cache.edit(\"my\\nkey\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":507,"symbol":"keyWithCarriageReturnNotPermitted","kind":"function","lang":"kotlin","code":"@Test\n fun keyWithCarriageReturnNotPermitted() {\n assertFailsWith {\n cache.edit(\"my\\rkey\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":514,"symbol":"createNewEntryWithTooFewValuesFails","kind":"function","lang":"kotlin","code":"@Test\n fun createNewEntryWithTooFewValuesFails() {\n val creator = cache.edit(\"k1\")!!\n creator.setString(1, \"A\")\n assertFailsWith {\n creator.commit()\n }\n assertThat(filesystem.exists(getCleanFile(\"k1\", 0))).isFalse()\n assertThat(filesystem.exists(getCleanFile(\"k1\", 1))).isFalse()\n assertThat(filesystem.exists(getDirtyFile(\"k1\", 0))).isFalse()\n assertThat(filesystem.exists(getDirtyFile(\"k1\", 1))).isFalse()\n assertThat(cache[\"k1\"]).isNull()\n val creator2 = cache.edit(\"k1\")!!\n creator2.setString(0, \"B\")\n creator2.setString(1, \"C\")\n creator2.commit()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":532,"symbol":"revertWithTooFewValues","kind":"function","lang":"kotlin","code":"@Test\n fun revertWithTooFewValues() {\n val creator = cache.edit(\"k1\")!!\n creator.setString(1, \"A\")\n creator.abort()\n assertThat(filesystem.exists(getCleanFile(\"k1\", 0))).isFalse()\n assertThat(filesystem.exists(getCleanFile(\"k1\", 1))).isFalse()\n assertThat(filesystem.exists(getDirtyFile(\"k1\", 0))).isFalse()\n assertThat(filesystem.exists(getDirtyFile(\"k1\", 1))).isFalse()\n assertThat(cache[\"k1\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":544,"symbol":"updateExistingEntryWithTooFewValuesReusesPreviousValues","kind":"function","lang":"kotlin","code":"@Test\n fun updateExistingEntryWithTooFewValuesReusesPreviousValues() {\n val creator = cache.edit(\"k1\")!!\n creator.setString(0, \"A\")\n creator.setString(1, \"B\")\n creator.commit()\n val updater = cache.edit(\"k1\")!!\n updater.setString(0, \"C\")\n updater.commit()\n val snapshot = cache[\"k1\"]!!\n snapshot.assertValue(0, \"C\")\n snapshot.assertValue(1, \"B\")\n snapshot.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":559,"symbol":"growMaxSize","kind":"function","lang":"kotlin","code":"@Test\n fun growMaxSize() {\n cache.close()\n createNewCacheWithSize(10)\n set(\"a\", \"a\", \"aaa\") // size 4\n set(\"b\", \"bb\", \"bbbb\") // size 6\n cache.maxSize = 20\n set(\"c\", \"c\", \"c\") // size 12\n assertThat(cache.size()).isEqualTo(12)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":570,"symbol":"shrinkMaxSizeEvicts","kind":"function","lang":"kotlin","code":"@Test\n fun shrinkMaxSizeEvicts() {\n cache.close()\n createNewCacheWithSize(20)\n set(\"a\", \"a\", \"aaa\") // size 4\n set(\"b\", \"bb\", \"bbbb\") // size 6\n set(\"c\", \"c\", \"c\") // size 12\n cache.maxSize = 10\n assertThat(taskFaker.isIdle()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":581,"symbol":"evictOnInsert","kind":"function","lang":"kotlin","code":"@Test\n fun evictOnInsert() {\n cache.close()\n createNewCacheWithSize(10)\n set(\"a\", \"a\", \"aaa\") // size 4\n set(\"b\", \"bb\", \"bbbb\") // size 6\n assertThat(cache.size()).isEqualTo(10)\n\n // Cause the size to grow to 12 should evict 'A'.\n set(\"c\", \"c\", \"c\")\n cache.flush()\n assertThat(cache.size()).isEqualTo(8)\n assertAbsent(\"a\")\n assertValue(\"b\", \"bb\", \"bbbb\")\n assertValue(\"c\", \"c\", \"c\")\n\n // Causing the size to grow to 10 should evict nothing.\n set(\"d\", \"d\", \"d\")\n cache.flush()\n assertThat(cache.size()).isEqualTo(10)\n assertAbsent(\"a\")\n assertValue(\"b\", \"bb\", \"bbbb\")\n assertValue(\"c\", \"c\", \"c\")\n assertValue(\"d\", \"d\", \"d\")\n\n // Causing the size to grow to 18 should evict 'B' and 'C'.\n set(\"e\", \"eeee\", \"eeee\")\n cache.flush()\n assertThat(cache.size()).isEqualTo(10)\n assertAbsent(\"a\")\n assertAbsent(\"b\")\n assertAbsent(\"c\")\n assertValue(\"d\", \"d\", \"d\")\n assertValue(\"e\", \"eeee\", \"eeee\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":617,"symbol":"evictOnUpdate","kind":"function","lang":"kotlin","code":"@Test\n fun evictOnUpdate() {\n cache.close()\n createNewCacheWithSize(10)\n set(\"a\", \"a\", \"aa\") // size 3\n set(\"b\", \"b\", \"bb\") // size 3\n set(\"c\", \"c\", \"cc\") // size 3\n assertThat(cache.size()).isEqualTo(9)\n\n // Causing the size to grow to 11 should evict 'A'.\n set(\"b\", \"b\", \"bbbb\")\n cache.flush()\n assertThat(cache.size()).isEqualTo(8)\n assertAbsent(\"a\")\n assertValue(\"b\", \"b\", \"bbbb\")\n assertValue(\"c\", \"c\", \"cc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":635,"symbol":"evictionHonorsLruFromCurrentSession","kind":"function","lang":"kotlin","code":"@Test\n fun evictionHonorsLruFromCurrentSession() {\n cache.close()\n createNewCacheWithSize(10)\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n set(\"c\", \"c\", \"c\")\n set(\"d\", \"d\", \"d\")\n set(\"e\", \"e\", \"e\")\n cache[\"b\"]!!.close() // 'B' is now least recently used.\n\n // Causing the size to grow to 12 should evict 'A'.\n set(\"f\", \"f\", \"f\")\n // Causing the size to grow to 12 should evict 'C'.\n set(\"g\", \"g\", \"g\")\n cache.flush()\n assertThat(cache.size()).isEqualTo(10)\n assertAbsent(\"a\")\n assertValue(\"b\", \"b\", \"b\")\n assertAbsent(\"c\")\n assertValue(\"d\", \"d\", \"d\")\n assertValue(\"e\", \"e\", \"e\")\n assertValue(\"f\", \"f\", \"f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":660,"symbol":"evictionHonorsLruFromPreviousSession","kind":"function","lang":"kotlin","code":"@Test\n fun evictionHonorsLruFromPreviousSession() {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n set(\"c\", \"c\", \"c\")\n set(\"d\", \"d\", \"d\")\n set(\"e\", \"e\", \"e\")\n set(\"f\", \"f\", \"f\")\n cache[\"b\"]!!.close() // 'B' is now least recently used.\n assertThat(cache.size()).isEqualTo(12)\n cache.close()\n createNewCacheWithSize(10)\n set(\"g\", \"g\", \"g\")\n cache.flush()\n assertThat(cache.size()).isEqualTo(10)\n assertAbsent(\"a\")\n assertValue(\"b\", \"b\", \"b\")\n assertAbsent(\"c\")\n assertValue(\"d\", \"d\", \"d\")\n assertValue(\"e\", \"e\", \"e\")\n assertValue(\"f\", \"f\", \"f\")\n assertValue(\"g\", \"g\", \"g\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":684,"symbol":"cacheSingleEntryOfSizeGreaterThanMaxSize","kind":"function","lang":"kotlin","code":"@Test\n fun cacheSingleEntryOfSizeGreaterThanMaxSize() {\n cache.close()\n createNewCacheWithSize(10)\n set(\"a\", \"aaaaa\", \"aaaaaa\") // size=11\n cache.flush()\n assertAbsent(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":693,"symbol":"cacheSingleValueOfSizeGreaterThanMaxSize","kind":"function","lang":"kotlin","code":"@Test\n fun cacheSingleValueOfSizeGreaterThanMaxSize() {\n cache.close()\n createNewCacheWithSize(10)\n set(\"a\", \"aaaaaaaaaaa\", \"a\") // size=12\n cache.flush()\n assertAbsent(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":702,"symbol":"constructorDoesNotAllowZeroCacheSize","kind":"function","lang":"kotlin","code":"@Test\n fun constructorDoesNotAllowZeroCacheSize() {\n assertFailsWith {\n DiskLruCache(filesystem, cacheDir, appVersion, 2, 0, taskRunner)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":709,"symbol":"constructorDoesNotAllowZeroValuesPerEntry","kind":"function","lang":"kotlin","code":"@Test\n fun constructorDoesNotAllowZeroValuesPerEntry() {\n assertFailsWith {\n DiskLruCache(filesystem, cacheDir, appVersion, 0, 10, taskRunner)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":716,"symbol":"removeAbsentElement","kind":"function","lang":"kotlin","code":"@Test\n fun removeAbsentElement() {\n cache.remove(\"a\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":721,"symbol":"readingTheSameStreamMultipleTimes","kind":"function","lang":"kotlin","code":"@Test\n fun readingTheSameStreamMultipleTimes() {\n set(\"a\", \"a\", \"b\")\n val snapshot = cache[\"a\"]!!\n assertThat(snapshot.getSource(0)).isSameInstanceAs(snapshot.getSource(0))\n snapshot.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":729,"symbol":"rebuildJournalOnRepeatedReads","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalOnRepeatedReads() {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n while (taskFaker.isIdle()) {\n assertValue(\"a\", \"a\", \"a\")\n assertValue(\"b\", \"b\", \"b\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":739,"symbol":"rebuildJournalOnRepeatedEdits","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalOnRepeatedEdits() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n }\n taskFaker.runNextTask()\n\n // Check that a rebuilt journal behaves normally.\n assertValue(\"a\", \"a\", \"a\")\n assertValue(\"b\", \"b\", \"b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":753,"symbol":"rebuildJournalOnRepeatedReadsWithOpenAndClose","kind":"function","lang":"kotlin","doc":"@see [Issue 28](https://github.com/JakeWharton/DiskLruCache/issues/28)","code":"@Test\n fun rebuildJournalOnRepeatedReadsWithOpenAndClose() {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n while (taskFaker.isIdle()) {\n assertValue(\"a\", \"a\", \"a\")\n assertValue(\"b\", \"b\", \"b\")\n cache.close()\n createNewCache()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":766,"symbol":"rebuildJournalOnRepeatedEditsWithOpenAndClose","kind":"function","lang":"kotlin","doc":"@see [Issue 28](https://github.com/JakeWharton/DiskLruCache/issues/28)","code":"@Test\n fun rebuildJournalOnRepeatedEditsWithOpenAndClose() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n cache.close()\n createNewCache()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":776,"symbol":"rebuildJournalFailurePreventsEditors","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalFailurePreventsEditors() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n }\n\n // Cause the rebuild action to fail.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, true)\n taskFaker.runNextTask()\n\n // Don't allow edits under any circumstances.\n assertThat(cache.edit(\"a\")).isNull()\n assertThat(cache.edit(\"c\")).isNull()\n cache[\"a\"]!!.use {\n assertThat(it.edit()).isNull()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":795,"symbol":"rebuildJournalFailureIsRetried","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalFailureIsRetried() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n }\n\n // Cause the rebuild action to fail.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, true)\n taskFaker.runNextTask()\n\n // The rebuild is retried on cache hits and on cache edits.\n val snapshot = cache[\"b\"]!!\n snapshot.close()\n assertThat(cache.edit(\"d\")).isNull()\n assertThat(taskFaker.isIdle()).isFalse()\n\n // On cache misses, no retry job is queued.\n assertThat(cache[\"c\"]).isNull()\n assertThat(taskFaker.isIdle()).isFalse()\n\n // Let the rebuild complete successfully.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, false)\n taskFaker.runNextTask()\n assertJournalEquals(\"CLEAN a 1 1\", \"CLEAN b 1 1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":822,"symbol":"rebuildJournalFailureWithInFlightEditors","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalFailureWithInFlightEditors() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n }\n val commitEditor = cache.edit(\"c\")!!\n val abortEditor = cache.edit(\"d\")!!\n cache.edit(\"e\") // Grab an editor, but don't do anything with it.\n\n // Cause the rebuild action to fail.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, true)\n taskFaker.runNextTask()\n\n // In-flight editors can commit and have their values retained.\n commitEditor.setString(0, \"c\")\n commitEditor.setString(1, \"c\")\n commitEditor.commit()\n assertValue(\"c\", \"c\", \"c\")\n abortEditor.abort()\n\n // Let the rebuild complete successfully.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, false)\n taskFaker.runNextTask()\n assertJournalEquals(\"CLEAN a 1 1\", \"CLEAN b 1 1\", \"DIRTY e\", \"CLEAN c 1 1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":849,"symbol":"rebuildJournalFailureWithEditorsInFlightThenClose","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalFailureWithEditorsInFlightThenClose() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n }\n val commitEditor = cache.edit(\"c\")!!\n val abortEditor = cache.edit(\"d\")!!\n cache.edit(\"e\") // Grab an editor, but don't do anything with it.\n\n // Cause the rebuild action to fail.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, true)\n taskFaker.runNextTask()\n commitEditor.setString(0, \"c\")\n commitEditor.setString(1, \"c\")\n commitEditor.commit()\n assertValue(\"c\", \"c\", \"c\")\n abortEditor.abort()\n cache.close()\n createNewCache()\n\n // Although 'c' successfully committed above, the journal wasn't available to issue a CLEAN op.\n // Because the last state of 'c' was DIRTY before the journal failed, it should be removed\n // entirely on a subsequent open.\n assertThat(cache.size()).isEqualTo(4)\n assertAbsent(\"c\")\n assertAbsent(\"d\")\n assertAbsent(\"e\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":879,"symbol":"rebuildJournalFailureAllowsRemovals","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalFailureAllowsRemovals() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n }\n\n // Cause the rebuild action to fail.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, true)\n taskFaker.runNextTask()\n assertThat(cache.remove(\"a\")).isTrue()\n assertAbsent(\"a\")\n\n // Let the rebuild complete successfully.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, false)\n taskFaker.runNextTask()\n assertJournalEquals(\"CLEAN b 1 1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":898,"symbol":"rebuildJournalFailureWithRemovalThenClose","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalFailureWithRemovalThenClose() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n }\n\n // Cause the rebuild action to fail.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, true)\n taskFaker.runNextTask()\n assertThat(cache.remove(\"a\")).isTrue()\n assertAbsent(\"a\")\n cache.close()\n createNewCache()\n\n // The journal will have no record that 'a' was removed. It will have an entry for 'a', but when\n // it tries to read the cache files, it will find they were deleted. Once it encounters an entry\n // with missing cache files, it should remove it from the cache entirely.\n assertThat(cache.size()).isEqualTo(4)\n assertThat(cache[\"a\"]).isNull()\n assertThat(cache.size()).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":921,"symbol":"rebuildJournalFailureAllowsEvictAll","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalFailureAllowsEvictAll() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"a\", \"a\")\n set(\"b\", \"b\", \"b\")\n }\n\n // Cause the rebuild action to fail.\n filesystem.setFaultyRename(cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP, true)\n taskFaker.runNextTask()\n cache.evictAll()\n assertThat(cache.size()).isEqualTo(0)\n assertAbsent(\"a\")\n assertAbsent(\"b\")\n cache.close()\n createNewCache()\n\n // The journal has no record that 'a' and 'b' were removed. It will have an entry for both, but\n // when it tries to read the cache files for either entry, it will discover the cache files are\n // missing and remove the entries from the cache.\n assertThat(cache.size()).isEqualTo(4)\n assertThat(cache[\"a\"]).isNull()\n assertThat(cache[\"b\"]).isNull()\n assertThat(cache.size()).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/cache/DiskLruCacheTest.kt","line":947,"symbol":"rebuildJournalFailureWithCacheTrim","kind":"function","lang":"kotlin","code":"@Test\n fun rebuildJournalFailureWithCacheTrim() {\n while (taskFaker.isIdle()) {\n set(\"a\", \"aa\", \"aa\")\n set(\"b\", \"bb\", \"bb\")\n }\n\n // Cause the rebuild action to fail.\n filesystem.setFaultyRename(\n cacheDir / DiskLruCache.JOURNAL_FILE_BACKUP,\n true,\n )\n taskFaker.runNextTask()\n\n // Trigger a job to trim the cache.\n cache.maxSize = 4\n taskFaker.runNextTask()\n assertAbsent(\"a\")\n assertValue(\"b\", \"bb\", \"bb\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskLoggerTest.kt","line":22,"symbol":"TaskLoggerTest","kind":"class","lang":"kotlin","code":"class TaskLoggerTest {\n @Suppress(\"ktlint\")\n @Test fun formatTime() {\n assertThat(formatDuration(-3_499_999_999L)).isEqualTo(\" -3 s \")\n assertThat(formatDuration(-3_000_000_000L)).isEqualTo(\" -3 s \")\n assertThat(formatDuration(-2_500_000_000L)).isEqualTo(\" -3 s \")\n assertThat(formatDuration(-2_499_999_999L)).isEqualTo(\" -2 s \")\n assertThat(formatDuration(-1_500_000_000L)).isEqualTo(\" -2 s \")\n assertThat(formatDuration(-1_499_999_999L)).isEqualTo(\" -1 s \")\n assertThat(formatDuration(-1_000_000_000L)).isEqualTo(\" -1 s \")\n assertThat(formatDuration( -999_500_000L)).isEqualTo(\" -1 s \")\n assertThat(formatDuration( -999_499_999L)).isEqualTo(\"-999 ms\")\n assertThat(formatDuration( -998_500_000L)).isEqualTo(\"-999 ms\")\n assertThat(formatDuration( -998_499_999L)).isEqualTo(\"-998 ms\")\n assertThat(formatDuration( -1_499_999L)).isEqualTo(\" -1 ms\")\n assertThat(formatDuration( -999_500L)).isEqualTo(\" -1 ms\")\n assertThat(formatDuration( -999_499L)).isEqualTo(\"-999 µs\")\n assertThat(formatDuration( -998_500L)).isEqualTo(\"-999 µs\")\n assertThat(formatDuration( -1_500L)).isEqualTo(\" -2 µs\")\n assertThat(formatDuration( "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskLoggerTest.kt","line":23,"symbol":"formatTime","kind":"function","lang":"kotlin","code":"@Suppress(\"ktlint\")\n @Test fun formatTime() {\n assertThat(formatDuration(-3_499_999_999L)).isEqualTo(\" -3 s \")\n assertThat(formatDuration(-3_000_000_000L)).isEqualTo(\" -3 s \")\n assertThat(formatDuration(-2_500_000_000L)).isEqualTo(\" -3 s \")\n assertThat(formatDuration(-2_499_999_999L)).isEqualTo(\" -2 s \")\n assertThat(formatDuration(-1_500_000_000L)).isEqualTo(\" -2 s \")\n assertThat(formatDuration(-1_499_999_999L)).isEqualTo(\" -1 s \")\n assertThat(formatDuration(-1_000_000_000L)).isEqualTo(\" -1 s \")\n assertThat(formatDuration( -999_500_000L)).isEqualTo(\" -1 s \")\n assertThat(formatDuration( -999_499_999L)).isEqualTo(\"-999 ms\")\n assertThat(formatDuration( -998_500_000L)).isEqualTo(\"-999 ms\")\n assertThat(formatDuration( -998_499_999L)).isEqualTo(\"-998 ms\")\n assertThat(formatDuration( -1_499_999L)).isEqualTo(\" -1 ms\")\n assertThat(formatDuration( -999_500L)).isEqualTo(\" -1 ms\")\n assertThat(formatDuration( -999_499L)).isEqualTo(\"-999 µs\")\n assertThat(formatDuration( -998_500L)).isEqualTo(\"-999 µs\")\n assertThat(formatDuration( -1_500L)).isEqualTo(\" -2 µs\")\n assertThat(formatDuration( -1_499L)).isEqualTo(\" "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerRealBackendTest.kt","line":38,"symbol":"TaskRunnerRealBackendTest","kind":"class","lang":"kotlin","doc":"Integration test to confirm that [TaskRunner] works with a real backend. Business logic is all exercised by [TaskRunnerTest]. This test is doing real sleeping with tolerances of 250 ms. Hopefully that's enough for even the busiest of CI servers.","code":"@Tag(\"Slowish\")\nclass TaskRunnerRealBackendTest {\n private val log = LinkedBlockingDeque()\n\n private val loggingUncaughtExceptionHandler =\n UncaughtExceptionHandler { _, throwable ->\n log.put(\"uncaught exception: $throwable\")\n }\n\n private val threadFactory =\n ThreadFactory { runnable ->\n Thread(runnable, \"TaskRunnerRealBackendTest\").apply {\n isDaemon = true\n uncaughtExceptionHandler = loggingUncaughtExceptionHandler\n }\n }\n\n private val backend = TaskRunner.RealBackend(threadFactory)\n private val taskRunner = TaskRunner(backend)\n private val queue = taskRunner.newQueue()\n\n @AfterEach fun tearDown() {\n backend.shutdown()\n }\n\n @Test fun test() {\n val t1 = System.nanoTime() / 1e6\n\n val delays = mutableListOf(TimeUnit.MILLISECONDS.toNanos(1000), -1L)\n queue.schedule(\"task\", TimeUnit.MILLISECONDS.toNanos(750)) {\n log.put(\"runOnce delays.size=${delays.size}\")\n return@schedule delays.removeAt(0)\n }\n\n assertThat(log.take()).isEqualTo(\"runOnce delays.size=2\")\n val t2 = System.nanoTime() / 1e6 - t1\n assertThat(t2).isCloseTo(750.0, 250.0)\n\n assertThat(log.take()).isEqualTo(\"runOnce delays.size=1\")\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerRealBackendTest.kt","line":59,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n backend.shutdown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerRealBackendTest.kt","line":63,"symbol":"test","kind":"function","lang":"kotlin","code":"@Test fun test() {\n val t1 = System.nanoTime() / 1e6\n\n val delays = mutableListOf(TimeUnit.MILLISECONDS.toNanos(1000), -1L)\n queue.schedule(\"task\", TimeUnit.MILLISECONDS.toNanos(750)) {\n log.put(\"runOnce delays.size=${delays.size}\")\n return@schedule delays.removeAt(0)\n }\n\n assertThat(log.take()).isEqualTo(\"runOnce delays.size=2\")\n val t2 = System.nanoTime() / 1e6 - t1\n assertThat(t2).isCloseTo(750.0, 250.0)\n\n assertThat(log.take()).isEqualTo(\"runOnce delays.size=1\")\n val t3 = System.nanoTime() / 1e6 - t1\n assertThat(t3).isCloseTo(1750.0, 250.0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerRealBackendTest.kt","line":81,"symbol":"taskFailsWithUncheckedException","kind":"function","lang":"kotlin","code":"@Test fun taskFailsWithUncheckedException() {\n queue.schedule(\"task\", TimeUnit.MILLISECONDS.toNanos(100)) {\n log.put(\"failing task running\")\n throw RuntimeException(\"boom!\")\n }\n\n queue.schedule(\"task\", TimeUnit.MILLISECONDS.toNanos(200)) {\n log.put(\"normal task running\")\n return@schedule -1L\n }\n\n queue.idleLatch().await(500, TimeUnit.MILLISECONDS)\n\n assertThat(log.take()).isEqualTo(\"failing task running\")\n assertThat(log.take()).isEqualTo(\"uncaught exception: java.lang.RuntimeException: boom!\")\n assertThat(log.take()).isEqualTo(\"normal task running\")\n assertThat(log).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerRealBackendTest.kt","line":100,"symbol":"idleLatchAfterShutdown","kind":"function","lang":"kotlin","code":"@Test fun idleLatchAfterShutdown() {\n queue.schedule(\"task\") {\n Thread.sleep(250)\n backend.shutdown()\n return@schedule -1L\n }\n\n assertThat(queue.idleLatch().await(500L, TimeUnit.MILLISECONDS)).isTrue()\n assertThat(queue.idleLatch().count).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":31,"symbol":"TaskRunnerTest","kind":"class","lang":"kotlin","code":"class TaskRunnerTest {\n private val taskFaker = TaskFaker()\n\n @RegisterExtension @JvmField\n val testLogHandler = TestLogHandler(taskFaker.logger)\n\n private val taskRunner = taskFaker.taskRunner\n private val log = mutableListOf()\n private val redQueue = taskRunner.newQueue()\n private val blueQueue = taskRunner.newQueue()\n private val greenQueue = taskRunner.newQueue()\n\n @AfterEach\n internal fun tearDown() {\n taskFaker.close()\n }\n\n @Test fun executeDelayed() {\n redQueue.execute(\"task\", 100.µs) {\n log += \"run@${taskFaker.nanoTime}\"\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).containsExactly()\n\n taskFaker.advanceUntil(99.µs)\n assertThat(log).containsExactly()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }\n\n @Test fun executeRepeated() {\n val delays = mutableListOf(50.µs, 150.µs, -1L)\n redQueue.schedule(\"task\", 100.µs) {\n log += \"ru"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":43,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n internal fun tearDown() {\n taskFaker.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":48,"symbol":"executeDelayed","kind":"function","lang":"kotlin","code":"@Test fun executeDelayed() {\n redQueue.execute(\"task\", 100.µs) {\n log += \"run@${taskFaker.nanoTime}\"\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).containsExactly()\n\n taskFaker.advanceUntil(99.µs)\n assertThat(log).containsExactly()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":71,"symbol":"executeRepeated","kind":"function","lang":"kotlin","code":"@Test fun executeRepeated() {\n val delays = mutableListOf(50.µs, 150.µs, -1L)\n redQueue.schedule(\"task\", 100.µs) {\n log += \"run@${taskFaker.nanoTime}\"\n return@schedule delays.removeAt(0)\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).containsExactly()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.advanceUntil(150.µs)\n assertThat(log).containsExactly(\"run@100000\", \"run@150000\")\n\n taskFaker.advanceUntil(299.µs)\n assertThat(log).containsExactly(\"run@100000\", \"run@150000\")\n\n taskFaker.advanceUntil(300.µs)\n assertThat(log).containsExactly(\"run@100000\", \"run@150000\", \"run@300000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n \"FINE: Q10000 run again after 50 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n \"FINE: Q10000 run again after 150 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q100"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":109,"symbol":"executeScheduledEarlierReplacesRepeatedLater","kind":"function","lang":"kotlin","doc":"Repeat with a delay of 200 but schedule with a delay of 50. The schedule wins.","code":"@Test fun executeScheduledEarlierReplacesRepeatedLater() {\n val task =\n object : Task(\"task\") {\n val schedules = mutableListOf(50.µs)\n val delays = mutableListOf(200.µs, -1)\n\n override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n if (schedules.isNotEmpty()) {\n redQueue.schedule(this, schedules.removeAt(0))\n }\n return delays.removeAt(0)\n }\n }\n redQueue.schedule(task, 100.µs)\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.advanceUntil(150.µs)\n assertThat(log).containsExactly(\"run@100000\", \"run@150000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 scheduled after 50 µs: task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n \"FINE: Q10000 already scheduled : task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":115,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n if (schedules.isNotEmpty()) {\n redQueue.schedule(this, schedules.removeAt(0))\n }\n return delays.removeAt(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":148,"symbol":"executeRepeatedEarlierReplacesScheduledLater","kind":"function","lang":"kotlin","doc":"Schedule with a delay of 200 but repeat with a delay of 50. The repeat wins.","code":"@Test fun executeRepeatedEarlierReplacesScheduledLater() {\n val task =\n object : Task(\"task\") {\n val schedules = mutableListOf(200.µs)\n val delays = mutableListOf(50.µs, -1L)\n\n override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n if (schedules.isNotEmpty()) {\n redQueue.schedule(this, schedules.removeAt(0))\n }\n return delays.removeAt(0)\n }\n }\n redQueue.schedule(task, 100.µs)\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.advanceUntil(150.µs)\n assertThat(log).containsExactly(\"run@100000\", \"run@150000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 scheduled after 200 µs: task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n \"FINE: Q10000 run again after 50 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":154,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n if (schedules.isNotEmpty()) {\n redQueue.schedule(this, schedules.removeAt(0))\n }\n return delays.removeAt(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":186,"symbol":"cancelReturnsTruePreventsNextExecution","kind":"function","lang":"kotlin","code":"@Test fun cancelReturnsTruePreventsNextExecution() {\n redQueue.execute(\"task\", 100.µs) {\n log += \"run@${taskFaker.nanoTime}\"\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n redQueue.cancelAll()\n\n taskFaker.advanceUntil(99.µs)\n assertThat(log).isEmpty()\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 canceled : task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":207,"symbol":"cancelReturnsFalseDoesNotCancel","kind":"function","lang":"kotlin","code":"@Test fun cancelReturnsFalseDoesNotCancel() {\n redQueue.schedule(\n object : Task(\"task\", cancelable = false) {\n override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n return -1L\n }\n },\n 100.µs,\n )\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n redQueue.cancelAll()\n\n taskFaker.advanceUntil(99.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":210,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n return -1L\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":238,"symbol":"cancelWhileExecutingPreventsRepeat","kind":"function","lang":"kotlin","code":"@Test fun cancelWhileExecutingPreventsRepeat() {\n redQueue.schedule(\"task\", 100.µs) {\n log += \"run@${taskFaker.nanoTime}\"\n redQueue.cancelAll()\n return@schedule 100.µs\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":260,"symbol":"cancelWhileExecutingDoesNothingIfTaskDoesNotRepeat","kind":"function","lang":"kotlin","code":"@Test fun cancelWhileExecutingDoesNothingIfTaskDoesNotRepeat() {\n redQueue.execute(\"task\", 100.µs) {\n log += \"run@${taskFaker.nanoTime}\"\n redQueue.cancelAll()\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":281,"symbol":"cancelWhileExecutingDoesNotStopUncancelableTask","kind":"function","lang":"kotlin","code":"@Test fun cancelWhileExecutingDoesNotStopUncancelableTask() {\n redQueue.schedule(\n object : Task(\"task\", cancelable = false) {\n val delays = mutableListOf(50.µs, -1L)\n\n override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n redQueue.cancelAll()\n return delays.removeAt(0)\n }\n },\n 100.µs,\n )\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.advanceUntil(150.µs)\n assertThat(log).containsExactly(\"run@100000\", \"run@150000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n \"FINE: Q10000 run again after 50 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":286,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n redQueue.cancelAll()\n return delays.removeAt(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":316,"symbol":"interruptingCoordinatorAttemptsToCancelsAndSucceeds","kind":"function","lang":"kotlin","code":"@Test fun interruptingCoordinatorAttemptsToCancelsAndSucceeds() {\n redQueue.execute(\"task\", 100.µs) {\n log += \"run@${taskFaker.nanoTime}\"\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.interruptCoordinatorThread()\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 canceled : task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":337,"symbol":"interruptingCoordinatorAttemptsToCancelsAndFails","kind":"function","lang":"kotlin","code":"@Test fun interruptingCoordinatorAttemptsToCancelsAndFails() {\n redQueue.schedule(\n object : Task(\"task\", cancelable = false) {\n override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n return -1L\n }\n },\n 100.µs,\n )\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.interruptCoordinatorThread()\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":340,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n return -1L\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":369,"symbol":"singleQueueIsSerial","kind":"function","lang":"kotlin","doc":"Inspect how many runnables have been enqueued. If none then we're truly sequential.","code":"@Test fun singleQueueIsSerial() {\n redQueue.execute(\"task one\", 100.µs) {\n log += \"one:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}\"\n }\n\n redQueue.execute(\"task two\", 100.µs) {\n log += \"two:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}\"\n }\n\n redQueue.execute(\"task three\", 100.µs) {\n log += \"three:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}\"\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\n \"one:run@100000 parallel=false\",\n \"two:run@100000 parallel=false\",\n \"three:run@100000 parallel=false\",\n )\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task one\",\n \"FINE: Q10000 scheduled after 100 µs: task two\",\n \"FINE: Q10000 scheduled after 100 µs: task three\",\n \"FINE: Q10000 starting : task one\",\n \"FINE: Q10000 finished run in 0 µs: task one\",\n \"FINE: Q10000 starting : task two\",\n \"FINE: Q10000 finished run in 0 µs: task two\",\n \"FINE: Q10000 starting "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":408,"symbol":"differentQueuesAreParallel","kind":"function","lang":"kotlin","doc":"Inspect how many runnables have been enqueued. If non-zero then we're truly parallel.","code":"@Test fun differentQueuesAreParallel() {\n redQueue.execute(\"task one\", 100.µs) {\n log += \"one:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}\"\n }\n\n blueQueue.execute(\"task two\", 100.µs) {\n log += \"two:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}\"\n }\n\n greenQueue.execute(\"task three\", 100.µs) {\n log += \"three:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}\"\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactlyInAnyOrder(\n \"one:run@100000 parallel=true\",\n \"two:run@100000 parallel=true\",\n \"three:run@100000 parallel=true\",\n )\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactlyInAnyOrder(\n \"FINE: Q10000 scheduled after 100 µs: task one\",\n \"FINE: Q10001 scheduled after 100 µs: task two\",\n \"FINE: Q10002 scheduled after 100 µs: task three\",\n \"FINE: Q10000 starting : task one\",\n \"FINE: Q10000 finished run in 0 µs: task one\",\n \"FINE: Q10001 starting : task two\",\n \"FINE: Q10001 finished run in 0 µs: task two\",\n \"FI"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":447,"symbol":"scheduledTasks","kind":"function","lang":"kotlin","doc":"Test the introspection method [TaskQueue.scheduledTasks].","code":"@Test fun scheduledTasks() {\n redQueue.execute(\"task one\", 100.µs) {\n // Do nothing.\n }\n\n redQueue.execute(\"task two\", 200.µs) {\n // Do nothing.\n }\n\n assertThat(redQueue.scheduledTasks.toString()).isEqualTo(\"[task one, task two]\")\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task one\",\n \"FINE: Q10000 scheduled after 200 µs: task two\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":468,"symbol":"scheduledTasksDoesNotIncludeRunningTask","kind":"function","lang":"kotlin","doc":"We don't track the active task in scheduled tasks. This behavior might be a mistake, but it's cumbersome to implement properly because the active task might be a cancel.","code":"@Test fun scheduledTasksDoesNotIncludeRunningTask() {\n val task =\n object : Task(\"task one\") {\n val schedules = mutableListOf(200.µs)\n\n override fun runOnce(): Long {\n if (schedules.isNotEmpty()) {\n redQueue.schedule(this, schedules.removeAt(0)) // Add it at the end also.\n }\n log += \"scheduledTasks=${redQueue.scheduledTasks}\"\n return -1L\n }\n }\n redQueue.schedule(task, 100.µs)\n\n redQueue.execute(\"task two\", 200.µs) {\n log += \"scheduledTasks=${redQueue.scheduledTasks}\"\n }\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\n \"scheduledTasks=[task two, task one]\",\n )\n\n taskFaker.advanceUntil(200.µs)\n assertThat(log).containsExactly(\n \"scheduledTasks=[task two, task one]\",\n \"scheduledTasks=[task one]\",\n )\n\n taskFaker.advanceUntil(300.µs)\n assertThat(log).containsExactly(\n \"scheduledTasks=[task two, task one]\",\n \"scheduledTasks=[task one]\",\n \"scheduledTasks=[]\",\n )\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task one\",\n \"FINE:"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":473,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n if (schedules.isNotEmpty()) {\n redQueue.schedule(this, schedules.removeAt(0)) // Add it at the end also.\n }\n log += \"scheduledTasks=${redQueue.scheduledTasks}\"\n return -1L\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":525,"symbol":"activeQueuesContainsOnlyQueuesWithScheduledTasks","kind":"function","lang":"kotlin","doc":"The runner doesn't hold references to its queues! Otherwise we'd need a mechanism to clean them up when they're no longer needed and that's annoying. Instead the task runner only tracks which queues have work scheduled.","code":"@Test fun activeQueuesContainsOnlyQueuesWithScheduledTasks() {\n redQueue.execute(\"task one\", 100.µs) {\n // Do nothing.\n }\n\n blueQueue.execute(\"task two\", 200.µs) {\n // Do nothing.\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(taskRunner.activeQueues()).containsExactly(redQueue, blueQueue)\n\n taskFaker.advanceUntil(100.µs)\n assertThat(taskRunner.activeQueues()).containsExactly(blueQueue)\n\n taskFaker.advanceUntil(200.µs)\n assertThat(taskRunner.activeQueues()).isEmpty()\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task one\",\n \"FINE: Q10001 scheduled after 200 µs: task two\",\n \"FINE: Q10000 starting : task one\",\n \"FINE: Q10000 finished run in 0 µs: task one\",\n \"FINE: Q10001 starting : task two\",\n \"FINE: Q10001 finished run in 0 µs: task two\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":555,"symbol":"taskNameIsUsedForThreadNameWhenRunning","kind":"function","lang":"kotlin","code":"@Test fun taskNameIsUsedForThreadNameWhenRunning() {\n redQueue.execute(\"lucky task\") {\n log += \"run threadName:${Thread.currentThread().name}\"\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).containsExactly(\"run threadName:lucky task\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 0 µs: lucky task\",\n \"FINE: Q10000 starting : lucky task\",\n \"FINE: Q10000 finished run in 0 µs: lucky task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":572,"symbol":"shutdownSuccessfullyCancelsScheduledTasks","kind":"function","lang":"kotlin","code":"@Test fun shutdownSuccessfullyCancelsScheduledTasks() {\n redQueue.execute(\"task\", 100.µs) {\n log += \"run@${taskFaker.nanoTime}\"\n }\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n redQueue.shutdown()\n\n taskFaker.advanceUntil(99.µs)\n assertThat(log).isEmpty()\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 canceled : task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":593,"symbol":"shutdownFailsToCancelsScheduledTasks","kind":"function","lang":"kotlin","code":"@Test fun shutdownFailsToCancelsScheduledTasks() {\n redQueue.schedule(\n object : Task(\"task\", false) {\n override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n return 50.µs\n }\n },\n 100.µs,\n )\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).isEmpty()\n\n redQueue.shutdown()\n\n taskFaker.advanceUntil(99.µs)\n assertThat(log).isEmpty()\n\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"run@100000\")\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 scheduled after 100 µs: task\",\n \"FINE: Q10000 starting : task\",\n \"FINE: Q10000 finished run in 0 µs: task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":596,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long {\n log += \"run@${taskFaker.nanoTime}\"\n return 50.µs\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":624,"symbol":"scheduleDiscardsTaskWhenShutdown","kind":"function","lang":"kotlin","code":"@Test fun scheduleDiscardsTaskWhenShutdown() {\n redQueue.shutdown()\n\n redQueue.execute(\"task\", 100.µs) {\n // Do nothing.\n }\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 schedule canceled (queue is shutdown): task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":638,"symbol":"scheduleThrowsWhenShutdown","kind":"function","lang":"kotlin","code":"@Test fun scheduleThrowsWhenShutdown() {\n redQueue.shutdown()\n\n assertFailsWith {\n redQueue.schedule(\n object : Task(\"task\", cancelable = false) {\n override fun runOnce(): Long = -1L\n },\n 100.µs,\n )\n }\n\n taskFaker.assertNoMoreTasks()\n\n assertThat(testLogHandler.takeAll()).containsExactly(\n \"FINE: Q10000 schedule failed (queue is shutdown): task\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":644,"symbol":"runOnce","kind":"function","lang":"kotlin","code":"override fun runOnce(): Long = -1L"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":657,"symbol":"idleLatch","kind":"function","lang":"kotlin","code":"@Test fun idleLatch() {\n redQueue.execute(\"task\") {\n log += \"run@${taskFaker.nanoTime}\"\n }\n\n val idleLatch = redQueue.idleLatch()\n assertThat(idleLatch.count).isEqualTo(1)\n\n taskFaker.advanceUntil(0.µs)\n assertThat(log).containsExactly(\"run@0\")\n\n assertThat(idleLatch.count).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":671,"symbol":"multipleCallsToIdleLatchReturnSameInstance","kind":"function","lang":"kotlin","code":"@Test fun multipleCallsToIdleLatchReturnSameInstance() {\n redQueue.execute(\"task\") {\n log += \"run@${taskFaker.nanoTime}\"\n }\n\n val idleLatch1 = redQueue.idleLatch()\n val idleLatch2 = redQueue.idleLatch()\n assertThat(idleLatch2).isSameInstanceAs(idleLatch1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":681,"symbol":"cancelAllWhenEmptyDoesNotStartWorkerThread","kind":"function","lang":"kotlin","code":"@Test fun cancelAllWhenEmptyDoesNotStartWorkerThread() {\n redQueue.execute(\"red task\", 100.µs) {\n error(\"expected to be canceled\")\n }\n assertThat(taskFaker.executeCallCount).isEqualTo(1)\n\n blueQueue.execute(\"task\", 100.µs) {\n error(\"expected to be canceled\")\n }\n assertThat(taskFaker.executeCallCount).isEqualTo(1)\n\n redQueue.cancelAll()\n assertThat(taskFaker.executeCallCount).isEqualTo(1)\n\n blueQueue.cancelAll()\n assertThat(taskFaker.executeCallCount).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":699,"symbol":"noMoreThanOneWorkerThreadWaitingToStartAtATime","kind":"function","lang":"kotlin","code":"@Test fun noMoreThanOneWorkerThreadWaitingToStartAtATime() {\n // Enqueueing the red task starts a thread because the head of the queue changed.\n redQueue.execute(\"red task\") {\n log += \"red:starting@${taskFaker.nanoTime}\"\n taskFaker.sleep(100.µs)\n log += \"red:finishing@${taskFaker.nanoTime}\"\n }\n assertThat(taskFaker.executeCallCount).isEqualTo(1)\n\n // Enqueueing the blue task doesn't start a thread because the red one is still starting.\n blueQueue.execute(\"blue task\") {\n log += \"blue:starting@${taskFaker.nanoTime}\"\n taskFaker.sleep(100.µs)\n log += \"blue:finishing@${taskFaker.nanoTime}\"\n }\n assertThat(taskFaker.executeCallCount).isEqualTo(1)\n\n // Running the red task starts another thread, so the two can run in parallel.\n taskFaker.runNextTask()\n assertThat(log).containsExactly(\"red:starting@0\")\n assertThat(taskFaker.executeCallCount).isEqualTo(2)\n\n // Next the blue task starts.\n taskFaker.runNextTask()\n assertThat(log).containsExactly(\n \"red:starting@0\",\n \"blue:starting@0\",\n )\n assertThat(taskFaker.executeCallCount).isEqualTo(2)\n\n // Advance time until the tasks complete.\n taskFaker.adva"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/concurrent/TaskRunnerTest.kt","line":741,"symbol":"onlyOneCoordinatorWaitingToStartFutureTasks","kind":"function","lang":"kotlin","code":"@Test fun onlyOneCoordinatorWaitingToStartFutureTasks() {\n // Enqueueing the red task starts a coordinator thread.\n redQueue.execute(\"red task\", 100.µs) {\n log += \"red:run@${taskFaker.nanoTime}\"\n }\n assertThat(taskFaker.executeCallCount).isEqualTo(1)\n\n // Enqueueing the blue task doesn't need a 2nd coordinator yet.\n blueQueue.execute(\"blue task\", 200.µs) {\n log += \"blue:run@${taskFaker.nanoTime}\"\n }\n assertThat(taskFaker.executeCallCount).isEqualTo(1)\n\n // Nothing to do.\n taskFaker.runTasks()\n assertThat(log).isEmpty()\n\n // At 100.µs, the coordinator runs the red task and starts a thread for the new coordinator.\n taskFaker.advanceUntil(100.µs)\n assertThat(log).containsExactly(\"red:run@100000\")\n assertThat(taskFaker.executeCallCount).isEqualTo(2)\n\n // At 200.µs, the blue task runs.\n taskFaker.advanceUntil(200.µs)\n assertThat(log).containsExactly(\"red:run@100000\", \"blue:run@200000\")\n assertThat(taskFaker.executeCallCount).isEqualTo(2)\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":36,"symbol":"ConnectionPoolTest","kind":"class","lang":"kotlin","code":"class ConnectionPoolTest {\n private val routePlanner = FakeRoutePlanner()\n private val factory = routePlanner.factory\n private val peer = MockHttp2Peer()\n\n /** The fake task runner prevents the cleanup runnable from being started. */\n private val addressA = factory.newAddress(\"a\")\n private val routeA1 = factory.newRoute(addressA)\n private val addressB = factory.newAddress(\"b\")\n private val routeB1 = factory.newRoute(addressB)\n private val addressC = factory.newAddress(\"c\")\n private val routeC1 = factory.newRoute(addressC)\n\n @AfterEach fun tearDown() {\n factory.close()\n peer.close()\n }\n\n @Test fun connectionsEvictedWhenIdleLongEnough() {\n val pool = factory.newConnectionPool()\n val c1 = factory.newConnection(pool, routeA1, 50L)\n\n // Running at time 50, the pool returns that nothing can be evicted until time 150.\n assertThat(pool.closeConnections(50L)).isEqualTo(100L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n assertThat(c1.socket().isClosed).isFalse()\n\n // Running at time 60, the pool returns that nothing can be evicted until time 150.\n assertThat(pool.closeConnections(60L)).isEqualTo(90L)\n assertThat(pool.connectionCount()).isEq"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":49,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n factory.close()\n peer.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":54,"symbol":"connectionsEvictedWhenIdleLongEnough","kind":"function","lang":"kotlin","code":"@Test fun connectionsEvictedWhenIdleLongEnough() {\n val pool = factory.newConnectionPool()\n val c1 = factory.newConnection(pool, routeA1, 50L)\n\n // Running at time 50, the pool returns that nothing can be evicted until time 150.\n assertThat(pool.closeConnections(50L)).isEqualTo(100L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n assertThat(c1.socket().isClosed).isFalse()\n\n // Running at time 60, the pool returns that nothing can be evicted until time 150.\n assertThat(pool.closeConnections(60L)).isEqualTo(90L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n assertThat(c1.socket().isClosed).isFalse()\n\n // Running at time 149, the pool returns that nothing can be evicted until time 150.\n assertThat(pool.closeConnections(149L)).isEqualTo(1L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n assertThat(c1.socket().isClosed).isFalse()\n\n // Running at time 150, the pool evicts.\n assertThat(pool.closeConnections(150L)).isEqualTo(0)\n assertThat(pool.connectionCount()).isEqualTo(0)\n assertThat(c1.socket().isClosed).isTrue()\n\n // Running again, the pool reports that no further runs are necessary.\n assertThat(pool.closeConnectio"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":84,"symbol":"inUseConnectionsNotEvicted","kind":"function","lang":"kotlin","code":"@Test fun inUseConnectionsNotEvicted() {\n val pool = factory.newConnectionPool()\n val poolApi = ConnectionPool(pool)\n val c1 = factory.newConnection(pool, routeA1, 50L)\n val client =\n OkHttpClient\n .Builder()\n .connectionPool(poolApi)\n .build()\n val call = client.newCall(Request(addressA.url)) as RealCall\n call.enterNetworkInterceptorExchange(call.request(), true, factory.newChain(call))\n c1.withLock { call.acquireConnectionNoEvents(c1) }\n\n // Running at time 50, the pool returns that nothing can be evicted until time 150.\n assertThat(pool.closeConnections(50L)).isEqualTo(100L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n assertThat(c1.socket().isClosed).isFalse()\n\n // Running at time 60, the pool returns that nothing can be evicted until time 160.\n assertThat(pool.closeConnections(60L)).isEqualTo(100L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n assertThat(c1.socket().isClosed).isFalse()\n\n // Running at time 160, the pool returns that nothing can be evicted until time 260.\n assertThat(pool.closeConnections(160L)).isEqualTo(100L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n assertThat"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":113,"symbol":"cleanupPrioritizesEarliestEviction","kind":"function","lang":"kotlin","code":"@Test fun cleanupPrioritizesEarliestEviction() {\n val pool = factory.newConnectionPool()\n val c1 = factory.newConnection(pool, routeA1, 75L)\n val c2 = factory.newConnection(pool, routeB1, 50L)\n\n // Running at time 75, the pool returns that nothing can be evicted until time 150.\n assertThat(pool.closeConnections(75L)).isEqualTo(75L)\n assertThat(pool.connectionCount()).isEqualTo(2)\n\n // Running at time 149, the pool returns that nothing can be evicted until time 150.\n assertThat(pool.closeConnections(149L)).isEqualTo(1L)\n assertThat(pool.connectionCount()).isEqualTo(2)\n\n // Running at time 150, the pool evicts c2.\n assertThat(pool.closeConnections(150L)).isEqualTo(0L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n assertThat(c1.socket().isClosed).isFalse()\n assertThat(c2.socket().isClosed).isTrue()\n\n // Running at time 150, the pool returns that nothing can be evicted until time 175.\n assertThat(pool.closeConnections(150L)).isEqualTo(25L)\n assertThat(pool.connectionCount()).isEqualTo(1)\n\n // Running at time 175, the pool evicts c1.\n assertThat(pool.closeConnections(175L)).isEqualTo(0L)\n assertThat(pool.connectionCount())."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":143,"symbol":"oldestConnectionsEvictedIfIdleLimitExceeded","kind":"function","lang":"kotlin","code":"@Test fun oldestConnectionsEvictedIfIdleLimitExceeded() {\n val pool =\n factory.newConnectionPool(\n maxIdleConnections = 2,\n )\n val c1 = factory.newConnection(pool, routeA1, 50L)\n val c2 = factory.newConnection(pool, routeB1, 75L)\n\n // With 2 connections, there's no need to evict until the connections time out.\n assertThat(pool.closeConnections(100L)).isEqualTo(50L)\n assertThat(pool.connectionCount()).isEqualTo(2)\n assertThat(c1.socket().isClosed).isFalse()\n assertThat(c2.socket().isClosed).isFalse()\n\n // Add a third connection\n val c3 = factory.newConnection(pool, routeC1, 75L)\n\n // The third connection bounces the first.\n assertThat(pool.closeConnections(100L)).isEqualTo(0L)\n assertThat(pool.connectionCount()).isEqualTo(2)\n assertThat(c1.socket().isClosed).isTrue()\n assertThat(c2.socket().isClosed).isFalse()\n assertThat(c3.socket().isClosed).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":168,"symbol":"leakedAllocation","kind":"function","lang":"kotlin","code":"@Test fun leakedAllocation() {\n val pool = factory.newConnectionPool()\n val poolApi = ConnectionPool(pool)\n val c1 = factory.newConnection(pool, routeA1, 0L)\n allocateAndLeakAllocation(poolApi, c1)\n awaitGarbageCollection()\n assertThat(pool.closeConnections(100L)).isEqualTo(0L)\n assertThat(c1.calls).isEmpty()\n\n // Can't allocate once a leak has been detected.\n assertThat(c1.noNewExchanges).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":181,"symbol":"interruptStopsThread","kind":"function","lang":"kotlin","code":"@Test fun interruptStopsThread() {\n val taskRunnerThreads = mutableListOf()\n val taskRunner =\n TaskRunner(\n RealBackend { runnable ->\n Thread(runnable, \"interruptStopsThread TaskRunner\")\n .also { taskRunnerThreads += it }\n },\n )\n\n val pool =\n factory.newConnectionPool(\n taskRunner = taskRunner,\n maxIdleConnections = 2,\n )\n factory.newConnection(pool, routeA1)\n // Racy causing flaky tests\n // assertThat(taskRunner.activeQueues()).isNotEmpty()\n assertThat(taskRunnerThreads).isNotEmpty()\n Thread.sleep(100)\n for (t in taskRunnerThreads) {\n t.interrupt()\n }\n Thread.sleep(100)\n assertThat(taskRunner.activeQueues()).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/ConnectionPoolTest.kt","line":209,"symbol":"allocateAndLeakAllocation","kind":"function","lang":"kotlin","doc":"Use a helper method so there's no hidden reference remaining on the stack.","code":"private fun allocateAndLeakAllocation(\n pool: ConnectionPool,\n connection: RealConnection,\n ) {\n val client =\n OkHttpClient\n .Builder()\n .connectionPool(pool)\n .build()\n val call = client.newCall(Request(connection.route().address.url)) as RealCall\n call.enterNetworkInterceptorExchange(call.request(), true, factory.newChain(call))\n connection.withLock { call.acquireConnectionNoEvents(connection) }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":41,"symbol":"FastFallbackExchangeFinderTest","kind":"class","lang":"kotlin","doc":"the same structure: * prepare a set of plans, each with a predictable connect delay * attempt to find a connection * step through time, asserting that the expected side effects are performed.","code":"internal class FastFallbackExchangeFinderTest {\n private val taskFaker = TaskFaker()\n private val taskRunner = taskFaker.taskRunner\n\n /**\n * Note that we don't use the same [TaskFaker] for this factory. That way off-topic tasks like\n * connection pool maintenance tasks don't add noise to route planning tests.\n */\n private val routePlanner = FakeRoutePlanner(taskFaker = taskFaker)\n private val finder = FastFallbackExchangeFinder(routePlanner, taskRunner)\n\n @AfterEach\n fun tearDown() {\n taskFaker.close()\n routePlanner.close()\n }\n\n @Test\n fun takeConnectedConnection() {\n val plan0 = routePlanner.addPlan()\n plan0.connectState = TLS_CONNECTED\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan0.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n )\n\n taskFaker.assertNoMoreTasks()\n }\n\n @Test\n fun takeConnectingConnection() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 240.ms\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan0.connection)\n }\n\n task"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":52,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n taskFaker.close()\n routePlanner.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":58,"symbol":"takeConnectedConnection","kind":"function","lang":"kotlin","code":"@Test\n fun takeConnectedConnection() {\n val plan0 = routePlanner.addPlan()\n plan0.connectState = TLS_CONNECTED\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan0.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":76,"symbol":"takeConnectingConnection","kind":"function","lang":"kotlin","code":"@Test\n fun takeConnectingConnection() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 240.ms\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan0.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(240.ms)\n assertEvents(\n \"plan 0 TCP connected\",\n \"plan 0 TLS connecting...\",\n \"plan 0 TLS connected\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":100,"symbol":"firstPlanConnectedBeforeSecondPlan","kind":"function","lang":"kotlin","code":"@Test\n fun firstPlanConnectedBeforeSecondPlan() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 260.ms\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectDelayNanos = 20.ms // Connect at time = 270 ms.\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan0.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(260.ms)\n assertEvents(\n \"plan 0 TCP connected\",\n \"plan 1 cancel\",\n \"plan 0 TLS connecting...\",\n \"plan 0 TLS connected\",\n )\n\n taskFaker.advanceUntil(270.ms)\n assertEvents(\n \"plan 1 TCP connect canceled\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":138,"symbol":"secondPlanAlreadyConnected","kind":"function","lang":"kotlin","code":"@Test\n fun secondPlanAlreadyConnected() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 260.ms\n val plan1 = routePlanner.addPlan()\n plan1.connectState = TLS_CONNECTED\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan1.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 0 cancel\",\n )\n\n taskFaker.advanceUntil(260.ms)\n assertEvents(\n \"plan 0 TCP connect canceled\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":168,"symbol":"secondPlanConnectedBeforeFirstPlan","kind":"function","lang":"kotlin","code":"@Test\n fun secondPlanConnectedBeforeFirstPlan() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 270.ms\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectDelayNanos = 10.ms // Connect at time = 260 ms.\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan1.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(260.ms)\n assertEvents(\n \"plan 1 TCP connected\",\n \"plan 0 cancel\",\n \"plan 1 TLS connecting...\",\n \"plan 1 TLS connected\",\n )\n\n taskFaker.advanceUntil(270.ms)\n assertEvents(\n \"plan 0 TCP connect canceled\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":206,"symbol":"thirdPlanAlreadyConnected","kind":"function","lang":"kotlin","code":"@Test\n fun thirdPlanAlreadyConnected() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 520.ms\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectDelayNanos = 260.ms // Connect completes at 510 ms.\n val plan2 = routePlanner.addPlan()\n plan2.connectState = TLS_CONNECTED\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan2.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(500.ms)\n assertEvents(\n \"take plan 2\",\n \"plan 0 cancel\",\n \"plan 1 cancel\",\n )\n\n taskFaker.advanceUntil(510.ms)\n assertEvents(\n \"plan 1 TCP connect canceled\",\n )\n\n taskFaker.advanceUntil(520.ms)\n assertEvents(\n \"plan 0 TCP connect canceled\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":250,"symbol":"takeMultipleConnections","kind":"function","lang":"kotlin","code":"@Test\n fun takeMultipleConnections() {\n val plan0 = routePlanner.addPlan()\n plan0.connectState = TLS_CONNECTED\n val plan1 = routePlanner.addPlan()\n plan1.connectState = TLS_CONNECTED\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan0.connection)\n val result1 = finder.find()\n assertThat(result1).isEqualTo(plan1.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"take plan 1\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":273,"symbol":"takeMultipleConnectionsReturnsRaceLoser","kind":"function","lang":"kotlin","code":"@Test\n fun takeMultipleConnectionsReturnsRaceLoser() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 270.ms\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectDelayNanos = 10.ms // Connect at time = 260 ms.\n val plan2 = plan0.createRetry()\n plan2.tcpConnectDelayNanos = 20.ms // Connect at time = 280 ms.\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan1.connection)\n val result1 = finder.find()\n assertThat(result1).isEqualTo(plan2.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(260.ms)\n assertEvents(\n \"plan 1 TCP connected\",\n \"plan 0 cancel\",\n \"plan 1 TLS connecting...\",\n \"plan 1 TLS connected\",\n \"plan 2 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(270.ms)\n assertEvents(\n \"plan 0 TCP connect canceled\",\n )\n\n taskFaker.advanceUntil(280.ms)\n assertEvents(\n \"plan 2 TCP connected\",\n \"plan "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":325,"symbol":"firstConnectionFailsAndNoOthersExist","kind":"function","lang":"kotlin","code":"@Test\n fun firstConnectionFailsAndNoOthersExist() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectThrowable = IOException(\"boom!\")\n\n taskRunner.newQueue().execute(\"connect\") {\n assertFailsWith {\n finder.find()\n }.also { expected ->\n assertThat(expected).hasMessage(\"boom!\")\n }\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n \"plan 0 TCP connect failed\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":348,"symbol":"firstConnectionFailsToConnectAndSecondSucceeds","kind":"function","lang":"kotlin","code":"@Test\n fun firstConnectionFailsToConnectAndSecondSucceeds() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectThrowable = IOException(\"boom!\")\n val plan1 = routePlanner.addPlan()\n plan1.connectState = TLS_CONNECTED\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan1.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n \"plan 0 TCP connect failed\",\n \"take plan 1\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":371,"symbol":"firstConnectionFailsToConnectAndSecondFailureIsSuppressedException","kind":"function","lang":"kotlin","code":"@Test\n fun firstConnectionFailsToConnectAndSecondFailureIsSuppressedException() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectThrowable = IOException(\"boom 0!\")\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectThrowable = IOException(\"boom 1!\")\n\n taskRunner.newQueue().execute(\"connect\") {\n assertFailsWith {\n finder.find()\n }.also { expected ->\n assertThat(expected).hasMessage(\"boom 0!\")\n assertThat(expected.suppressed.single()).hasMessage(\"boom 1!\")\n }\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n \"plan 0 TCP connect failed\",\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n \"plan 1 TCP connect failed\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":400,"symbol":"firstConnectionCrashesWithUncheckedException","kind":"function","lang":"kotlin","code":"@Test\n fun firstConnectionCrashesWithUncheckedException() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectThrowable = IllegalStateException(\"boom!\")\n routePlanner.addPlan() // This plan should not be used.\n\n taskRunner.newQueue().execute(\"connect\") {\n assertFailsWith {\n finder.find()\n }.also { expected ->\n assertThat(expected).hasMessage(\"boom!\")\n }\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n \"plan 0 TCP connect failed\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":424,"symbol":"routePlannerPlanThrowsOnOnlyPlan","kind":"function","lang":"kotlin","code":"@Test\n fun routePlannerPlanThrowsOnOnlyPlan() {\n val plan0 = routePlanner.addPlan()\n plan0.planningThrowable = UnknownServiceException(\"boom!\")\n\n taskRunner.newQueue().execute(\"connect\") {\n assertFailsWith {\n finder.find()\n }.also { expected ->\n assertThat(expected).hasMessage(\"boom!\")\n }\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":445,"symbol":"recoversAfterFirstPlanCallThrows","kind":"function","lang":"kotlin","code":"@Test\n fun recoversAfterFirstPlanCallThrows() {\n val plan0 = routePlanner.addPlan()\n plan0.planningThrowable = UnknownServiceException(\"boom!\")\n val plan1 = routePlanner.addPlan()\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan1.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n \"plan 1 TCP connected\",\n \"plan 1 TLS connecting...\",\n \"plan 1 TLS connected\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":469,"symbol":"retryConnectionThatLostTcpRaceAfterWinnersTlsFails","kind":"function","lang":"kotlin","code":"@Test\n fun retryConnectionThatLostTcpRaceAfterWinnersTlsFails() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 270.ms\n\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectDelayNanos = 10.ms // TCP connect at time = 260 ms.\n plan1.tlsConnectThrowable = IOException(\"boom!\")\n\n val plan2 = plan0.createRetry()\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan2.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(260.ms)\n assertEvents(\n \"plan 1 TCP connected\",\n \"plan 0 cancel\",\n \"plan 1 TLS connecting...\",\n \"plan 1 TLS connect failed\",\n \"plan 2 TCP connecting...\",\n \"plan 2 TCP connected\",\n \"plan 2 TLS connecting...\",\n \"plan 2 TLS connected\",\n )\n\n taskFaker.advanceUntil(270.ms)\n assertEvents(\n \"plan 0 TCP connect canceled\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":517,"symbol":"losingPlanDoesNotConnectTls","kind":"function","lang":"kotlin","code":"@Test\n fun losingPlanDoesNotConnectTls() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 270.ms\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectDelayNanos = 10.ms // Connect at time = 260 ms.\n plan1.tlsConnectDelayNanos = 20.ms // Connect at time = 280 ms.\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan0.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(260.ms)\n assertEvents(\n \"plan 1 TCP connected\",\n \"plan 0 cancel\",\n \"plan 1 TLS connecting...\",\n )\n\n taskFaker.advanceUntil(270.ms)\n assertEvents(\n \"plan 0 TCP connect canceled\",\n )\n\n taskFaker.advanceUntil(280.ms)\n assertEvents(\n \"plan 1 TLS connected\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":562,"symbol":"tcpConnectFollowUpPlanUsed","kind":"function","lang":"kotlin","code":"@Test\n fun tcpConnectFollowUpPlanUsed() {\n val plan0 = routePlanner.addPlan()\n val plan1 = plan0.createConnectTcpNextPlan()\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan1.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n \"plan 0 needs follow-up\",\n \"plan 1 TCP connecting...\",\n \"plan 1 TCP connected\",\n \"plan 1 TLS connecting...\",\n \"plan 1 TLS connected\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":586,"symbol":"tlsConnectFollowUpPlanUsed","kind":"function","lang":"kotlin","code":"@Test\n fun tlsConnectFollowUpPlanUsed() {\n val plan0 = routePlanner.addPlan()\n val plan1 = plan0.createConnectTlsNextPlan()\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan1.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n \"plan 0 TCP connected\",\n \"plan 0 TLS connecting...\",\n \"plan 0 needs follow-up\",\n \"plan 1 TCP connecting...\",\n \"plan 1 TCP connected\",\n \"plan 1 TLS connecting...\",\n \"plan 1 TLS connected\",\n )\n\n taskFaker.assertNoMoreTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":625,"symbol":"tcpConnectionsRaceAfterTlsFails","kind":"function","lang":"kotlin","doc":"We get plan2 as a follow-up to plan1, typically retry the same IP but different TLS. We get plan3 as a retry of plan0, which was canceled when it lost the race. This test confirms that we prefer to do the TLS follow-up (plan2) before the TCP retry (plan3). It also confirms we enforce the 250 ms delay in each race.","code":"@Test\n fun tcpConnectionsRaceAfterTlsFails() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 280.ms\n\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectDelayNanos = 10.ms // Connect at time = 260 ms.\n plan1.tlsConnectDelayNanos = 10.ms // Connect at time = 270 ms.\n plan1.tlsConnectThrowable = IOException(\"boom!\")\n\n val plan2 = plan1.createConnectTlsNextPlan()\n plan2.tcpConnectDelayNanos = 270.ms // Connect at time = 540 ms.\n\n val plan3 = plan0.createRetry()\n plan3.tcpConnectDelayNanos = 10.ms // Connect at time = 530 ms.\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan3.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(260.ms)\n assertEvents(\n \"plan 1 TCP connected\",\n \"plan 0 cancel\",\n \"plan 1 TLS connecting...\",\n )\n\n taskFaker.advanceUntil(270.ms)\n assertEvents(\n \"plan 1 TLS connect failed\",\n \"plan 2 TCP conn"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":704,"symbol":"minimumDelayEnforcedBetweenConnects","kind":"function","lang":"kotlin","doc":"This test puts several connections in flight that all fail at approximately the same time. It confirms the fast fallback implements these invariants: * if there's no TCP connect in flight, start one. * don't start a new TCP connect within 250 ms of the previous TCP connect.","code":"@Test\n fun minimumDelayEnforcedBetweenConnects() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 510.ms\n plan0.tcpConnectThrowable = IOException(\"boom!\")\n val plan1 = routePlanner.addPlan()\n plan1.tcpConnectDelayNanos = 270.ms // Connect fail at time = 520 ms.\n plan1.tcpConnectThrowable = IOException(\"boom!\")\n val plan2 = routePlanner.addPlan()\n plan2.tcpConnectDelayNanos = 30.ms // Connect fail at time = 530 ms.\n plan2.tcpConnectThrowable = IOException(\"boom!\")\n val plan3 = routePlanner.addPlan()\n plan3.tcpConnectDelayNanos = 270.ms // Connect at time 800 ms.\n val plan4 = routePlanner.addPlan()\n plan4.tcpConnectDelayNanos = 10.ms // Connect at time 790 ms.\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan4.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 1 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(500.ms)\n assertEvents(\n \"take plan 2\",\n \"plan 2 TCP connecting...\",\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":796,"symbol":"reusePlanAndNewConnectRace","kind":"function","lang":"kotlin","doc":"1. take plan 0 3. plan 0 connects 4. finish taking plan 1 https://github.com/lysine-dev/okhttp/issues/7152","code":"@Test\n fun reusePlanAndNewConnectRace() {\n val plan0 = routePlanner.addPlan()\n plan0.tcpConnectDelayNanos = 250.ms\n plan0.yieldBeforeTcpConnectReturns = true // Yield so we get a chance to take plan1...\n val plan1 = routePlanner.addPlan()\n plan1.connectState = TLS_CONNECTED\n plan1.yieldBeforePlanReturns = true // ... but let plan 0 connect before we act upon it.\n\n taskRunner.newQueue().execute(\"connect\") {\n val result0 = finder.find()\n assertThat(result0).isEqualTo(plan0.connection)\n }\n\n taskFaker.runTasks()\n assertEvents(\n \"take plan 0\",\n \"plan 0 TCP connecting...\",\n )\n\n taskFaker.advanceUntil(250.ms)\n assertEvents(\n \"take plan 1\",\n \"plan 0 cancel\",\n \"plan 0 TCP connect canceled\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/FastFallbackExchangeFinderTest.kt","line":824,"symbol":"assertEvents","kind":"function","lang":"kotlin","code":"private fun assertEvents(vararg expected: String) {\n val actual = generateSequence { routePlanner.events.poll() }.toList()\n assertThat(actual).containsExactly(*expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/InetAddressOrderTest.kt","line":29,"symbol":"InetAddressOrderTest","kind":"class","lang":"kotlin","code":"@Suppress(\"ktlint:standard:property-naming\")\nclass InetAddressOrderTest {\n private val factory = TestValueFactory()\n\n private val ipv4_10_0_0_6 = route(Inet4Address.getByName(\"10.0.0.6\"))\n private val ipv4_10_0_0_1 = route(Inet4Address.getByName(\"10.0.0.1\"))\n private val ipv4_10_0_0_4 = route(Inet4Address.getByName(\"10.0.0.4\"))\n private val ipv6_ab = route(Inet6Address.getByName(\"::ac\"))\n private val ipv6_fc = route(Inet6Address.getByName(\"::fc\"))\n\n @Test\n fun prioritiseIpv6Example() {\n val result =\n reorderForHappyEyeballs(\n listOf(\n ipv4_10_0_0_6,\n ipv4_10_0_0_1,\n ipv4_10_0_0_4,\n ipv6_ab,\n ipv6_fc,\n ),\n )\n\n assertThat(result).isEqualTo(\n listOf(ipv6_ab, ipv4_10_0_0_6, ipv6_fc, ipv4_10_0_0_1, ipv4_10_0_0_4),\n )\n }\n\n @Test\n fun ipv6Only() {\n val result = reorderForHappyEyeballs(listOf(ipv6_ab, ipv6_fc))\n\n assertThat(result).isEqualTo(\n listOf(ipv6_ab, ipv6_fc),\n )\n }\n\n @Test\n fun ipv4Only() {\n val result =\n reorderForHappyEyeballs(\n listOf(\n ipv4_10_0_0_6,\n ipv4_10_0_0_1,\n ipv4_10_0_0_4,\n ),\n )\n\n assertThat(result).i"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/InetAddressOrderTest.kt","line":39,"symbol":"prioritiseIpv6Example","kind":"function","lang":"kotlin","code":"@Test\n fun prioritiseIpv6Example() {\n val result =\n reorderForHappyEyeballs(\n listOf(\n ipv4_10_0_0_6,\n ipv4_10_0_0_1,\n ipv4_10_0_0_4,\n ipv6_ab,\n ipv6_fc,\n ),\n )\n\n assertThat(result).isEqualTo(\n listOf(ipv6_ab, ipv4_10_0_0_6, ipv6_fc, ipv4_10_0_0_1, ipv4_10_0_0_4),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/InetAddressOrderTest.kt","line":57,"symbol":"ipv6Only","kind":"function","lang":"kotlin","code":"@Test\n fun ipv6Only() {\n val result = reorderForHappyEyeballs(listOf(ipv6_ab, ipv6_fc))\n\n assertThat(result).isEqualTo(\n listOf(ipv6_ab, ipv6_fc),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/InetAddressOrderTest.kt","line":66,"symbol":"ipv4Only","kind":"function","lang":"kotlin","code":"@Test\n fun ipv4Only() {\n val result =\n reorderForHappyEyeballs(\n listOf(\n ipv4_10_0_0_6,\n ipv4_10_0_0_1,\n ipv4_10_0_0_4,\n ),\n )\n\n assertThat(result).isEqualTo(\n listOf(ipv4_10_0_0_6, ipv4_10_0_0_1, ipv4_10_0_0_4),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/InetAddressOrderTest.kt","line":82,"symbol":"singleIpv6","kind":"function","lang":"kotlin","code":"@Test\n fun singleIpv6() {\n val result = reorderForHappyEyeballs(listOf(ipv6_ab))\n\n assertThat(result).isEqualTo(\n listOf(ipv6_ab),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/InetAddressOrderTest.kt","line":91,"symbol":"singleIpv4","kind":"function","lang":"kotlin","code":"@Test\n fun singleIpv4() {\n val result = reorderForHappyEyeballs(listOf(ipv4_10_0_0_6))\n\n assertThat(result).isEqualTo(\n listOf(ipv4_10_0_0_6),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/InetAddressOrderTest.kt","line":100,"symbol":"prioritiseIpv6","kind":"function","lang":"kotlin","code":"@Test\n fun prioritiseIpv6() {\n val result = reorderForHappyEyeballs(listOf(ipv4_10_0_0_6, ipv6_ab))\n\n assertThat(result).isEqualTo(\n listOf(ipv6_ab, ipv4_10_0_0_6),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/InetAddressOrderTest.kt","line":109,"symbol":"route","kind":"function","lang":"kotlin","code":"private fun route(inetAddress: InetAddress): Route =\n factory.newRoute(\n socketAddress = InetSocketAddress(inetAddress, 443),\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":52,"symbol":"RetryConnectionTest","kind":"class","lang":"kotlin","code":"class RetryConnectionTest {\n private val factory = TestValueFactory()\n private val handshakeCertificates = localhost()\n private val retryableException = SSLHandshakeException(\"Simulated handshake exception\")\n private val echRetryException = SSLHandshakeException(\"ECH Mismatch with updated config\")\n private val echDisabledException = SSLHandshakeException(\"ECH Mismatch without config\")\n private val echRetryPlan =\n EchRetryPlan.getOrNull(\n publicName = \"public.tls-ech.dev\",\n configList = \"retry config\".encodeUtf8(),\n )!!\n private val echDisabledPlan =\n EchRetryPlan.getOrNull(\n publicName = \"public.tls-ech.dev\",\n configList = null,\n )!!\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @RegisterExtension\n val platform =\n PlatformRule(\n platform =\n object : Platform() {\n override fun echRetryPlan(exception: SSLException): EchRetryPlan? =\n when {\n exception === echRetryException -> echRetryPlan\n exception === echDisabledException -> echDisabledPlan\n else -> null\n }\n },\n )\n\n private var client = clientTestRule.newClient()\n\n @AfterEa"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":77,"symbol":"echRetryPlan","kind":"function","lang":"kotlin","code":"override fun echRetryPlan(exception: SSLException): EchRetryPlan? =\n when {\n exception === echRetryException -> echRetryPlan\n exception === echDisabledException -> echDisabledPlan\n else -> null\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":88,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach internal fun tearDown() {\n factory.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":92,"symbol":"nonRetryableIOException","kind":"function","lang":"kotlin","code":"@Test fun nonRetryableIOException() {\n val exception = IOException(\"Non-handshake exception\")\n assertThat(attemptAnotherConnectionSpec(exception)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":97,"symbol":"nonRetryableSSLHandshakeException","kind":"function","lang":"kotlin","code":"@Test fun nonRetryableSSLHandshakeException() {\n val exception =\n SSLHandshakeException(\"Certificate handshake exception\").apply {\n initCause(CertificateException())\n }\n assertThat(attemptAnotherConnectionSpec(exception)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":105,"symbol":"retryableSSLHandshakeException","kind":"function","lang":"kotlin","code":"@Test fun retryableSSLHandshakeException() {\n assertThat(attemptAnotherConnectionSpec(retryableException)).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":109,"symbol":"echRetryConfigIsUsedOnceWithoutTlsFallback","kind":"function","lang":"kotlin","code":"@Test fun echRetryConfigIsUsedOnceWithoutTlsFallback() {\n val address = newEchAddress()\n val routePlanner = factory.newRoutePlanner(client, address)\n val route = factory.newRoute(address)\n val connectionSpecs = listOf(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)\n val socket = createEchSocket()\n val attempt0 =\n routePlanner\n .planConnectToRoute(route)\n .planWithCurrentOrInitialConnectionSpec(connectionSpecs, socket)\n\n val attempt1 = attempt0.nextConnectionSpec(connectionSpecs, socket, echRetryException)\n\n assertThat(attempt1).isNotNull()\n assertThat(attempt1!!.route.echConfigList).isEqualTo(echRetryPlan.configList)\n assertThat(attempt1.isTlsFallback).isFalse()\n assertThat(verifiedHostnames).isEqualTo(listOf(echRetryPlan.publicName))\n\n verifiedHostnames.clear()\n val attempt2 = attempt1.nextConnectionSpec(connectionSpecs, socket, retryableException)\n assertThat(attempt2).isNull()\n // An ordinary handshake failure doesn't verify a public hostname.\n assertThat(verifiedHostnames).isEmpty()\n socket.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":136,"symbol":"echRetryUsesOnlyAddressesFromOriginalDnsResults","kind":"function","lang":"kotlin","doc":"https://www.rfc-editor.org/rfc/rfc9849.html#section-6.1.6","code":"@Test fun echRetryUsesOnlyAddressesFromOriginalDnsResults() {\n val dns = FakeDns()\n val hostname = \"stale.tls-ech.dev\"\n val originalAddresses = dns.allocate(2)\n val newAddress = dns.allocate(1).single()\n factory.dns = dns\n factory.uriHost = hostname\n dns[hostname] =\n listOf(\n ResourceRecord.Https(\n name = hostname,\n timeToLive = 5,\n echConfigList = \"stale config\".encodeUtf8(),\n ),\n *originalAddresses\n .map {\n ResourceRecord.IpAddress(\n name = hostname,\n timeToLive = 5,\n address = it,\n )\n }.toTypedArray(),\n )\n val address = newEchAddress()\n val routePlanner = factory.newRoutePlanner(client, address)\n val connectionSpecs = listOf(ConnectionSpec.MODERN_TLS)\n val socket = createEchSocket()\n val attempt0 =\n routePlanner\n .planConnect()\n .planWithCurrentOrInitialConnectionSpec(connectionSpecs, socket)\n\n // A new DNS result must not influence a retry of the previous ECH configuration.\n dns[hostname] = listOf(newAddress)\n val attempt1 = attempt0.nextConnectionSpec(connectionSpecs, socket, ech"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":180,"symbol":"untrustedEchRetryConfigIsNotRetried","kind":"function","lang":"kotlin","code":"@Test fun untrustedEchRetryConfigIsNotRetried() {\n val address = newEchAddress(verified = false)\n val routePlanner = factory.newRoutePlanner(client, address)\n val route = factory.newRoute(address)\n val connectionSpecs = listOf(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)\n val socket = createEchSocket()\n val attempt0 =\n routePlanner\n .planConnectToRoute(route)\n .planWithCurrentOrInitialConnectionSpec(connectionSpecs, socket)\n\n // not retried because validation failed\n val e =\n assertFailsWith {\n attempt0.nextConnectionSpec(connectionSpecs, socket, echRetryException)\n }\n assertThat(e).hasMessage(\"public_name 'public.tls-ech.dev' not verified\")\n\n assertThat(verifiedHostnames).isEqualTo(listOf(echRetryPlan.publicName))\n socket.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":207,"symbol":"missingEchRetryConfigIsRetriedWithout","kind":"function","lang":"kotlin","doc":"A server that offers no retry config has securely disabled ECH, so we retry without it. https://www.rfc-editor.org/rfc/rfc9849.html#section-6.1.6","code":"@Test fun missingEchRetryConfigIsRetriedWithout() {\n val address = newEchAddress()\n val routePlanner = factory.newRoutePlanner(client, address)\n val route = factory.newRoute(address).withEchConfigList(\"stale config\".encodeUtf8())\n val connectionSpecs = listOf(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)\n val socket = createEchSocket()\n val attempt0 =\n routePlanner\n .planConnectToRoute(route)\n .planWithCurrentOrInitialConnectionSpec(connectionSpecs, socket)\n\n val attempt1 = attempt0.nextConnectionSpec(connectionSpecs, socket, echDisabledException)\n\n assertThat(attempt1).isNotNull()\n assertThat(attempt1!!.route.echConfigList).isNull()\n assertThat(attempt1.isTlsFallback).isFalse()\n assertThat(verifiedHostnames).isEqualTo(listOf(echDisabledPlan.publicName))\n\n // Having disabled ECH once, we don't do it again.\n verifiedHostnames.clear()\n val attempt2 = attempt1.nextConnectionSpec(connectionSpecs, socket, echDisabledException)\n assertThat(attempt2).isNull()\n assertThat(verifiedHostnames).isEmpty()\n socket.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":239,"symbol":"echRetryConfigIsRetriedOnceOnly","kind":"function","lang":"kotlin","doc":"A retry config in response to a retry config signals a misconfigured server, but the server may still securely disable ECH. https://www.rfc-editor.org/rfc/rfc9849.html#section-6.1.6","code":"@Test fun echRetryConfigIsRetriedOnceOnly() {\n val address = factory.newHttpsAddress(hostnameVerifier = { _, _ -> true })\n val routePlanner = factory.newRoutePlanner(client, address)\n val route = factory.newRoute(address).withEchConfigList(\"stale config\".encodeUtf8())\n val connectionSpecs = listOf(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS)\n val socket = createEchSocket()\n val attempt0 =\n routePlanner\n .planConnectToRoute(route)\n .planWithCurrentOrInitialConnectionSpec(connectionSpecs, socket)\n\n val attempt1 = attempt0.nextConnectionSpec(connectionSpecs, socket, echRetryException)\n assertThat(attempt1).isNotNull()\n assertThat(attempt1!!.route.echConfigList).isEqualTo(echRetryPlan.configList)\n\n // At most two attempts are made.\n assertThat(attempt1.nextConnectionSpec(connectionSpecs, socket, echRetryException)).isNull()\n assertThat(attempt1.nextConnectionSpec(connectionSpecs, socket, echDisabledException)).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":259,"symbol":"someFallbacksSupported","kind":"function","lang":"kotlin","code":"@Test fun someFallbacksSupported() {\n val sslV3 =\n ConnectionSpec\n .Builder(ConnectionSpec.MODERN_TLS)\n .tlsVersions(TlsVersion.SSL_3_0)\n .build()\n val routePlanner = factory.newRoutePlanner(client)\n val route = factory.newRoute()\n val connectionSpecs = listOf(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS, sslV3)\n val enabledSocketTlsVersions =\n arrayOf(\n TlsVersion.TLS_1_2,\n TlsVersion.TLS_1_1,\n TlsVersion.TLS_1_0,\n )\n var socket = createSocketWithEnabledProtocols(*enabledSocketTlsVersions)\n\n // MODERN_TLS is used here.\n val attempt0 =\n routePlanner\n .planConnectToRoute(route)\n .planWithCurrentOrInitialConnectionSpec(connectionSpecs, socket)\n assertThat(attempt0.isTlsFallback).isFalse()\n connectionSpecs[attempt0.connectionSpecIndex].apply(socket, attempt0.isTlsFallback)\n assertEnabledProtocols(socket, TlsVersion.TLS_1_2)\n val attempt1 = attempt0.nextConnectionSpec(connectionSpecs, socket, retryableException)\n assertThat(attempt1).isNotNull()\n assertThat(attempt1!!.isTlsFallback).isTrue()\n socket.close()\n\n // COMPATIBLE_TLS is used here.\n socket "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":310,"symbol":"newEchAddress","kind":"function","lang":"kotlin","code":"private fun newEchAddress(verified: Boolean = true) =\n factory.newHttpsAddress(\n hostnameVerifier = { hostname, _ ->\n verifiedHostnames += hostname\n verified\n },\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":323,"symbol":"createEchSocket","kind":"function","lang":"kotlin","doc":"ECH is only carried by TLS 1.3, so every ECH attempt needs it enabled. https://www.rfc-editor.org/rfc/rfc9849.html#section-1","code":"private fun createEchSocket(): SSLSocket = createSocketWithEnabledProtocols(TlsVersion.TLS_1_3, TlsVersion.TLS_1_2)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":325,"symbol":"createSocketWithEnabledProtocols","kind":"function","lang":"kotlin","code":"private fun createSocketWithEnabledProtocols(vararg tlsVersions: TlsVersion): SSLSocket =\n (handshakeCertificates.sslSocketFactory().createSocket() as SSLSocket).apply {\n enabledProtocols = javaNames(*tlsVersions)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":330,"symbol":"withEchConfigList","kind":"function","lang":"kotlin","code":"private fun Route.withEchConfigList(echConfigList: ByteString): Route =\n Route(\n address = address,\n proxy = proxy,\n socketAddress = socketAddress,\n echConfigList = echConfigList,\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":338,"symbol":"assertEnabledProtocols","kind":"function","lang":"kotlin","code":"private fun assertEnabledProtocols(\n socket: SSLSocket,\n vararg required: TlsVersion,\n ) {\n assertThat(socket.enabledProtocols.toList()).containsExactlyInAnyOrder(*javaNames(*required))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RetryConnectionTest.kt","line":345,"symbol":"javaNames","kind":"function","lang":"kotlin","code":"private fun javaNames(vararg tlsVersions: TlsVersion) = tlsVersions.map { it.javaName }.toTypedArray()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":55,"symbol":"RouteSelectorTest","kind":"class","lang":"kotlin","code":"@Burst\nclass RouteSelectorTest(\n private val entryPoint: EntryPoint = EntryPoint.Lookup,\n) {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private val dns = FakeDns()\n private val proxySelector = RecordingProxySelector()\n private val uriHost = \"hosta\"\n private val uriPort = 1003\n private val echConfigList = \"this is an encrypted client hello\".encodeUtf8()\n private val factory =\n TestValueFactory().apply {\n this.dns = this@RouteSelectorTest.dns.forceEntryPoint(entryPoint)\n this.proxySelector = this@RouteSelectorTest.proxySelector\n this.uriHost = this@RouteSelectorTest.uriHost\n this.uriPort = this@RouteSelectorTest.uriPort\n }\n\n private lateinit var call: RealCall\n private val routeDatabase = RouteDatabase()\n\n @BeforeEach fun setUp() {\n call =\n clientTestRule.newClient().newCall(\n Request\n .Builder()\n .url(\"https://$uriHost:$uriPort/\")\n .build(),\n ) as RealCall\n }\n\n @AfterEach fun tearDown() {\n factory.close()\n }\n\n @Test fun singleRoute() {\n val address = factory.newAddress()\n val routeSelector = newRouteSelector(a"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":81,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach fun setUp() {\n call =\n clientTestRule.newClient().newCall(\n Request\n .Builder()\n .url(\"https://$uriHost:$uriPort/\")\n .build(),\n ) as RealCall\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":91,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n factory.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":95,"symbol":"singleRoute","kind":"function","lang":"kotlin","code":"@Test fun singleRoute() {\n val address = factory.newAddress()\n val routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[uriHost] = dns.allocate(1)\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][0], uriPort)\n dns.assertRequests(uriHost)\n assertThat(selection.hasNext()).isFalse()\n assertFailsWith {\n selection.next()\n }\n assertThat(routeSelector.hasNext()).isFalse()\n assertFailsWith {\n routeSelector.next()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":113,"symbol":"routeReturnsEncryptedClientHelloData","kind":"function","lang":"kotlin","code":"@Test fun routeReturnsEncryptedClientHelloData() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n val address = factory.newAddress()\n val routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[uriHost] =\n listOf(\n ResourceRecord.IpAddress(\n name = uriHost,\n timeToLive = 5,\n address = dns.allocate(1).single(),\n ),\n ResourceRecord.Https(\n name = uriHost,\n timeToLive = 5,\n echConfigList = echConfigList,\n ),\n )\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][0], uriPort, echConfigList)\n dns.assertRequests(uriHost)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":138,"symbol":"echAddressesDoNotFallBackToNonEch","kind":"function","lang":"kotlin","doc":"https://www.rfc-editor.org/rfc/rfc9848.html#section-5.1","code":"@Test fun echAddressesDoNotFallBackToNonEch() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n val echAddress = dns.allocate(1).single()\n val nonEchAddress = dns.allocate(1).single()\n dns[uriHost] =\n listOf(\n ResourceRecord.Https(\n name = uriHost,\n timeToLive = 5,\n targetName = \"ech.$uriHost\",\n echConfigList = echConfigList,\n ),\n ResourceRecord.IpAddress(\n name = \"ech.$uriHost\",\n timeToLive = 5,\n address = echAddress,\n ),\n ResourceRecord.IpAddress(\n name = \"non-ech.$uriHost\",\n timeToLive = 5,\n address = nonEchAddress,\n ),\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":174,"symbol":"singleRouteReturnsFailedRoute","kind":"function","lang":"kotlin","code":"@Test fun singleRouteReturnsFailedRoute() {\n val address = factory.newAddress()\n var routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[uriHost] = dns.allocate(1)\n var selection = routeSelector.next()\n val route = selection.next()\n routeDatabase.failed(route)\n routeSelector = newRouteSelector(address)\n selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][0], uriPort)\n assertThat(selection.hasNext()).isFalse()\n assertFailsWith {\n selection.next()\n }\n assertThat(routeSelector.hasNext()).isFalse()\n assertFailsWith {\n routeSelector.next()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":195,"symbol":"explicitProxyTriesThatProxysAddressesOnly","kind":"function","lang":"kotlin","code":"@Test fun explicitProxyTriesThatProxysAddressesOnly() {\n val address =\n factory.newAddress(\n proxy = proxyA,\n )\n val routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[PROXY_A_HOST] = dns.allocate(2)\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, proxyA, dns[PROXY_A_HOST][0], PROXY_A_PORT)\n assertRoute(selection.next(), address, proxyA, dns[PROXY_A_HOST][1], PROXY_A_PORT)\n assertThat(selection.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n dns.assertRequests(PROXY_A_HOST)\n proxySelector.assertRequests() // No proxy selector requests!\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":212,"symbol":"explicitDirectProxy","kind":"function","lang":"kotlin","code":"@Test fun explicitDirectProxy() {\n val address =\n factory.newAddress(\n proxy = Proxy.NO_PROXY,\n )\n val routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[uriHost] = dns.allocate(2)\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][0], uriPort)\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][1], uriPort)\n assertThat(selection.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n dns.assertRequests(uriHost)\n proxySelector.assertRequests() // No proxy selector requests!\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":233,"symbol":"proxySelectorNotCalledForNullHost","kind":"function","lang":"kotlin","doc":"Don't call through to the proxy selector if we don't have a host name. https://github.com/lysine-dev/okhttp/issues/5770","code":"@Test fun proxySelectorNotCalledForNullHost() {\n // The string '>' is okay in a hostname in HttpUrl, which does very light hostname validation.\n // It is not okay in URI, and so it's stripped and we get a URI with a null host.\n val bogusHostname = \">\"\n val address =\n factory.newAddress(\n uriHost = bogusHostname,\n uriPort = uriPort,\n )\n val routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[bogusHostname] = dns.allocate(1)\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[bogusHostname][0], uriPort)\n assertThat(selection.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n dns.assertRequests(bogusHostname)\n proxySelector.assertRequests() // No proxy selector requests!\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":253,"symbol":"proxySelectorReturnsNull","kind":"function","lang":"kotlin","code":"@Test fun proxySelectorReturnsNull() {\n val nullProxySelector: ProxySelector =\n object : ProxySelector() {\n override fun select(uri: URI): List? {\n assertThat(uri.host).isEqualTo(uriHost)\n return null\n }\n\n override fun connectFailed(\n uri: URI,\n socketAddress: SocketAddress,\n e: IOException,\n ): Unit = throw AssertionError()\n }\n\n val address =\n factory.newAddress(\n proxySelector = nullProxySelector,\n )\n val routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[uriHost] = dns.allocate(1)\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][0], uriPort)\n dns.assertRequests(uriHost)\n assertThat(selection.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":256,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI): List? {\n assertThat(uri.host).isEqualTo(uriHost)\n return null\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":261,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI,\n socketAddress: SocketAddress,\n e: IOException,\n ): Unit = throw AssertionError()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":282,"symbol":"proxySelectorThrowingIllegalArgumentExceptionFallsBackToDirect","kind":"function","lang":"kotlin","code":"@Test fun proxySelectorThrowingIllegalArgumentExceptionFallsBackToDirect() {\n val brokenProxySelector: ProxySelector =\n object : ProxySelector() {\n override fun select(uri: URI): List? {\n // A system proxy with an unset port makes the platform ProxySelector throw this.\n throw IllegalArgumentException(\"port out of range:-1\")\n }\n\n override fun connectFailed(\n uri: URI,\n socketAddress: SocketAddress,\n e: IOException,\n ): Unit = throw AssertionError()\n }\n\n val address =\n factory.newAddress(\n proxySelector = brokenProxySelector,\n )\n val routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[uriHost] = dns.allocate(1)\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][0], uriPort)\n dns.assertRequests(uriHost)\n assertThat(selection.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":285,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI): List? {\n // A system proxy with an unset port makes the platform ProxySelector throw this.\n throw IllegalArgumentException(\"port out of range:-1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":290,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI,\n socketAddress: SocketAddress,\n e: IOException,\n ): Unit = throw AssertionError()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":311,"symbol":"proxySelectorReturnsNoProxies","kind":"function","lang":"kotlin","code":"@Test fun proxySelectorReturnsNoProxies() {\n val address = factory.newAddress()\n val routeSelector = newRouteSelector(address)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[uriHost] = dns.allocate(2)\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][0], uriPort)\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][1], uriPort)\n assertThat(selection.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n dns.assertRequests(uriHost)\n proxySelector.assertRequests(address.url.toUri())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":325,"symbol":"proxySelectorReturnsMultipleProxies","kind":"function","lang":"kotlin","code":"@Test fun proxySelectorReturnsMultipleProxies() {\n val address = factory.newAddress()\n proxySelector.proxies.add(proxyA)\n proxySelector.proxies.add(proxyB)\n val routeSelector = newRouteSelector(address)\n proxySelector.assertRequests(address.url.toUri())\n\n // First try the IP addresses of the first proxy, in sequence.\n assertThat(routeSelector.hasNext()).isTrue()\n dns[PROXY_A_HOST] = dns.allocate(2)\n val selection1 = routeSelector.next()\n assertRoute(selection1.next(), address, proxyA, dns[PROXY_A_HOST][0], PROXY_A_PORT)\n assertRoute(selection1.next(), address, proxyA, dns[PROXY_A_HOST][1], PROXY_A_PORT)\n dns.assertRequests(PROXY_A_HOST)\n assertThat(selection1.hasNext()).isFalse()\n\n // Next try the IP address of the second proxy.\n assertThat(routeSelector.hasNext()).isTrue()\n dns[PROXY_B_HOST] = dns.allocate(1)\n val selection2 = routeSelector.next()\n assertRoute(selection2.next(), address, proxyB, dns[PROXY_B_HOST][0], PROXY_B_PORT)\n dns.assertRequests(PROXY_B_HOST)\n assertThat(selection2.hasNext()).isFalse()\n\n // No more proxies to try.\n assertThat(routeSelector.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":353,"symbol":"proxySelectorDirectConnectionsAreSkipped","kind":"function","lang":"kotlin","code":"@Test fun proxySelectorDirectConnectionsAreSkipped() {\n val address = factory.newAddress()\n proxySelector.proxies.add(Proxy.NO_PROXY)\n val routeSelector = newRouteSelector(address)\n proxySelector.assertRequests(address.url.toUri())\n\n // Only the origin server will be attempted.\n assertThat(routeSelector.hasNext()).isTrue()\n dns[uriHost] = dns.allocate(1)\n val selection = routeSelector.next()\n assertRoute(selection.next(), address, Proxy.NO_PROXY, dns[uriHost][0], uriPort)\n dns.assertRequests(uriHost)\n assertThat(selection.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":369,"symbol":"proxyDnsFailureContinuesToNextProxy","kind":"function","lang":"kotlin","code":"@Test fun proxyDnsFailureContinuesToNextProxy() {\n val address = factory.newAddress()\n proxySelector.proxies.add(proxyA)\n proxySelector.proxies.add(proxyB)\n proxySelector.proxies.add(proxyA)\n val routeSelector = newRouteSelector(address)\n proxySelector.assertRequests(address.url.toUri())\n assertThat(routeSelector.hasNext()).isTrue()\n dns[PROXY_A_HOST] = dns.allocate(1)\n val selection1 = routeSelector.next()\n assertRoute(selection1.next(), address, proxyA, dns[PROXY_A_HOST][0], PROXY_A_PORT)\n dns.assertRequests(PROXY_A_HOST)\n assertThat(selection1.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isTrue()\n dns.clear(PROXY_B_HOST)\n assertFailsWith {\n routeSelector.next()\n }\n dns.assertRequests(PROXY_B_HOST)\n assertThat(routeSelector.hasNext()).isTrue()\n dns[PROXY_A_HOST] = dns.allocate(1)\n val selection2 = routeSelector.next()\n assertRoute(selection2.next(), address, proxyA, dns[PROXY_A_HOST][0], PROXY_A_PORT)\n dns.assertRequests(PROXY_A_HOST)\n assertThat(selection2.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":397,"symbol":"multipleProxiesMultipleInetAddressesMultipleConfigurations","kind":"function","lang":"kotlin","code":"@Test fun multipleProxiesMultipleInetAddressesMultipleConfigurations() {\n val address = factory.newHttpsAddress()\n proxySelector.proxies.add(proxyA)\n proxySelector.proxies.add(proxyB)\n val routeSelector = newRouteSelector(address)\n\n // Proxy A\n dns[PROXY_A_HOST] = dns.allocate(2)\n val selection1 = routeSelector.next()\n assertRoute(selection1.next(), address, proxyA, dns[PROXY_A_HOST][0], PROXY_A_PORT)\n dns.assertRequests(PROXY_A_HOST)\n assertRoute(selection1.next(), address, proxyA, dns[PROXY_A_HOST][1], PROXY_A_PORT)\n assertThat(selection1.hasNext()).isFalse()\n\n // Proxy B\n dns[PROXY_B_HOST] = dns.allocate(2)\n val selection2 = routeSelector.next()\n assertRoute(selection2.next(), address, proxyB, dns[PROXY_B_HOST][0], PROXY_B_PORT)\n dns.assertRequests(PROXY_B_HOST)\n assertRoute(selection2.next(), address, proxyB, dns[PROXY_B_HOST][1], PROXY_B_PORT)\n assertThat(selection2.hasNext()).isFalse()\n\n // No more proxies to attempt.\n assertThat(routeSelector.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":423,"symbol":"failedRouteWithSingleProxy","kind":"function","lang":"kotlin","code":"@Test fun failedRouteWithSingleProxy() {\n val address = factory.newHttpsAddress()\n var routeSelector = newRouteSelector(address)\n val numberOfAddresses = 2\n dns[uriHost] = dns.allocate(numberOfAddresses)\n\n // Extract the regular sequence of routes from selector.\n val selection1 = routeSelector.next()\n val regularRoutes = selection1.routes\n\n // Check that we do indeed have more than one route.\n assertThat(regularRoutes.size).isEqualTo(numberOfAddresses)\n // Add first regular route as failed.\n routeDatabase.failed(regularRoutes[0])\n // Reset selector\n routeSelector = newRouteSelector(address)\n\n // The first selection prioritizes the non-failed routes.\n val selection2 = routeSelector.next()\n assertThat(selection2.next()).isEqualTo(regularRoutes[1])\n assertThat(selection2.hasNext()).isFalse()\n\n // The second selection will contain all failed routes.\n val selection3 = routeSelector.next()\n assertThat(selection3.next()).isEqualTo(regularRoutes[0])\n assertThat(selection3.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":452,"symbol":"failedRouteWithMultipleProxies","kind":"function","lang":"kotlin","code":"@Test fun failedRouteWithMultipleProxies() {\n val address = factory.newHttpsAddress()\n proxySelector.proxies.add(proxyA)\n proxySelector.proxies.add(proxyB)\n var routeSelector = newRouteSelector(address)\n dns[PROXY_A_HOST] = dns.allocate(1)\n dns[PROXY_B_HOST] = dns.allocate(1)\n\n // Mark the ProxyA route as failed.\n val selection = routeSelector.next()\n dns.assertRequests(PROXY_A_HOST)\n val route = selection.next()\n assertRoute(route, address, proxyA, dns[PROXY_A_HOST][0], PROXY_A_PORT)\n routeDatabase.failed(route)\n routeSelector = newRouteSelector(address)\n\n // Confirm we enumerate both proxies, giving preference to the route from ProxyB.\n val selection2 = routeSelector.next()\n dns.assertRequests(PROXY_A_HOST, PROXY_B_HOST)\n assertRoute(selection2.next(), address, proxyB, dns[PROXY_B_HOST][0], PROXY_B_PORT)\n assertThat(selection2.hasNext()).isFalse()\n\n // Confirm the last selection contains the postponed route from ProxyA.\n val selection3 = routeSelector.next()\n dns.assertRequests()\n assertRoute(selection3.next(), address, proxyA, dns[PROXY_A_HOST][0], PROXY_A_PORT)\n assertThat(selection3.hasNext()).isFalse()\n a"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":482,"symbol":"queryForAllSelectedRoutes","kind":"function","lang":"kotlin","code":"@Test fun queryForAllSelectedRoutes() {\n val address = factory.newAddress()\n val routeSelector = newRouteSelector(address)\n dns[uriHost] = dns.allocate(2)\n val selection = routeSelector.next()\n dns.assertRequests(uriHost)\n val routes = selection.routes\n assertRoute(routes[0], address, Proxy.NO_PROXY, dns[uriHost][0], uriPort)\n assertRoute(routes[1], address, Proxy.NO_PROXY, dns[uriHost][1], uriPort)\n assertThat(selection.next()).isSameInstanceAs(routes[0])\n assertThat(selection.next()).isSameInstanceAs(routes[1])\n assertThat(selection.hasNext()).isFalse()\n assertThat(routeSelector.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":497,"symbol":"addressesNotSortedWhenFastFallbackIsOff","kind":"function","lang":"kotlin","code":"@Test fun addressesNotSortedWhenFastFallbackIsOff() {\n val address =\n factory.newAddress(\n proxy = Proxy.NO_PROXY,\n )\n val routeSelector =\n newRouteSelector(\n address = address,\n fastFallback = false,\n )\n assertThat(routeSelector.hasNext()).isTrue()\n val (ipv6_1, ipv6_2) = dns.allocateIpv6(2)\n val (ipv4_1, ipv4_2) = dns.allocate(2)\n dns[uriHost] = listOf(ipv6_1, ipv6_2, ipv4_1, ipv4_2)\n\n val selection = routeSelector.next()\n assertThat(selection.routes.map { it.socketAddress.address }).containsExactly(\n ipv6_1,\n ipv6_2,\n ipv4_1,\n ipv4_2,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":521,"symbol":"addressesSortedWhenFastFallbackIsOn","kind":"function","lang":"kotlin","code":"@Test fun addressesSortedWhenFastFallbackIsOn() {\n val address =\n factory.newAddress(\n proxy = Proxy.NO_PROXY,\n )\n val routeSelector =\n newRouteSelector(\n address = address,\n fastFallback = true,\n )\n assertThat(routeSelector.hasNext()).isTrue()\n val (ipv6_1, ipv6_2) = dns.allocateIpv6(2)\n val (ipv4_1, ipv4_2) = dns.allocate(2)\n dns[uriHost] = listOf(ipv6_1, ipv6_2, ipv4_1, ipv4_2)\n\n val selection = routeSelector.next()\n assertThat(selection.routes.map { it.socketAddress.address }).containsExactly(\n ipv6_1,\n ipv4_1,\n ipv6_2,\n ipv4_2,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":545,"symbol":"getHostString","kind":"function","lang":"kotlin","code":"@Test fun getHostString() {\n // Name proxy specification.\n var socketAddress = InetSocketAddress.createUnresolved(\"host\", 1234)\n assertThat(socketAddress.socketHost).isEqualTo(\"host\")\n socketAddress = InetSocketAddress.createUnresolved(\"127.0.0.1\", 1234)\n assertThat(socketAddress.socketHost).isEqualTo(\"127.0.0.1\")\n\n // InetAddress proxy specification.\n socketAddress = InetSocketAddress(InetAddress.getByName(\"localhost\"), 1234)\n assertThat(socketAddress.socketHost).isEqualTo(\"127.0.0.1\")\n socketAddress = InetSocketAddress(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)), 1234)\n assertThat(socketAddress.socketHost).isEqualTo(\"127.0.0.1\")\n socketAddress =\n InetSocketAddress(\n InetAddress.getByAddress(\"foobar\", byteArrayOf(127, 0, 0, 1)),\n 1234,\n )\n assertThat(socketAddress.socketHost).isEqualTo(\"127.0.0.1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":565,"symbol":"routeToString","kind":"function","lang":"kotlin","code":"@Test fun routeToString() {\n val ipv4Address =\n InetAddress.getByAddress(\n byteArrayOf(1, 2, 3, 4),\n )\n assertThat(\n Route(\n factory.newAddress(uriHost = \"1.2.3.4\", uriPort = 1003),\n Proxy.NO_PROXY,\n InetSocketAddress(ipv4Address, 1003),\n ).toString(),\n ).isEqualTo(\"1.2.3.4:1003\")\n assertThat(\n Route(\n factory.newAddress(uriHost = \"example.com\", uriPort = 1003),\n Proxy.NO_PROXY,\n InetSocketAddress(ipv4Address, 1003),\n ).toString(),\n ).isEqualTo(\"example.com at 1.2.3.4:1003\")\n assertThat(\n Route(\n factory.newAddress(uriHost = \"example.com\", uriPort = 1003),\n Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(\"proxy.example.com\", 1003)),\n InetSocketAddress(ipv4Address, 1003),\n ).toString(),\n ).isEqualTo(\"example.com via proxy 1.2.3.4:1003\")\n assertThat(\n Route(\n factory.newAddress(uriHost = \"example.com\", uriPort = 1003),\n Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(\"proxy.example.com\", 1003)),\n InetSocketAddress(ipv4Address, 5678),\n ).toString(),\n ).isEqualTo(\"example.com:1003 via proxy 1.2.3.4:56"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":608,"symbol":"routeToStringIpv6","kind":"function","lang":"kotlin","code":"@Test fun routeToStringIpv6() {\n val ipv6Address =\n InetAddress.getByAddress(\n byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),\n )\n assertThat(\n Route(\n factory.newAddress(uriHost = \"::1\", uriPort = 1003),\n Proxy.NO_PROXY,\n InetSocketAddress(ipv6Address, uriPort),\n ).toString(),\n ).isEqualTo(\"[::1]:1003\")\n assertThat(\n Route(\n factory.newAddress(uriHost = \"example.com\", uriPort = 1003),\n Proxy.NO_PROXY,\n InetSocketAddress(ipv6Address, uriPort),\n ).toString(),\n ).isEqualTo(\"example.com at [::1]:1003\")\n assertThat(\n Route(\n factory.newAddress(uriHost = \"example.com\", uriPort = 1003),\n Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(\"proxy.example.com\", 1003)),\n InetSocketAddress(ipv6Address, 5678),\n ).toString(),\n ).isEqualTo(\"example.com:1003 via proxy [::1]:5678\")\n assertThat(\n Route(\n factory.newAddress(uriHost = \"::2\", uriPort = 1003),\n Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(\"proxy.example.com\", 1003)),\n InetSocketAddress(ipv6Address, 5678),\n ).toString(),\n ).isEqualTo(\"[::2"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":643,"symbol":"assertRoute","kind":"function","lang":"kotlin","code":"private fun assertRoute(\n route: Route,\n address: Address,\n proxy: Proxy,\n socketAddress: InetAddress,\n socketPort: Int,\n echConfigList: ByteString? = null,\n ) {\n assertThat(route.address).isEqualTo(address)\n assertThat(route.proxy).isEqualTo(proxy)\n assertThat(route.socketAddress.address).isEqualTo(socketAddress)\n assertThat(route.socketAddress.port).isEqualTo(socketPort)\n assertThat(route.echConfigList).isEqualTo(echConfigList)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/connection/RouteSelectorTest.kt","line":658,"symbol":"newRouteSelector","kind":"function","lang":"kotlin","code":"private fun newRouteSelector(\n address: Address,\n routeDatabase: RouteDatabase = this.routeDatabase,\n fastFallback: Boolean = false,\n call: RealCall = this.call,\n ): RouteSelector =\n RouteSelector(\n address = address,\n routeDatabase = routeDatabase,\n fastFallback = fastFallback,\n call = call,\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":70,"symbol":"CancelTest","kind":"class","lang":"kotlin","code":"@Timeout(30)\n@Tag(\"Slow\")\n@Burst\nclass CancelTest(\n private val cancelMode: CancelMode = INTERRUPT,\n private val connectionType: ConnectionType = H2,\n) {\n @JvmField @RegisterExtension\n val platform = PlatformRule()\n\n private var threadToCancel: Thread? = null\n\n enum class CancelMode {\n CANCEL,\n INTERRUPT,\n }\n\n enum class ConnectionType {\n H2,\n HTTPS,\n HTTP,\n }\n\n @JvmField @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n val handshakeCertificates = platform.localhostHandshakeCertificates()\n\n private lateinit var server: MockWebServer\n private lateinit var client: OkHttpClient\n\n val eventRecorder = EventRecorder()\n\n @BeforeEach\n fun setUp() {\n if (connectionType == H2) {\n platform.assumeHttp2Support()\n }\n\n // Sockets on some platforms can have large buffers that mean writes do not block when\n // required. These socket factories explicitly set the buffer sizes on sockets created.\n server = MockWebServer()\n server.serverSocketFactory =\n object : DelegatingServerSocketFactory(Platform.get().serverSocketFactory) {\n @Throws(IOException::class)\n override fun configureServerSocket(serverSocket: Server"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":82,"symbol":"CancelMode","kind":"enum","lang":"kotlin","code":"enum class CancelMode {\n CANCEL,\n INTERRUPT,\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":83,"symbol":"CANCEL","kind":"enum_member","lang":"kotlin","code":"CANCEL"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":84,"symbol":"INTERRUPT","kind":"enum_member","lang":"kotlin","code":"INTERRUPT"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":87,"symbol":"ConnectionType","kind":"enum","lang":"kotlin","code":"enum class ConnectionType {\n H2,\n HTTPS,\n HTTP,\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":88,"symbol":"H2","kind":"enum_member","lang":"kotlin","code":"H2"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":89,"symbol":"HTTPS","kind":"enum_member","lang":"kotlin","code":"HTTPS"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":90,"symbol":"HTTP","kind":"enum_member","lang":"kotlin","code":"HTTP"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":103,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n if (connectionType == H2) {\n platform.assumeHttp2Support()\n }\n\n // Sockets on some platforms can have large buffers that mean writes do not block when\n // required. These socket factories explicitly set the buffer sizes on sockets created.\n server = MockWebServer()\n server.serverSocketFactory =\n object : DelegatingServerSocketFactory(Platform.get().serverSocketFactory) {\n @Throws(IOException::class)\n override fun configureServerSocket(serverSocket: ServerSocket): ServerSocket {\n serverSocket.receiveBufferSize = SOCKET_BUFFER_SIZE\n return serverSocket\n }\n }\n if (connectionType != HTTP) {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n }\n server.start()\n\n client =\n clientTestRule\n .newClientBuilder()\n .socketFactory(\n object : DelegatingSocketFactory(Platform.get().socketFactory) {\n @Throws(IOException::class)\n override fun configureSocket(socket: Socket): Socket {\n socket.sendBufferSize = SOCKET_BUFFER_SIZE\n socket.receiveBufferSize = SOCKET_BUFFER_SIZE\n return socket"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":114,"symbol":"configureServerSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun configureServerSocket(serverSocket: ServerSocket): ServerSocket {\n serverSocket.receiveBufferSize = SOCKET_BUFFER_SIZE\n return serverSocket\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":130,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun configureSocket(socket: Socket): Socket {\n socket.sendBufferSize = SOCKET_BUFFER_SIZE\n socket.receiveBufferSize = SOCKET_BUFFER_SIZE\n return socket\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":149,"symbol":"cancelWritingRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun cancelWritingRequestBody() {\n server.enqueue(MockResponse())\n val call =\n client.newCall(\n Request(\n url = server.url(\"/\"),\n body =\n object : RequestBody() {\n override fun contentType(): MediaType? = null\n\n @Throws(\n IOException::class,\n )\n override fun writeTo(sink: BufferedSink) {\n for (i in 0..9) {\n sink.writeByte(0)\n sink.flush()\n sleep(100)\n }\n fail(\"Expected connection to be closed\")\n }\n },\n ),\n )\n cancelLater(call, 500)\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertEquals(cancelMode == INTERRUPT, Thread.interrupted())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":158,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":160,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(\n IOException::class,\n )\n override fun writeTo(sink: BufferedSink) {\n for (i in 0..9) {\n sink.writeByte(0)\n sink.flush()\n sleep(100)\n }\n fail(\"Expected connection to be closed\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":182,"symbol":"cancelReadingResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun cancelReadingResponseBody() {\n val responseBodySize = 8 * 1024 * 1024 // 8 MiB.\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n Buffer()\n .write(ByteArray(responseBodySize)),\n ).throttleBody(64 * 1024, 125, MILLISECONDS) // 500 Kbps\n .build(),\n )\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n cancelLater(call, 500)\n val responseBody = response.body.byteStream()\n val buffer = ByteArray(1024)\n assertFailsWith {\n while (responseBody.read(buffer) != -1) {\n }\n }.also { expected ->\n assertEquals(cancelMode == INTERRUPT, Thread.interrupted())\n }\n responseBody.close()\n assertEquals(if (connectionType == H2) 1 else 0, client.connectionPool.connectionCount())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":209,"symbol":"cancelAndFollowup","kind":"function","lang":"kotlin","code":"@Test\n fun cancelAndFollowup() {\n val responseBodySize = 8 * 1024 * 1024 // 8 MiB.\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n Buffer()\n .write(ByteArray(responseBodySize)),\n ).throttleBody(64 * 1024, 125, MILLISECONDS) // 500 Kbps\n .build(),\n )\n server.enqueue(MockResponse(body = \".\"))\n\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n val response = call.execute()\n val cancelLatch = cancelLater(call, 500)\n val responseBody = response.body.byteStream()\n val buffer = ByteArray(1024)\n assertFailsWith {\n while (responseBody.read(buffer) != -1) {\n }\n }.also { expected ->\n assertEquals(cancelMode == INTERRUPT, Thread.interrupted())\n }\n responseBody.close()\n assertEquals(if (connectionType == H2) 1 else 0, client.connectionPool.connectionCount())\n\n cancelLatch.await()\n\n val events = eventRecorder.eventSequence.filter { isConnectionEvent(it) }.map { it.name }\n eventRecorder.clearAllEvents()\n\n assertThat(events).startsWith(\"CallStart\", \"ConnectStart\", \"ConnectEnd\", \"ConnectionAcquired\")\n if (cancelMode == CANCEL) {\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":269,"symbol":"isConnectionEvent","kind":"function","lang":"kotlin","code":"private fun isConnectionEvent(it: CallEvent?) =\n it is CallStart ||\n it is CallEnd ||\n it is ConnectStart ||\n it is ConnectEnd ||\n it is ConnectionAcquired ||\n it is ConnectionReleased ||\n it is Canceled ||\n it is RequestFailed ||\n it is ResponseFailed"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":280,"symbol":"sleep","kind":"function","lang":"kotlin","code":"private fun sleep(delayMillis: Int) {\n try {\n Thread.sleep(delayMillis.toLong())\n } catch (e: InterruptedException) {\n Thread.currentThread().interrupt()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":288,"symbol":"cancelLater","kind":"function","lang":"kotlin","code":"private fun cancelLater(\n call: Call,\n delayMillis: Int,\n ): CountDownLatch {\n val latch = CountDownLatch(1)\n Thread {\n sleep(delayMillis)\n if (cancelMode == CANCEL) {\n call.cancel()\n } else {\n threadToCancel!!.interrupt()\n }\n latch.countDown()\n }.apply { start() }\n return latch\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":311,"symbol":"CancelModelParamProvider","kind":"class","lang":"kotlin","code":"class CancelModelParamProvider : SimpleProvider() {\n override fun arguments() =\n CancelTest.CancelMode.values().flatMap { c ->\n CancelTest.ConnectionType.values().map { x ->\n Pair(\n c,\n x,\n )\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/CancelTest.kt","line":312,"symbol":"arguments","kind":"function","lang":"kotlin","code":"override fun arguments() =\n CancelTest.CancelMode.values().flatMap { c ->\n CancelTest.ConnectionType.values().map { x ->\n Pair(\n c,\n x,\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ExternalHttp2Example.kt","line":22,"symbol":"ExternalHttp2Example","kind":"object","lang":"kotlin","code":"object ExternalHttp2Example {\n @JvmStatic\n fun main(args: Array) {\n val client =\n OkHttpClient\n .Builder()\n .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))\n .build()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(\"https://www.google.ca/\")\n .build(),\n )\n val response = call.execute()\n try {\n println(response.code)\n println(\"PROTOCOL ${response.protocol}\")\n var line: String?\n while (response.body\n .source()\n .readUtf8Line()\n .also { line = it } != null\n ) {\n println(line)\n }\n } finally {\n response.body.close()\n }\n client.connectionPool.evictAll()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ExternalHttp2Example.kt","line":23,"symbol":"main","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun main(args: Array) {\n val client =\n OkHttpClient\n .Builder()\n .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))\n .build()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(\"https://www.google.ca/\")\n .build(),\n )\n val response = call.execute()\n try {\n println(response.code)\n println(\"PROTOCOL ${response.protocol}\")\n var line: String?\n while (response.body\n .source()\n .readUtf8Line()\n .also { line = it } != null\n ) {\n println(line)\n }\n } finally {\n response.body.close()\n }\n client.connectionPool.evictAll()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpDateTest.kt","line":27,"symbol":"HttpDateTest","kind":"class","lang":"kotlin","code":"class HttpDateTest {\n private lateinit var originalDefault: TimeZone\n\n @BeforeEach\n fun setUp() {\n originalDefault = TimeZone.getDefault()\n // The default timezone should affect none of these tests: HTTP specified GMT, so we set it to\n // something else.\n TimeZone.setDefault(TimeZone.getTimeZone(\"America/Los_Angeles\"))\n }\n\n @AfterEach\n @Throws(Exception::class)\n fun tearDown() {\n TimeZone.setDefault(originalDefault)\n }\n\n @Test\n @Throws(Exception::class)\n fun parseStandardFormats() {\n // RFC 822, updated by RFC 1123 with GMT.\n assertThat(\"Thu, 01 Jan 1970 00:00:00 GMT\".toHttpDateOrNull()!!.time).isEqualTo(0L)\n assertThat(\"Fri, 06 Jun 2014 12:30:30 GMT\".toHttpDateOrNull()!!.time).isEqualTo(1402057830000L)\n\n // RFC 850, obsoleted by RFC 1036 with GMT.\n assertThat(\"Thursday, 01-Jan-70 00:00:00 GMT\".toHttpDateOrNull()!!.time).isEqualTo(0L)\n assertThat(\"Friday, 06-Jun-14 12:30:30 GMT\".toHttpDateOrNull()!!.time).isEqualTo(1402057830000L)\n\n // ANSI C's asctime(): should use GMT, not platform default.\n assertThat(\"Thu Jan 1 00:00:00 1970\".toHttpDateOrNull()!!.time).isEqualTo(0L)\n assertThat(\"Fri Jun 6 12:30:30 2014\".toHttpDateOrNull()!!.t"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpDateTest.kt","line":30,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n originalDefault = TimeZone.getDefault()\n // The default timezone should affect none of these tests: HTTP specified GMT, so we set it to\n // something else.\n TimeZone.setDefault(TimeZone.getTimeZone(\"America/Los_Angeles\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpDateTest.kt","line":38,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n @Throws(Exception::class)\n fun tearDown() {\n TimeZone.setDefault(originalDefault)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpDateTest.kt","line":44,"symbol":"parseStandardFormats","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun parseStandardFormats() {\n // RFC 822, updated by RFC 1123 with GMT.\n assertThat(\"Thu, 01 Jan 1970 00:00:00 GMT\".toHttpDateOrNull()!!.time).isEqualTo(0L)\n assertThat(\"Fri, 06 Jun 2014 12:30:30 GMT\".toHttpDateOrNull()!!.time).isEqualTo(1402057830000L)\n\n // RFC 850, obsoleted by RFC 1036 with GMT.\n assertThat(\"Thursday, 01-Jan-70 00:00:00 GMT\".toHttpDateOrNull()!!.time).isEqualTo(0L)\n assertThat(\"Friday, 06-Jun-14 12:30:30 GMT\".toHttpDateOrNull()!!.time).isEqualTo(1402057830000L)\n\n // ANSI C's asctime(): should use GMT, not platform default.\n assertThat(\"Thu Jan 1 00:00:00 1970\".toHttpDateOrNull()!!.time).isEqualTo(0L)\n assertThat(\"Fri Jun 6 12:30:30 2014\".toHttpDateOrNull()!!.time).isEqualTo(1402057830000L)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpDateTest.kt","line":60,"symbol":"format","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun format() {\n assertThat(Date(0L).toHttpDateString()).isEqualTo(\"Thu, 01 Jan 1970 00:00:00 GMT\")\n assertThat(Date(1402057830000L).toHttpDateString()).isEqualTo(\"Fri, 06 Jun 2014 12:30:30 GMT\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpDateTest.kt","line":67,"symbol":"parseNonStandardStrings","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun parseNonStandardStrings() {\n // RFC 822, updated by RFC 1123 with any TZ\n assertThat(\"Thu, 01 Jan 1970 00:00:00 GMT-01:00\".toHttpDateOrNull()!!.time).isEqualTo(3600000L)\n assertThat(\"Thu, 01 Jan 1970 00:00:00 PST\".toHttpDateOrNull()!!.time).isEqualTo(28800000L)\n // Ignore trailing junk\n assertThat(\"Thu, 01 Jan 1970 00:00:00 GMT JUNK\".toHttpDateOrNull()!!.time).isEqualTo(0L)\n // Missing timezones treated as bad.\n assertThat(\"Thu, 01 Jan 1970 00:00:00\".toHttpDateOrNull()).isNull()\n // Missing seconds treated as bad.\n assertThat(\"Thu, 01 Jan 1970 00:00 GMT\".toHttpDateOrNull()).isNull()\n // Extra spaces treated as bad.\n assertThat(\"Thu, 01 Jan 1970 00:00 GMT\".toHttpDateOrNull()).isNull()\n // Missing leading zero treated as bad.\n assertThat(\"Thu, 1 Jan 1970 00:00 GMT\".toHttpDateOrNull()).isNull()\n\n // RFC 850, obsoleted by RFC 1036 with any TZ.\n assertThat(\"Thursday, 01-Jan-1970 00:00:00 GMT-01:00\".toHttpDateOrNull()!!.time)\n .isEqualTo(3600000L)\n assertThat(\"Thursday, 01-Jan-1970 00:00:00 PST\".toHttpDateOrNull()!!.time)\n .isEqualTo(28800000L)\n // Ignore trailing junk\n assertThat(\"Th"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":62,"symbol":"HttpUpgradesTest","kind":"class","lang":"kotlin","code":"class HttpUpgradesTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private var eventRecorder = EventRecorder()\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private var client =\n clientTestRule\n .newClientBuilder()\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n\n fun executeAndCheckUpgrade(request: Request) {\n val socketHandler =\n MockSocketHandler()\n .apply {\n receiveRequest(\"client says hello\\n\")\n sendResponse(\"server says hello\\n\")\n receiveRequest(\"client says goodbye\\n\")\n sendResponse(\"server says goodbye\\n\")\n exhaustResponse()\n exhaustRequest()\n }\n server.enqueue(socketHandler.upgradeResponse())\n\n client\n .newCall(request)\n .execute()\n .use { response ->\n assertThat(response.code).isEqualTo(HTTP_SWITCHING_PROTOCOLS)\n val socket = response.socket!!\n socket.sink.buffer().use { sink ->\n socket.source.buffer().use { source ->\n sink.write"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":80,"symbol":"executeAndCheckUpgrade","kind":"function","lang":"kotlin","code":"fun executeAndCheckUpgrade(request: Request) {\n val socketHandler =\n MockSocketHandler()\n .apply {\n receiveRequest(\"client says hello\\n\")\n sendResponse(\"server says hello\\n\")\n receiveRequest(\"client says goodbye\\n\")\n sendResponse(\"server says goodbye\\n\")\n exhaustResponse()\n exhaustRequest()\n }\n server.enqueue(socketHandler.upgradeResponse())\n\n client\n .newCall(request)\n .execute()\n .use { response ->\n assertThat(response.code).isEqualTo(HTTP_SWITCHING_PROTOCOLS)\n val socket = response.socket!!\n socket.sink.buffer().use { sink ->\n socket.source.buffer().use { source ->\n sink.writeUtf8(\"client says hello\\n\")\n sink.flush()\n\n assertThat(source.readUtf8Line()).isEqualTo(\"server says hello\")\n\n sink.writeUtf8(\"client says goodbye\\n\")\n sink.flush()\n\n assertThat(source.readUtf8Line()).isEqualTo(\"server says goodbye\")\n\n assertThat(source.exhausted()).isTrue()\n }\n }\n socketHandler.awaitSuccess()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":118,"symbol":"upgrade","kind":"function","lang":"kotlin","code":"@Test\n fun upgrade() {\n executeAndCheckUpgrade(upgradeRequest())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":123,"symbol":"upgradeWithEmptyRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun upgradeWithEmptyRequestBody() {\n executeAndCheckUpgrade(upgradeRequest().newBuilder().post(RequestBody.EMPTY).build())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":128,"symbol":"upgradeWithNonEmptyRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun upgradeWithNonEmptyRequestBody() {\n executeAndCheckUpgrade(\n upgradeRequest()\n .newBuilder()\n .post(\"Hello\".toRequestBody())\n .build(),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":138,"symbol":"upgradeHttps","kind":"function","lang":"kotlin","code":"@Test\n fun upgradeHttps() {\n // org.bouncycastle.tls.TlsNoCloseNotifyException: No close_notify alert received before connection closed\n platform.assumeNotBouncyCastle()\n\n enableTls(Protocol.HTTP_1_1)\n upgrade()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":147,"symbol":"upgradeRefusedByServer","kind":"function","lang":"kotlin","code":"@Test\n fun upgradeRefusedByServer() {\n server.enqueue(MockResponse(body = \"normal request\"))\n val requestWithUpgrade =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"Connection\", \"upgrade\")\n .build()\n client.newCall(requestWithUpgrade).execute().use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(response.socket).isNull()\n assertThat(response.body.string()).isEqualTo(\"normal request\")\n }\n // Confirm there's no RequestBodyStart/RequestBodyEnd on failed upgrades.\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":183,"symbol":"upgradeForbiddenOnHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun upgradeForbiddenOnHttp2() {\n enableTls(Protocol.HTTP_2, Protocol.HTTP_1_1)\n val socketHandler = MockSocketHandler()\n server.enqueue(socketHandler.upgradeResponse())\n val requestWithUpgrade =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"Connection\", \"upgrade\")\n .build()\n assertFailsWith {\n client.newCall(requestWithUpgrade).execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":199,"symbol":"upgradesOnReusedConnection","kind":"function","lang":"kotlin","code":"@Test\n fun upgradesOnReusedConnection() {\n server.enqueue(MockResponse(body = \"normal request\"))\n client.newCall(Request(server.url(\"/\"))).execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"normal request\")\n }\n\n upgrade()\n\n assertThat(server.takeRequest().connectionIndex).isEqualTo(0)\n assertThat(server.takeRequest().connectionIndex).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":212,"symbol":"cannotReuseConnectionAfterUpgrade","kind":"function","lang":"kotlin","code":"@Test\n fun cannotReuseConnectionAfterUpgrade() {\n upgrade()\n\n server.enqueue(MockResponse(body = \"normal request\"))\n client.newCall(Request(server.url(\"/\"))).execute().use { response ->\n assertThat(response.body.string()).isEqualTo(\"normal request\")\n }\n\n assertThat(server.takeRequest().connectionIndex).isEqualTo(0)\n assertThat(server.takeRequest().connectionIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":225,"symbol":"upgradeEventsWithoutRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun upgradeEventsWithoutRequestBody() {\n upgrade()\n\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n RequestBodyStart::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n RequestBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":252,"symbol":"upgradeEventsWithEmptyRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun upgradeEventsWithEmptyRequestBody() {\n upgradeWithEmptyRequestBody()\n\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n RequestBodyStart::class,\n RequestBodyEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n RequestBodyStart::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n RequestBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":281,"symbol":"upgradeEventsWithNonEmptyRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun upgradeEventsWithNonEmptyRequestBody() {\n upgradeWithNonEmptyRequestBody()\n\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n RequestBodyStart::class,\n RequestBodyEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n RequestBodyStart::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n RequestBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":310,"symbol":"enableTls","kind":"function","lang":"kotlin","code":"private fun enableTls(vararg protocols: Protocol) {\n client =\n client\n .newBuilder()\n .protocols(protocols.toList())\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.protocols = protocols.toList()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":324,"symbol":"upgradeRequest","kind":"function","lang":"kotlin","code":"private fun upgradeRequest() =\n Request(\n url = server.url(\"/\"),\n headers =\n headersOf(\n \"Connection\",\n \"upgrade\",\n ),\n )"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/HttpUpgradesTest.kt","line":334,"symbol":"upgradeResponse","kind":"function","lang":"kotlin","code":"private fun MockSocketHandler.upgradeResponse() =\n MockResponse\n .Builder()\n .code(HTTP_SWITCHING_PROTOCOLS)\n .addHeader(\"Connection\", \"upgrade\")\n .socketHandler(this)\n .build()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/SocketFailureTest.kt","line":37,"symbol":"SocketFailureTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass SocketFailureTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n val listener = SocketClosingEventListener()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private var client =\n clientTestRule\n .newClientBuilder()\n .eventListener(listener)\n .build()\n\n class SocketClosingEventListener : EventListener() {\n var shouldClose: Boolean = false\n var lastSocket: Socket? = null\n\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n lastSocket = connection.socket()\n }\n\n override fun requestHeadersStart(call: Call) {\n if (shouldClose) {\n lastSocket!!.close()\n }\n }\n }\n\n @Test\n fun socketFailureOnLargeRequestHeaders() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n server.start()\n\n val call1 =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n call1.execute().use { response -> response.body.string() }\n\n listener.shouldClose = true\n // Large headers are a likely reason the servers wou"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/SocketFailureTest.kt","line":56,"symbol":"SocketClosingEventListener","kind":"class","lang":"kotlin","code":"class SocketClosingEventListener : EventListener() {\n var shouldClose: Boolean = false\n var lastSocket: Socket? = null\n\n override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n lastSocket = connection.socket()\n }\n\n override fun requestHeadersStart(call: Call) {\n if (shouldClose) {\n lastSocket!!.close()\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/SocketFailureTest.kt","line":60,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n lastSocket = connection.socket()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/SocketFailureTest.kt","line":67,"symbol":"requestHeadersStart","kind":"function","lang":"kotlin","code":"override fun requestHeadersStart(call: Call) {\n if (shouldClose) {\n lastSocket!!.close()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/SocketFailureTest.kt","line":74,"symbol":"socketFailureOnLargeRequestHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun socketFailureOnLargeRequestHeaders() {\n server.enqueue(MockResponse())\n server.enqueue(MockResponse())\n server.start()\n\n val call1 =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n call1.execute().use { response -> response.body.string() }\n\n listener.shouldClose = true\n // Large headers are a likely reason the servers would cut off the connection before it completes sending\n // request headers.\n // 431 \"Request Header Fields Too Large\"\n val largeHeaders =\n Headers\n .Builder()\n .apply {\n repeat(32) {\n add(\"name-$it\", \"value-$it-\" + \"0\".repeat(1024))\n }\n }.build()\n val call2 =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .headers(largeHeaders)\n .build(),\n )\n\n val exception =\n assertFailsWith {\n call2.execute()\n }\n assertThat(exception.message).isIn(\"Socket closed\", \"Socket is closed\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":26,"symbol":"StatusLineTest","kind":"class","lang":"kotlin","code":"class StatusLineTest {\n @Test\n fun parse() {\n val message = \"Temporary Redirect\"\n val version = 1\n val code = 200\n val statusLine = parse(\"HTTP/1.$version $code $message\")\n assertThat(statusLine.message).isEqualTo(message)\n assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1)\n assertThat(statusLine.code).isEqualTo(code)\n }\n\n @Test\n fun emptyMessage() {\n val version = 1\n val code = 503\n val statusLine = parse(\"HTTP/1.$version $code \")\n assertThat(statusLine.message).isEqualTo(\"\")\n assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1)\n assertThat(statusLine.code).isEqualTo(code)\n }\n\n /**\n * This is not defined in the protocol but some servers won't add the leading empty space when the\n * message is empty. http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1\n */\n @Test\n fun emptyMessageAndNoLeadingSpace() {\n val version = 1\n val code = 503\n val statusLine = parse(\"HTTP/1.$version $code\")\n assertThat(statusLine.message).isEqualTo(\"\")\n assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1)\n assertThat(statusLine.code).isEqualTo(code)\n }\n\n // https://github.com/lysine-dev/okhttp/issues/"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":27,"symbol":"parse","kind":"function","lang":"kotlin","code":"@Test\n fun parse() {\n val message = \"Temporary Redirect\"\n val version = 1\n val code = 200\n val statusLine = parse(\"HTTP/1.$version $code $message\")\n assertThat(statusLine.message).isEqualTo(message)\n assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1)\n assertThat(statusLine.code).isEqualTo(code)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":38,"symbol":"emptyMessage","kind":"function","lang":"kotlin","code":"@Test\n fun emptyMessage() {\n val version = 1\n val code = 503\n val statusLine = parse(\"HTTP/1.$version $code \")\n assertThat(statusLine.message).isEqualTo(\"\")\n assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1)\n assertThat(statusLine.code).isEqualTo(code)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":52,"symbol":"emptyMessageAndNoLeadingSpace","kind":"function","lang":"kotlin","doc":"This is not defined in the protocol but some servers won't add the leading empty space when the message is empty. http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1","code":"@Test\n fun emptyMessageAndNoLeadingSpace() {\n val version = 1\n val code = 503\n val statusLine = parse(\"HTTP/1.$version $code\")\n assertThat(statusLine.message).isEqualTo(\"\")\n assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_1)\n assertThat(statusLine.code).isEqualTo(code)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":63,"symbol":"shoutcast","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/386","code":"@Test\n fun shoutcast() {\n val statusLine = parse(\"ICY 200 OK\")\n assertThat(statusLine.message).isEqualTo(\"OK\")\n assertThat(statusLine.protocol).isEqualTo(Protocol.HTTP_1_0)\n assertThat(statusLine.code).isEqualTo(200)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":71,"symbol":"missingProtocol","kind":"function","lang":"kotlin","code":"@Test\n fun missingProtocol() {\n assertInvalid(\"\")\n assertInvalid(\" \")\n assertInvalid(\"200 OK\")\n assertInvalid(\" 200 OK\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":79,"symbol":"protocolVersions","kind":"function","lang":"kotlin","code":"@Test\n fun protocolVersions() {\n assertInvalid(\"HTTP/2.0 200 OK\")\n assertInvalid(\"HTTP/2.1 200 OK\")\n assertInvalid(\"HTTP/-.1 200 OK\")\n assertInvalid(\"HTTP/1.- 200 OK\")\n assertInvalid(\"HTTP/0.1 200 OK\")\n assertInvalid(\"HTTP/101 200 OK\")\n assertInvalid(\"HTTP/1.1_200 OK\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":90,"symbol":"nonThreeDigitCode","kind":"function","lang":"kotlin","code":"@Test\n fun nonThreeDigitCode() {\n assertInvalid(\"HTTP/1.1 OK\")\n assertInvalid(\"HTTP/1.1 2 OK\")\n assertInvalid(\"HTTP/1.1 20 OK\")\n assertInvalid(\"HTTP/1.1 2000 OK\")\n assertInvalid(\"HTTP/1.1 two OK\")\n assertInvalid(\"HTTP/1.1 2\")\n assertInvalid(\"HTTP/1.1 2000\")\n assertInvalid(\"HTTP/1.1 two\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":102,"symbol":"truncated","kind":"function","lang":"kotlin","code":"@Test\n fun truncated() {\n assertInvalid(\"\")\n assertInvalid(\"H\")\n assertInvalid(\"HTTP/1\")\n assertInvalid(\"HTTP/1.\")\n assertInvalid(\"HTTP/1.1\")\n assertInvalid(\"HTTP/1.1 \")\n assertInvalid(\"HTTP/1.1 2\")\n assertInvalid(\"HTTP/1.1 20\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":114,"symbol":"wrongMessageDelimiter","kind":"function","lang":"kotlin","code":"@Test\n fun wrongMessageDelimiter() {\n assertInvalid(\"HTTP/1.1 200_\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/StatusLineTest.kt","line":119,"symbol":"assertInvalid","kind":"function","lang":"kotlin","code":"private fun assertInvalid(statusLine: String) {\n assertFailsWith {\n parse(statusLine)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":53,"symbol":"ThreadInterruptTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass ThreadInterruptTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n private lateinit var server: MockWebServer\n private lateinit var client: OkHttpClient\n\n @BeforeEach\n fun setUp() {\n // Sockets on some platforms can have large buffers that mean writes do not block when\n // required. These socket factories explicitly set the buffer sizes on sockets created.\n server = MockWebServer()\n server.serverSocketFactory =\n object : DelegatingServerSocketFactory(getDefault()) {\n @Throws(SocketException::class)\n override fun configureServerSocket(serverSocket: ServerSocket): ServerSocket {\n serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE)\n return serverSocket\n }\n }\n client =\n clientTestRule\n .newClientBuilder()\n .socketFactory(\n object : DelegatingSocketFactory(getDefault()) {\n @Throws(IOException::class)\n override fun configureSocket(socket: Socket): Socket {\n socket.setSendBufferSize(SOCKET_BUFFER_SIZE)\n socket.setReceiveBufferSize(SOCKET_BUFFER_SIZ"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":63,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n // Sockets on some platforms can have large buffers that mean writes do not block when\n // required. These socket factories explicitly set the buffer sizes on sockets created.\n server = MockWebServer()\n server.serverSocketFactory =\n object : DelegatingServerSocketFactory(getDefault()) {\n @Throws(SocketException::class)\n override fun configureServerSocket(serverSocket: ServerSocket): ServerSocket {\n serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE)\n return serverSocket\n }\n }\n client =\n clientTestRule\n .newClientBuilder()\n .socketFactory(\n object : DelegatingSocketFactory(getDefault()) {\n @Throws(IOException::class)\n override fun configureSocket(socket: Socket): Socket {\n socket.setSendBufferSize(SOCKET_BUFFER_SIZE)\n socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE)\n return socket\n }\n },\n ).build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":70,"symbol":"configureServerSocket","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun configureServerSocket(serverSocket: ServerSocket): ServerSocket {\n serverSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE)\n return serverSocket\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":81,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun configureSocket(socket: Socket): Socket {\n socket.setSendBufferSize(SOCKET_BUFFER_SIZE)\n socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE)\n return socket\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":91,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n Thread.interrupted() // Clear interrupted state.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":96,"symbol":"interruptWritingRequestBody","kind":"function","lang":"kotlin","code":"@Test\n fun interruptWritingRequestBody() {\n server.enqueue(MockResponse())\n server.start()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .post(\n object : RequestBody() {\n override fun contentType() = null\n\n override fun writeTo(sink: BufferedSink) {\n for (i in 0..9) {\n sink.writeByte(0)\n sink.flush()\n sleep(100)\n }\n fail(\"Expected connection to be closed\")\n }\n },\n ).build(),\n )\n interruptLater(500)\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":107,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = null"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":109,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n for (i in 0..9) {\n sink.writeByte(0)\n sink.flush()\n sleep(100)\n }\n fail(\"Expected connection to be closed\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":126,"symbol":"interruptReadingResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun interruptReadingResponseBody() {\n val responseBodySize = 8 * 1024 * 1024 // 8 MiB.\n server.enqueue(\n MockResponse()\n .setBody(Buffer().write(ByteArray(responseBodySize)))\n .throttleBody((64 * 1024).toLong(), 125, TimeUnit.MILLISECONDS),\n ) // 500 Kbps\n server.start()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response = call.execute()\n interruptLater(500)\n val responseBody = response.body.byteStream()\n val buffer = ByteArray(1024)\n assertFailsWith {\n while (responseBody.read(buffer) != -1) {\n }\n }\n responseBody.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":153,"symbol":"forciblyStopDispatcher","kind":"function","lang":"kotlin","code":"@Test\n fun forciblyStopDispatcher() {\n client =\n client\n .newBuilder()\n .fastFallback(true)\n .build()\n\n val callFailure = CompletableFuture()\n\n server.enqueue(\n MockResponse()\n .setSocketPolicy(SocketPolicy.STALL_SOCKET_AT_START),\n )\n server.start()\n val call =\n client.newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n call.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: okio.IOException,\n ) {\n callFailure.complete(e)\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n }\n },\n )\n\n // This should fail the Call, but not cause an unhandled Exception bubbling up\n client.dispatcher.executorService.shutdownNow()\n\n val exception = callFailure.get(5, TimeUnit.SECONDS)\n assertThat(exception.message)\n .isNotNull()\n .startsWith(\"canceled due to\")\n assertThat(exception).isInstanceOf()\n assertThat(exception.cause)\n .isNotNull()\n .matchesPredicate { it is InterruptedException |"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":177,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: okio.IOException,\n ) {\n callFailure.complete(e)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":184,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":207,"symbol":"sleep","kind":"function","lang":"kotlin","code":"private fun sleep(delayMillis: Int) {\n try {\n Thread.sleep(delayMillis.toLong())\n } catch (e: InterruptedException) {\n Thread.currentThread().interrupt()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http/ThreadInterruptTest.kt","line":215,"symbol":"interruptLater","kind":"function","lang":"kotlin","code":"private fun interruptLater(delayMillis: Int) {\n val toInterrupt = Thread.currentThread()\n val interruptingCow =\n Thread {\n sleep(delayMillis)\n toInterrupt.interrupt()\n }\n interruptingCow.start()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":22,"symbol":"BaseTestHandler","kind":"class","lang":"kotlin","code":"internal open class BaseTestHandler : Http2Reader.Handler {\n override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n fail(\"\")\n }\n\n override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n fail(\"\")\n }\n\n override fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n fail(\"\")\n }\n\n override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n fail(\"\")\n }\n\n override fun ackSettings() {\n fail(\"\")\n }\n\n override fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n ) {\n fail(\"\")\n }\n\n override fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n ) {\n fail(\"\")\n }\n\n override fun windowUpdate(\n streamId: Int,\n windowSizeIncrement: Long,\n ) {\n fail(\"\")\n }\n\n override fun priority(\n streamId: Int,\n streamDependency: Int,\n weight: Int,\n exclusive: Boolean,\n ) {\n fail(\"\")\n }\n\n override fun pushPromise(\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n fail(\"\")\n }\n\n override "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":23,"symbol":"data","kind":"function","lang":"kotlin","code":"override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":32,"symbol":"headers","kind":"function","lang":"kotlin","code":"override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":41,"symbol":"rstStream","kind":"function","lang":"kotlin","code":"override fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":48,"symbol":"settings","kind":"function","lang":"kotlin","code":"override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":55,"symbol":"ackSettings","kind":"function","lang":"kotlin","code":"override fun ackSettings() {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":59,"symbol":"ping","kind":"function","lang":"kotlin","code":"override fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":67,"symbol":"goAway","kind":"function","lang":"kotlin","code":"override fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":75,"symbol":"windowUpdate","kind":"function","lang":"kotlin","code":"override fun windowUpdate(\n streamId: Int,\n windowSizeIncrement: Long,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":82,"symbol":"priority","kind":"function","lang":"kotlin","code":"override fun priority(\n streamId: Int,\n streamDependency: Int,\n weight: Int,\n exclusive: Boolean,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":91,"symbol":"pushPromise","kind":"function","lang":"kotlin","code":"override fun pushPromise(\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/BaseTestHandler.kt","line":99,"symbol":"alternateService","kind":"function","lang":"kotlin","code":"override fun alternateService(\n streamId: Int,\n origin: String,\n protocol: ByteString,\n host: String,\n port: Int,\n maxAge: Long,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/FrameLogTest.kt","line":37,"symbol":"FrameLogTest","kind":"class","lang":"kotlin","code":"class FrameLogTest {\n /** Real stream traffic applied to the log format. */\n @Test\n fun exampleStream() {\n assertThat(frameLog(false, 0, 5, TYPE_SETTINGS, FLAG_NONE))\n .isEqualTo(\">> 0x00000000 5 SETTINGS \")\n assertThat(frameLog(false, 3, 100, TYPE_HEADERS, FLAG_END_HEADERS))\n .isEqualTo(\">> 0x00000003 100 HEADERS END_HEADERS\")\n assertThat(frameLog(false, 3, 0, TYPE_DATA, FLAG_END_STREAM))\n .isEqualTo(\">> 0x00000003 0 DATA END_STREAM\")\n assertThat(frameLog(true, 0, 15, TYPE_SETTINGS, FLAG_NONE))\n .isEqualTo(\"<< 0x00000000 15 SETTINGS \")\n assertThat(frameLog(false, 0, 0, TYPE_SETTINGS, FLAG_ACK))\n .isEqualTo(\">> 0x00000000 0 SETTINGS ACK\")\n assertThat(frameLog(true, 0, 0, TYPE_SETTINGS, FLAG_ACK))\n .isEqualTo(\"<< 0x00000000 0 SETTINGS ACK\")\n assertThat(frameLog(true, 3, 22, TYPE_HEADERS, FLAG_END_HEADERS))\n .isEqualTo(\"<< 0x00000003 22 HEADERS END_HEADERS\")\n assertThat(frameLog(true, 3, 226, TYPE_DATA, FLAG_END_STREAM))\n .isEqualTo(\"<< 0x00000003 226 DATA END_STREAM\")\n assertThat(frameLog(false, 0, 8, TYPE_GOAWAY, FLAG_NONE))\n .isEqu"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/FrameLogTest.kt","line":39,"symbol":"exampleStream","kind":"function","lang":"kotlin","doc":"Real stream traffic applied to the log format.","code":"@Test\n fun exampleStream() {\n assertThat(frameLog(false, 0, 5, TYPE_SETTINGS, FLAG_NONE))\n .isEqualTo(\">> 0x00000000 5 SETTINGS \")\n assertThat(frameLog(false, 3, 100, TYPE_HEADERS, FLAG_END_HEADERS))\n .isEqualTo(\">> 0x00000003 100 HEADERS END_HEADERS\")\n assertThat(frameLog(false, 3, 0, TYPE_DATA, FLAG_END_STREAM))\n .isEqualTo(\">> 0x00000003 0 DATA END_STREAM\")\n assertThat(frameLog(true, 0, 15, TYPE_SETTINGS, FLAG_NONE))\n .isEqualTo(\"<< 0x00000000 15 SETTINGS \")\n assertThat(frameLog(false, 0, 0, TYPE_SETTINGS, FLAG_ACK))\n .isEqualTo(\">> 0x00000000 0 SETTINGS ACK\")\n assertThat(frameLog(true, 0, 0, TYPE_SETTINGS, FLAG_ACK))\n .isEqualTo(\"<< 0x00000000 0 SETTINGS ACK\")\n assertThat(frameLog(true, 3, 22, TYPE_HEADERS, FLAG_END_HEADERS))\n .isEqualTo(\"<< 0x00000003 22 HEADERS END_HEADERS\")\n assertThat(frameLog(true, 3, 226, TYPE_DATA, FLAG_END_STREAM))\n .isEqualTo(\"<< 0x00000003 226 DATA END_STREAM\")\n assertThat(frameLog(false, 0, 8, TYPE_GOAWAY, FLAG_NONE))\n .isEqualTo(\">> 0x00000000 8 GOAWAY \")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/FrameLogTest.kt","line":62,"symbol":"windowUpdateFrames","kind":"function","lang":"kotlin","doc":"Window update frames have special formatting.","code":"@Test\n fun windowUpdateFrames() {\n assertThat(frameLogWindowUpdate(false, 0, 4, Int.MAX_VALUE.toLong()))\n .isEqualTo(\">> 0x00000000 4 WINDOW_UPDATE 2147483647\")\n assertThat(frameLogWindowUpdate(true, 101, 4, 1))\n .isEqualTo(\"<< 0x00000065 4 WINDOW_UPDATE 1\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/FrameLogTest.kt","line":70,"symbol":"flagOverlapOn0x1","kind":"function","lang":"kotlin","code":"@Test\n fun flagOverlapOn0x1() {\n assertThat(frameLog(true, 0, 0, TYPE_SETTINGS, 0x1))\n .isEqualTo(\"<< 0x00000000 0 SETTINGS ACK\")\n assertThat(frameLog(true, 0, 8, TYPE_PING, 0x1))\n .isEqualTo(\"<< 0x00000000 8 PING ACK\")\n assertThat(frameLog(true, 3, 0, TYPE_HEADERS, 0x1))\n .isEqualTo(\"<< 0x00000003 0 HEADERS END_STREAM\")\n assertThat(frameLog(true, 3, 0, TYPE_DATA, 0x1))\n .isEqualTo(\"<< 0x00000003 0 DATA END_STREAM\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/FrameLogTest.kt","line":82,"symbol":"flagOverlapOn0x4","kind":"function","lang":"kotlin","code":"@Test\n fun flagOverlapOn0x4() {\n assertThat(frameLog(true, 3, 10000, TYPE_HEADERS, 0x4))\n .isEqualTo(\"<< 0x00000003 10000 HEADERS END_HEADERS\")\n assertThat(frameLog(true, 3, 10000, TYPE_CONTINUATION, 0x4))\n .isEqualTo(\"<< 0x00000003 10000 CONTINUATION END_HEADERS\")\n assertThat(frameLog(true, 4, 10000, TYPE_PUSH_PROMISE, 0x4))\n .isEqualTo(\"<< 0x00000004 10000 PUSH_PROMISE END_PUSH_PROMISE\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/FrameLogTest.kt","line":92,"symbol":"flagOverlapOn0x20","kind":"function","lang":"kotlin","code":"@Test\n fun flagOverlapOn0x20() {\n assertThat(frameLog(true, 3, 10000, TYPE_HEADERS, 0x20))\n .isEqualTo(\"<< 0x00000003 10000 HEADERS PRIORITY\")\n assertThat(frameLog(true, 3, 10000, TYPE_DATA, 0x20))\n .isEqualTo(\"<< 0x00000003 10000 DATA COMPRESSED\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/FrameLogTest.kt","line":104,"symbol":"allFormattedFlagsWithValidBits","kind":"function","lang":"kotlin","doc":"Ensures that valid flag combinations appear visually correct, and invalid show in hex. This also demonstrates how sparse the lookup table is.","code":"@Test\n fun allFormattedFlagsWithValidBits() {\n val formattedFlags = mutableListOf() // Highest valid flag is 0x20.\n for (i in 0..0x3f) formattedFlags.add(formatFlags(TYPE_HEADERS, i))\n assertThat(formattedFlags).containsExactly(\n \"\",\n \"END_STREAM\",\n \"00000010\",\n \"00000011\",\n \"END_HEADERS\",\n \"END_STREAM|END_HEADERS\",\n \"00000110\",\n \"00000111\",\n \"PADDED\",\n \"END_STREAM|PADDED\",\n \"00001010\",\n \"00001011\",\n \"00001100\",\n \"END_STREAM|END_HEADERS|PADDED\",\n \"00001110\",\n \"00001111\",\n \"00010000\",\n \"00010001\",\n \"00010010\",\n \"00010011\",\n \"00010100\",\n \"00010101\",\n \"00010110\",\n \"00010111\",\n \"00011000\",\n \"00011001\",\n \"00011010\",\n \"00011011\",\n \"00011100\",\n \"00011101\",\n \"00011110\",\n \"00011111\",\n \"PRIORITY\",\n \"END_STREAM|PRIORITY\",\n \"00100010\",\n \"00100011\",\n \"END_HEADERS|PRIORITY\",\n \"END_STREAM|END_HEADERS|PRIORITY\",\n \"00100110\",\n \"00100111\",\n \"00101000\",\n \"END_STREAM|PRIORITY|PADDED\",\n \"00101010\",\n \"00101011\",\n \"00101100\",\n \"END_STREAM|END_HEADERS|PRIORITY|P"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":33,"symbol":"HpackTest","kind":"class","lang":"kotlin","code":"class HpackTest {\n private val bytesIn = Buffer()\n private var hpackReader: Hpack.Reader? = null\n private val bytesOut = Buffer()\n private var hpackWriter: Hpack.Writer? = null\n\n @BeforeEach\n fun reset() {\n hpackReader = newReader(bytesIn)\n hpackWriter = Hpack.Writer(4096, false, bytesOut)\n }\n\n /**\n * Variable-length quantity special cases strings which are longer than 127 bytes. Values such as\n * cookies can be 4KiB, and should be possible to send.\n *\n * http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#section-5.2\n */\n @Test\n fun largeHeaderValue() {\n val value = CharArray(4096)\n Arrays.fill(value, '!')\n val headerBlock = headerEntries(\"cookie\", String(value))\n hpackWriter!!.writeHeaders(headerBlock)\n bytesIn.writeAll(bytesOut)\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(headerBlock)\n }\n\n /**\n * HPACK has a max header table size, which can be smaller than the max header message. Ensure the\n * larger header content is not lost.\n */\n @Test\n fun tooLargeToHPackIsStillEmitted() {\n bytesIn.writeByte(0x21) /"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":39,"symbol":"reset","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun reset() {\n hpackReader = newReader(bytesIn)\n hpackWriter = Hpack.Writer(4096, false, bytesOut)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":51,"symbol":"largeHeaderValue","kind":"function","lang":"kotlin","doc":"Variable-length quantity special cases strings which are longer than 127 bytes. Values such as cookies can be 4KiB, and should be possible to send. http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#section-5.2","code":"@Test\n fun largeHeaderValue() {\n val value = CharArray(4096)\n Arrays.fill(value, '!')\n val headerBlock = headerEntries(\"cookie\", String(value))\n hpackWriter!!.writeHeaders(headerBlock)\n bytesIn.writeAll(bytesOut)\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":67,"symbol":"tooLargeToHPackIsStillEmitted","kind":"function","lang":"kotlin","doc":"HPACK has a max header table size, which can be smaller than the max header message. Ensure the larger header content is not lost.","code":"@Test\n fun tooLargeToHPackIsStillEmitted() {\n bytesIn.writeByte(0x21) // Dynamic table size update (size = 1).\n bytesIn.writeByte(0x00) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-key\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\"custom-key\", \"custom-header\"),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":83,"symbol":"writerEviction","kind":"function","lang":"kotlin","doc":"Oldest entries are evicted to support newer ones.","code":"@Test\n fun writerEviction() {\n val headerBlock =\n headerEntries(\n \"custom-foo\",\n \"custom-header\",\n \"custom-bar\",\n \"custom-header\",\n \"custom-baz\",\n \"custom-header\",\n )\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-foo\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-bar\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-baz\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n\n // Set to only support 110 bytes (enough for 2 headers).\n // Use a new Writer because we don't support change the dynamic table\n // size after Writer constructed.\n val writer = Hpack.Writer(110, false, bytesOut)\n writer.writeHeaders(headerBlock)\n assertThat("} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":124,"symbol":"readerEviction","kind":"function","lang":"kotlin","code":"@Test\n fun readerEviction() {\n val headerBlock =\n headerEntries(\n \"custom-foo\",\n \"custom-header\",\n \"custom-bar\",\n \"custom-header\",\n \"custom-baz\",\n \"custom-header\",\n )\n\n // Set to only support 110 bytes (enough for 2 headers).\n bytesIn.writeByte(0x3F) // Dynamic table size update (size = 110).\n bytesIn.writeByte(0x4F)\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-foo\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-bar\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-baz\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(2)\n val entry1 = hpackReader!!"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":173,"symbol":"dynamicallyGrowsBeyond64Entries","kind":"function","lang":"kotlin","doc":"Header table backing array is initially 8 long, let's ensure it grows.","code":"@Test\n fun dynamicallyGrowsBeyond64Entries() {\n // Lots of headers need more room!\n hpackReader = Hpack.Reader(bytesIn, 16384, 4096)\n bytesIn.writeByte(0x3F) // Dynamic table size update (size = 16384).\n bytesIn.writeByte(0xE1)\n bytesIn.writeByte(0x7F)\n for (i in 0..255) {\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-foo\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n }\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(256)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":191,"symbol":"huffmanDecodingSupported","kind":"function","lang":"kotlin","code":"@Test\n fun huffmanDecodingSupported() {\n bytesIn.writeByte(0x44) // == Literal indexed ==\n // Indexed name (idx = 4) -> :path\n bytesIn.writeByte(0x8c) // Literal value Huffman encoded 12 bytes\n // decodes to www.example.com which is length 15\n bytesIn.write(\"f1e3c2e5f23a6ba0ab90f4ff\".decodeHex())\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(1)\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(52)\n val entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]!!\n checkEntry(entry, \":path\", \"www.example.com\", 52)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":208,"symbol":"readLiteralHeaderFieldWithIndexing","kind":"function","lang":"kotlin","doc":"http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#appendix-C.2.1","code":"@Test\n fun readLiteralHeaderFieldWithIndexing() {\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-key\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(1)\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(55)\n val entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]!!\n checkEntry(entry, \"custom-key\", \"custom-header\", 55)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\"custom-key\", \"custom-header\"),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":228,"symbol":"literalHeaderFieldWithoutIndexingIndexedName","kind":"function","lang":"kotlin","doc":"http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#appendix-C.2.2","code":"@Test\n fun literalHeaderFieldWithoutIndexingIndexedName() {\n val headerBlock = headerEntries(\":path\", \"/sample/path\")\n bytesIn.writeByte(0x04) // == Literal not indexed ==\n // Indexed name (idx = 4) -> :path\n bytesIn.writeByte(0x0c) // Literal value (len = 12)\n bytesIn.writeUtf8(\"/sample/path\")\n hpackWriter!!.writeHeaders(headerBlock)\n assertThat(bytesOut).isEqualTo(bytesIn)\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":242,"symbol":"literalHeaderFieldWithoutIndexingNewName","kind":"function","lang":"kotlin","code":"@Test\n fun literalHeaderFieldWithoutIndexingNewName() {\n val headerBlock = headerEntries(\"custom-key\", \"custom-header\")\n bytesIn.writeByte(0x00) // Not indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-key\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":255,"symbol":"literalHeaderFieldNeverIndexedIndexedName","kind":"function","lang":"kotlin","code":"@Test\n fun literalHeaderFieldNeverIndexedIndexedName() {\n bytesIn.writeByte(0x14) // == Literal never indexed ==\n // Indexed name (idx = 4) -> :path\n bytesIn.writeByte(0x0c) // Literal value (len = 12)\n bytesIn.writeUtf8(\"/sample/path\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\":path\", \"/sample/path\"),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":268,"symbol":"literalHeaderFieldNeverIndexedNewName","kind":"function","lang":"kotlin","code":"@Test\n fun literalHeaderFieldNeverIndexedNewName() {\n val headerBlock = headerEntries(\"custom-key\", \"custom-header\")\n bytesIn.writeByte(0x10) // Never indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-key\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":281,"symbol":"literalHeaderFieldWithIncrementalIndexingIndexedName","kind":"function","lang":"kotlin","code":"@Test\n fun literalHeaderFieldWithIncrementalIndexingIndexedName() {\n val headerBlock = headerEntries(\":path\", \"/sample/path\")\n bytesIn.writeByte(0x44) // Indexed name (idx = 4) -> :path\n bytesIn.writeByte(0x0c) // Literal value (len = 12)\n bytesIn.writeUtf8(\"/sample/path\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(1)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":292,"symbol":"literalHeaderFieldWithIncrementalIndexingNewName","kind":"function","lang":"kotlin","code":"@Test\n fun literalHeaderFieldWithIncrementalIndexingNewName() {\n val headerBlock = headerEntries(\"custom-key\", \"custom-header\")\n bytesIn.writeByte(0x40) // Never indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-key\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n hpackWriter!!.writeHeaders(headerBlock)\n assertThat(bytesOut).isEqualTo(bytesIn)\n assertThat(hpackWriter!!.headerCount).isEqualTo(1)\n val entry = hpackWriter!!.dynamicTable[hpackWriter!!.dynamicTable.size - 1]!!\n checkEntry(entry, \"custom-key\", \"custom-header\", 55)\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(1)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":310,"symbol":"theSameHeaderAfterOneIncrementalIndexed","kind":"function","lang":"kotlin","code":"@Test\n fun theSameHeaderAfterOneIncrementalIndexed() {\n val headerBlock =\n headerEntries(\n \"custom-key\",\n \"custom-header\",\n \"custom-key\",\n \"custom-header\",\n )\n bytesIn.writeByte(0x40) // Never indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-key\")\n bytesIn.writeByte(0x0d) // Literal value (len = 13)\n bytesIn.writeUtf8(\"custom-header\")\n bytesIn.writeByte(0xbe) // Indexed name and value (idx = 63)\n hpackWriter!!.writeHeaders(headerBlock)\n assertThat(bytesOut).isEqualTo(bytesIn)\n assertThat(hpackWriter!!.headerCount).isEqualTo(1)\n val entry = hpackWriter!!.dynamicTable[hpackWriter!!.dynamicTable.size - 1]!!\n checkEntry(entry, \"custom-key\", \"custom-header\", 55)\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(1)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(headerBlock)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":335,"symbol":"staticHeaderIsNotCopiedIntoTheIndexedTable","kind":"function","lang":"kotlin","code":"@Test\n fun staticHeaderIsNotCopiedIntoTheIndexedTable() {\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(0)\n assertThat(hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]).isNull()\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\":method\", \"GET\"),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":349,"symbol":"readIndexedHeaderFieldIndex0","kind":"function","lang":"kotlin","doc":"Example taken from twitter/hpack DecoderTest.testUnusedIndex","code":"@Test\n fun readIndexedHeaderFieldIndex0() {\n bytesIn.writeByte(0x80) // == Indexed - Add idx = 0\n assertFailsWith {\n hpackReader!!.readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"index == 0\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":360,"symbol":"readIndexedHeaderFieldTooLargeIndex","kind":"function","lang":"kotlin","doc":"Example taken from twitter/hpack DecoderTest.testIllegalIndex","code":"@Test\n fun readIndexedHeaderFieldTooLargeIndex() {\n bytesIn.writeShort(0xff00) // == Indexed - Add idx = 127\n assertFailsWith {\n hpackReader!!.readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Header index too large 127\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":371,"symbol":"readIndexedHeaderFieldInsidiousIndex","kind":"function","lang":"kotlin","doc":"Example taken from twitter/hpack DecoderTest.testInsidiousIndex","code":"@Test\n fun readIndexedHeaderFieldInsidiousIndex() {\n bytesIn.writeByte(0xff) // == Indexed - Add ==\n bytesIn.write(\"8080808008\".decodeHex()) // idx = -2147483521\n assertFailsWith {\n hpackReader!!.readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"HPACK integer overflow\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":383,"symbol":"minMaxHeaderTableSize","kind":"function","lang":"kotlin","doc":"Example taken from twitter/hpack DecoderTest.testHeaderTableSizeUpdate","code":"@Test\n fun minMaxHeaderTableSize() {\n bytesIn.writeByte(0x20)\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.maxDynamicTableByteCount()).isEqualTo(0)\n bytesIn.writeByte(0x3f) // encode size 4096\n bytesIn.writeByte(0xe1)\n bytesIn.writeByte(0x1f)\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.maxDynamicTableByteCount()).isEqualTo(4096)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":396,"symbol":"cannotSetTableSizeLargerThanSettingsValue","kind":"function","lang":"kotlin","doc":"Example taken from twitter/hpack DecoderTest.testIllegalHeaderTableSizeUpdate","code":"@Test\n fun cannotSetTableSizeLargerThanSettingsValue() {\n bytesIn.writeByte(0x3f) // encode size 4097\n bytesIn.writeByte(0xe2)\n bytesIn.writeByte(0x1f)\n assertFailsWith {\n hpackReader!!.readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Invalid dynamic table size update 4097\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":409,"symbol":"readHeaderTableStateChangeInsidiousMaxHeaderByteCount","kind":"function","lang":"kotlin","doc":"Example taken from twitter/hpack DecoderTest.testInsidiousMaxHeaderSize","code":"@Test\n fun readHeaderTableStateChangeInsidiousMaxHeaderByteCount() {\n bytesIn.writeByte(0x3f)\n bytesIn.write(\"e1ffffff07\".decodeHex()) // count = -2147483648\n assertFailsWith {\n hpackReader!!.readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"HPACK integer overflow\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":420,"symbol":"dynamicTableSizeUpdateRejectsWrappedSmallPositive","kind":"function","lang":"kotlin","code":"@Test\n fun dynamicTableSizeUpdateRejectsWrappedSmallPositive() {\n bytesIn.writeByte(0x3f)\n bytesIn.write(\"ffffffff8f00\".decodeHex())\n assertFailsWith {\n hpackReader!!.readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"HPACK integer overflow\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":434,"symbol":"readIndexedHeaderFieldFromStaticTableWithoutBuffering","kind":"function","lang":"kotlin","doc":"http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#appendix-C.2.4","code":"@Test\n fun readIndexedHeaderFieldFromStaticTableWithoutBuffering() {\n bytesIn.writeByte(0x20) // Dynamic table size update (size = 0).\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n hpackReader!!.readHeaders()\n\n // Not buffered in header table.\n assertThat(hpackReader!!.headerCount).isEqualTo(0)\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\":method\", \"GET\"),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":448,"symbol":"readLiteralHeaderWithIncrementalIndexingStaticName","kind":"function","lang":"kotlin","code":"@Test\n fun readLiteralHeaderWithIncrementalIndexingStaticName() {\n bytesIn.writeByte(0x7d) // == Literal indexed ==\n // Indexed name (idx = 60) -> \"www-authenticate\"\n bytesIn.writeByte(0x05) // Literal value (len = 5)\n bytesIn.writeUtf8(\"Basic\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.getAndResetHeaderList())\n .containsExactly(Header(\"www-authenticate\", \"Basic\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":459,"symbol":"readLiteralHeaderWithIncrementalIndexingDynamicName","kind":"function","lang":"kotlin","code":"@Test\n fun readLiteralHeaderWithIncrementalIndexingDynamicName() {\n bytesIn.writeByte(0x40)\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-foo\")\n bytesIn.writeByte(0x05) // Literal value (len = 5)\n bytesIn.writeUtf8(\"Basic\")\n bytesIn.writeByte(0x7e)\n bytesIn.writeByte(0x06) // Literal value (len = 6)\n bytesIn.writeUtf8(\"Basic2\")\n hpackReader!!.readHeaders()\n assertThat(hpackReader!!.getAndResetHeaderList()).containsExactly(\n Header(\"custom-foo\", \"Basic\"),\n Header(\"custom-foo\", \"Basic2\"),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":479,"symbol":"readRequestExamplesWithoutHuffman","kind":"function","lang":"kotlin","doc":"http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#appendix-C.2","code":"@Test\n fun readRequestExamplesWithoutHuffman() {\n firstRequestWithoutHuffman()\n hpackReader!!.readHeaders()\n checkReadFirstRequestWithoutHuffman()\n secondRequestWithoutHuffman()\n hpackReader!!.readHeaders()\n checkReadSecondRequestWithoutHuffman()\n thirdRequestWithoutHuffman()\n hpackReader!!.readHeaders()\n checkReadThirdRequestWithoutHuffman()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":492,"symbol":"readFailingRequestExample","kind":"function","lang":"kotlin","code":"@Test\n fun readFailingRequestExample() {\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n bytesIn.writeByte(0x86) // == Indexed - Add ==\n // idx = 7 -> :scheme: http\n bytesIn.writeByte(0x84) // == Indexed - Add ==\n bytesIn.writeByte(0x7f) // == Bad index! ==\n\n // Indexed name (idx = 4) -> :authority\n bytesIn.writeByte(0x0f) // Literal value (len = 15)\n bytesIn.writeUtf8(\"www.example.com\")\n assertFailsWith {\n hpackReader!!.readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Header index too large 78\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":511,"symbol":"firstRequestWithoutHuffman","kind":"function","lang":"kotlin","code":"private fun firstRequestWithoutHuffman() {\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n bytesIn.writeByte(0x86) // == Indexed - Add ==\n // idx = 7 -> :scheme: http\n bytesIn.writeByte(0x84) // == Indexed - Add ==\n // idx = 6 -> :path: /\n bytesIn.writeByte(0x41) // == Literal indexed ==\n // Indexed name (idx = 4) -> :authority\n bytesIn.writeByte(0x0f) // Literal value (len = 15)\n bytesIn.writeUtf8(\"www.example.com\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":524,"symbol":"checkReadFirstRequestWithoutHuffman","kind":"function","lang":"kotlin","code":"private fun checkReadFirstRequestWithoutHuffman() {\n assertThat(hpackReader!!.headerCount).isEqualTo(1)\n\n // [ 1] (s = 57) :authority: www.example.com\n val entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]!!\n checkEntry(entry, \":authority\", \"www.example.com\", 57)\n\n // Table size: 57\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(57)\n\n // Decoded header list:\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\n \":method\",\n \"GET\",\n \":scheme\",\n \"http\",\n \":path\",\n \"/\",\n \":authority\",\n \"www.example.com\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":549,"symbol":"secondRequestWithoutHuffman","kind":"function","lang":"kotlin","code":"private fun secondRequestWithoutHuffman() {\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n bytesIn.writeByte(0x86) // == Indexed - Add ==\n // idx = 7 -> :scheme: http\n bytesIn.writeByte(0x84) // == Indexed - Add ==\n // idx = 6 -> :path: /\n bytesIn.writeByte(0xbe) // == Indexed - Add ==\n // Indexed name (idx = 62) -> :authority: www.example.com\n bytesIn.writeByte(0x58) // == Literal indexed ==\n // Indexed name (idx = 24) -> cache-control\n bytesIn.writeByte(0x08) // Literal value (len = 8)\n bytesIn.writeUtf8(\"no-cache\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":564,"symbol":"checkReadSecondRequestWithoutHuffman","kind":"function","lang":"kotlin","code":"private fun checkReadSecondRequestWithoutHuffman() {\n assertThat(hpackReader!!.headerCount).isEqualTo(2)\n\n // [ 1] (s = 53) cache-control: no-cache\n var entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 2]!!\n checkEntry(entry, \"cache-control\", \"no-cache\", 53)\n\n // [ 2] (s = 57) :authority: www.example.com\n entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]!!\n checkEntry(entry, \":authority\", \"www.example.com\", 57)\n\n // Table size: 110\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(110)\n\n // Decoded header list:\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\n \":method\",\n \"GET\",\n \":scheme\",\n \"http\",\n \":path\",\n \"/\",\n \":authority\",\n \"www.example.com\",\n \"cache-control\",\n \"no-cache\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":595,"symbol":"thirdRequestWithoutHuffman","kind":"function","lang":"kotlin","code":"private fun thirdRequestWithoutHuffman() {\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n bytesIn.writeByte(0x87) // == Indexed - Add ==\n // idx = 7 -> :scheme: http\n bytesIn.writeByte(0x85) // == Indexed - Add ==\n // idx = 5 -> :path: /index.html\n bytesIn.writeByte(0xbf) // == Indexed - Add ==\n // Indexed name (idx = 63) -> :authority: www.example.com\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x0a) // Literal name (len = 10)\n bytesIn.writeUtf8(\"custom-key\")\n bytesIn.writeByte(0x0c) // Literal value (len = 12)\n bytesIn.writeUtf8(\"custom-value\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":611,"symbol":"checkReadThirdRequestWithoutHuffman","kind":"function","lang":"kotlin","code":"private fun checkReadThirdRequestWithoutHuffman() {\n assertThat(hpackReader!!.headerCount).isEqualTo(3)\n\n // [ 1] (s = 54) custom-key: custom-value\n var entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 3]!!\n checkEntry(entry, \"custom-key\", \"custom-value\", 54)\n\n // [ 2] (s = 53) cache-control: no-cache\n entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 2]!!\n checkEntry(entry, \"cache-control\", \"no-cache\", 53)\n\n // [ 3] (s = 57) :authority: www.example.com\n entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]!!\n checkEntry(entry, \":authority\", \"www.example.com\", 57)\n\n // Table size: 164\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(164)\n\n // Decoded header list:\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\n \":method\",\n \"GET\",\n \":scheme\",\n \"https\",\n \":path\",\n \"/index.html\",\n \":authority\",\n \"www.example.com\",\n \"custom-key\",\n \"custom-value\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":649,"symbol":"readRequestExamplesWithHuffman","kind":"function","lang":"kotlin","doc":"http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#appendix-C.4","code":"@Test\n fun readRequestExamplesWithHuffman() {\n firstRequestWithHuffman()\n hpackReader!!.readHeaders()\n checkReadFirstRequestWithHuffman()\n secondRequestWithHuffman()\n hpackReader!!.readHeaders()\n checkReadSecondRequestWithHuffman()\n thirdRequestWithHuffman()\n hpackReader!!.readHeaders()\n checkReadThirdRequestWithHuffman()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":662,"symbol":"firstRequestWithHuffman","kind":"function","lang":"kotlin","code":"private fun firstRequestWithHuffman() {\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n bytesIn.writeByte(0x86) // == Indexed - Add ==\n // idx = 6 -> :scheme: http\n bytesIn.writeByte(0x84) // == Indexed - Add ==\n // idx = 4 -> :path: /\n bytesIn.writeByte(0x41) // == Literal indexed ==\n // Indexed name (idx = 1) -> :authority\n bytesIn.writeByte(0x8c) // Literal value Huffman encoded 12 bytes\n // decodes to www.example.com which is length 15\n bytesIn.write(\"f1e3c2e5f23a6ba0ab90f4ff\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":676,"symbol":"checkReadFirstRequestWithHuffman","kind":"function","lang":"kotlin","code":"private fun checkReadFirstRequestWithHuffman() {\n assertThat(hpackReader!!.headerCount).isEqualTo(1)\n\n // [ 1] (s = 57) :authority: www.example.com\n val entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]!!\n checkEntry(entry, \":authority\", \"www.example.com\", 57)\n\n // Table size: 57\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(57)\n\n // Decoded header list:\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\n \":method\",\n \"GET\",\n \":scheme\",\n \"http\",\n \":path\",\n \"/\",\n \":authority\",\n \"www.example.com\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":701,"symbol":"secondRequestWithHuffman","kind":"function","lang":"kotlin","code":"private fun secondRequestWithHuffman() {\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n bytesIn.writeByte(0x86) // == Indexed - Add ==\n // idx = 6 -> :scheme: http\n bytesIn.writeByte(0x84) // == Indexed - Add ==\n // idx = 4 -> :path: /\n bytesIn.writeByte(0xbe) // == Indexed - Add ==\n // idx = 62 -> :authority: www.example.com\n bytesIn.writeByte(0x58) // == Literal indexed ==\n // Indexed name (idx = 24) -> cache-control\n bytesIn.writeByte(0x86) // Literal value Huffman encoded 6 bytes\n // decodes to no-cache which is length 8\n bytesIn.write(\"a8eb10649cbf\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":717,"symbol":"checkReadSecondRequestWithHuffman","kind":"function","lang":"kotlin","code":"private fun checkReadSecondRequestWithHuffman() {\n assertThat(hpackReader!!.headerCount).isEqualTo(2)\n\n // [ 1] (s = 53) cache-control: no-cache\n var entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 2]!!\n checkEntry(entry, \"cache-control\", \"no-cache\", 53)\n\n // [ 2] (s = 57) :authority: www.example.com\n entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]!!\n checkEntry(entry, \":authority\", \"www.example.com\", 57)\n\n // Table size: 110\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(110)\n\n // Decoded header list:\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\n \":method\",\n \"GET\",\n \":scheme\",\n \"http\",\n \":path\",\n \"/\",\n \":authority\",\n \"www.example.com\",\n \"cache-control\",\n \"no-cache\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":748,"symbol":"thirdRequestWithHuffman","kind":"function","lang":"kotlin","code":"private fun thirdRequestWithHuffman() {\n bytesIn.writeByte(0x82) // == Indexed - Add ==\n // idx = 2 -> :method: GET\n bytesIn.writeByte(0x87) // == Indexed - Add ==\n // idx = 7 -> :scheme: https\n bytesIn.writeByte(0x85) // == Indexed - Add ==\n // idx = 5 -> :path: /index.html\n bytesIn.writeByte(0xbf) // == Indexed - Add ==\n // idx = 63 -> :authority: www.example.com\n bytesIn.writeByte(0x40) // Literal indexed\n bytesIn.writeByte(0x88) // Literal name Huffman encoded 8 bytes\n // decodes to custom-key which is length 10\n bytesIn.write(\"25a849e95ba97d7f\".decodeHex())\n bytesIn.writeByte(0x89) // Literal value Huffman encoded 9 bytes\n // decodes to custom-value which is length 12\n bytesIn.write(\"25a849e95bb8e8b4bf\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":766,"symbol":"checkReadThirdRequestWithHuffman","kind":"function","lang":"kotlin","code":"private fun checkReadThirdRequestWithHuffman() {\n assertThat(hpackReader!!.headerCount).isEqualTo(3)\n\n // [ 1] (s = 54) custom-key: custom-value\n var entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 3]!!\n checkEntry(entry, \"custom-key\", \"custom-value\", 54)\n\n // [ 2] (s = 53) cache-control: no-cache\n entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 2]!!\n checkEntry(entry, \"cache-control\", \"no-cache\", 53)\n\n // [ 3] (s = 57) :authority: www.example.com\n entry = hpackReader!!.dynamicTable[readerHeaderTableLength() - 1]!!\n checkEntry(entry, \":authority\", \"www.example.com\", 57)\n\n // Table size: 164\n assertThat(hpackReader!!.dynamicTableByteCount).isEqualTo(164)\n\n // Decoded header list:\n assertThat(hpackReader!!.getAndResetHeaderList()).isEqualTo(\n headerEntries(\n \":method\",\n \"GET\",\n \":scheme\",\n \"https\",\n \":path\",\n \"/index.html\",\n \":authority\",\n \"www.example.com\",\n \"custom-key\",\n \"custom-value\",\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":801,"symbol":"readSingleByteInt","kind":"function","lang":"kotlin","code":"@Test\n fun readSingleByteInt() {\n assertThat(newReader(byteStream()).readInt(10, 31)).isEqualTo(10)\n assertThat(newReader(byteStream()).readInt(0xe0 or 10, 31)).isEqualTo(10)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":807,"symbol":"readMultibyteInt","kind":"function","lang":"kotlin","code":"@Test\n fun readMultibyteInt() {\n assertThat(newReader(byteStream(154, 10)).readInt(31, 31)).isEqualTo(1337)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":812,"symbol":"writeSingleByteInt","kind":"function","lang":"kotlin","code":"@Test\n fun writeSingleByteInt() {\n hpackWriter!!.writeInt(10, 31, 0)\n assertBytes(10)\n hpackWriter!!.writeInt(10, 31, 0xe0)\n assertBytes(0xe0 or 10)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":820,"symbol":"writeMultibyteInt","kind":"function","lang":"kotlin","code":"@Test\n fun writeMultibyteInt() {\n hpackWriter!!.writeInt(1337, 31, 0)\n assertBytes(31, 154, 10)\n hpackWriter!!.writeInt(1337, 31, 0xe0)\n assertBytes(0xe0 or 31, 154, 10)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":828,"symbol":"max31BitValue","kind":"function","lang":"kotlin","code":"@Test\n fun max31BitValue() {\n hpackWriter!!.writeInt(0x7fffffff, 31, 0)\n assertBytes(31, 224, 255, 255, 255, 7)\n assertThat(newReader(byteStream(224, 255, 255, 255, 7)).readInt(31, 31))\n .isEqualTo(0x7fffffff)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":836,"symbol":"overflowingValueRejected","kind":"function","lang":"kotlin","code":"@Test\n fun overflowingValueRejected() {\n assertFailsWith {\n newReader(Buffer().write(\"8080808008\".decodeHex())).readInt(0xff, 0x7f)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"HPACK integer overflow\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":845,"symbol":"tooManyContinuationBytesRejected","kind":"function","lang":"kotlin","code":"@Test\n fun tooManyContinuationBytesRejected() {\n assertFailsWith {\n newReader(Buffer().write(\"808080808001\".decodeHex())).readInt(0x1f, 0x1f)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"HPACK integer overflow\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":854,"symbol":"stringLengthOverflowRejected","kind":"function","lang":"kotlin","code":"@Test\n fun stringLengthOverflowRejected() {\n val source = Buffer()\n source.writeByte(0x00)\n source.writeByte(0x7f)\n source.write(\"8080808008\".decodeHex())\n\n assertFailsWith {\n newReader(source).readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"HPACK integer overflow\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":868,"symbol":"prefixMask","kind":"function","lang":"kotlin","code":"@Test\n fun prefixMask() {\n hpackWriter!!.writeInt(31, 31, 0)\n assertBytes(31, 0)\n assertThat(newReader(byteStream(0)).readInt(31, 31)).isEqualTo(31)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":875,"symbol":"prefixMaskMinusOne","kind":"function","lang":"kotlin","code":"@Test\n fun prefixMaskMinusOne() {\n hpackWriter!!.writeInt(30, 31, 0)\n assertBytes(30)\n assertThat(newReader(byteStream(0)).readInt(31, 31)).isEqualTo(31)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":882,"symbol":"zero","kind":"function","lang":"kotlin","code":"@Test\n fun zero() {\n hpackWriter!!.writeInt(0, 31, 0)\n assertBytes(0)\n assertThat(newReader(byteStream()).readInt(0, 31)).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":889,"symbol":"lowercaseHeaderNameBeforeEmit","kind":"function","lang":"kotlin","code":"@Test\n fun lowercaseHeaderNameBeforeEmit() {\n hpackWriter!!.writeHeaders(listOf(Header(\"FoO\", \"BaR\")))\n assertBytes(0x40, 3, 'f'.code, 'o'.code, 'o'.code, 3, 'B'.code, 'a'.code, 'R'.code)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":895,"symbol":"mixedCaseHeaderNameIsMalformed","kind":"function","lang":"kotlin","code":"@Test\n fun mixedCaseHeaderNameIsMalformed() {\n assertFailsWith {\n newReader(\n byteStream(\n 0,\n 3,\n 'F'.code,\n 'o'.code,\n 'o'.code,\n 3,\n 'B'.code,\n 'a'.code,\n 'R'.code,\n ),\n ).readHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"PROTOCOL_ERROR response malformed: mixed case name: Foo\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":918,"symbol":"emptyHeaderName","kind":"function","lang":"kotlin","code":"@Test\n fun emptyHeaderName() {\n hpackWriter!!.writeByteString(\"\".encodeUtf8())\n assertBytes(0)\n assertThat(newReader(byteStream(0)).readByteString())\n .isEqualTo(ByteString.EMPTY)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":926,"symbol":"emitsDynamicTableSizeUpdate","kind":"function","lang":"kotlin","code":"@Test\n fun emitsDynamicTableSizeUpdate() {\n hpackWriter!!.resizeHeaderTable(2048)\n hpackWriter!!.writeHeaders(listOf(Header(\"foo\", \"bar\")))\n assertBytes(\n // Dynamic table size update (size = 2048).\n 0x3F,\n 0xE1,\n 0xF,\n 0x40,\n 3,\n 'f'.code,\n 'o'.code,\n 'o'.code,\n 3,\n 'b'.code,\n 'a'.code,\n 'r'.code,\n )\n hpackWriter!!.resizeHeaderTable(8192)\n hpackWriter!!.writeHeaders(listOf(Header(\"bar\", \"foo\")))\n assertBytes(\n // Dynamic table size update (size = 8192).\n 0x3F,\n 0xE1,\n 0x3F,\n 0x40,\n 3,\n 'b'.code,\n 'a'.code,\n 'r'.code,\n 3,\n 'f'.code,\n 'o'.code,\n 'o'.code,\n )\n\n // No more dynamic table updates should be emitted.\n hpackWriter!!.writeHeaders(listOf(Header(\"far\", \"boo\")))\n assertBytes(0x40, 3, 'f'.code, 'a'.code, 'r'.code, 3, 'b'.code, 'o'.code, 'o'.code)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":968,"symbol":"noDynamicTableSizeUpdateWhenSizeIsEqual","kind":"function","lang":"kotlin","code":"@Test\n fun noDynamicTableSizeUpdateWhenSizeIsEqual() {\n val currentSize = hpackWriter!!.headerTableSizeSetting\n hpackWriter!!.resizeHeaderTable(currentSize)\n hpackWriter!!.writeHeaders(listOf(Header(\"foo\", \"bar\")))\n assertBytes(0x40, 3, 'f'.code, 'o'.code, 'o'.code, 3, 'b'.code, 'a'.code, 'r'.code)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":976,"symbol":"growDynamicTableSize","kind":"function","lang":"kotlin","code":"@Test\n fun growDynamicTableSize() {\n hpackWriter!!.resizeHeaderTable(8192)\n hpackWriter!!.resizeHeaderTable(16384)\n hpackWriter!!.writeHeaders(listOf(Header(\"foo\", \"bar\")))\n assertBytes(\n // Dynamic table size update (size = 16384).\n 0x3F,\n 0xE1,\n 0x7F,\n 0x40,\n 3,\n 'f'.code,\n 'o'.code,\n 'o'.code,\n 3,\n 'b'.code,\n 'a'.code,\n 'r'.code,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HpackTest.kt","line":998,"symbol":"shrinkDynamicTableSize","kind":"function","lang":"kotlin","code":"@Test\n fun shrinkDynamicTableSize() {\n hpackWriter!!.resizeHeaderTable(2048)\n hpackWriter!!.resizeHeaderTable(0)\n hpackWriter!!.writeHeaders(listOf(Header(\"foo\", \"bar\")))\n assertBytes(\n // Dynamic size update (size = 0).\n 0x20,\n 0x40,\n 3,\n 'f'.code,\n 'o'.code,\n 'o'.code,\n 3,\n 'b'.code,\n 'a'.code,\n 'r'.code,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":58,"symbol":"Http2ConnectionTest","kind":"class","lang":"kotlin","code":"@Timeout(5)\n@Tag(\"Slow\")\nclass Http2ConnectionTest {\n private val peer = MockHttp2Peer()\n private val taskFaker = TaskFaker()\n\n @AfterEach fun tearDown() {\n peer.close()\n taskFaker.close()\n }\n\n @Test fun serverPingsClientHttp2() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.sendFrame().ping(false, 2, 3)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n connect(peer)\n\n // Verify the peer received what was expected.\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PING)\n assertThat(ping.streamId).isEqualTo(0)\n assertThat(ping.payload1).isEqualTo(2)\n assertThat(ping.payload2).isEqualTo(3)\n assertThat(ping.ack).isTrue()\n }\n\n @Test fun peerHttp2ServerLowersInitialWindowSize() {\n val initial = Settings()\n initial[Settings.INITIAL_WINDOW_SIZE] = 1684\n val shouldntImpactConnection = Settings()\n shouldntImpactConnection[Settings.INITIAL_WINDOW_SIZE] = 3368\n peer.sendFrame().settings(initial)\n peer.acceptFrame() // ACK\n peer.sendFrame().settings(shouldntImpactConnection)\n peer.acceptFrame() // ACK 2\n peer.acceptFrame"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":64,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n peer.close()\n taskFaker.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":69,"symbol":"serverPingsClientHttp2","kind":"function","lang":"kotlin","code":"@Test fun serverPingsClientHttp2() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.sendFrame().ping(false, 2, 3)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n connect(peer)\n\n // Verify the peer received what was expected.\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PING)\n assertThat(ping.streamId).isEqualTo(0)\n assertThat(ping.payload1).isEqualTo(2)\n assertThat(ping.payload2).isEqualTo(3)\n assertThat(ping.ack).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":89,"symbol":"peerHttp2ServerLowersInitialWindowSize","kind":"function","lang":"kotlin","code":"@Test fun peerHttp2ServerLowersInitialWindowSize() {\n val initial = Settings()\n initial[Settings.INITIAL_WINDOW_SIZE] = 1684\n val shouldntImpactConnection = Settings()\n shouldntImpactConnection[Settings.INITIAL_WINDOW_SIZE] = 3368\n peer.sendFrame().settings(initial)\n peer.acceptFrame() // ACK\n peer.sendFrame().settings(shouldntImpactConnection)\n peer.acceptFrame() // ACK 2\n peer.acceptFrame() // HEADERS\n peer.play()\n val connection = connect(peer)\n\n // Verify the peer received the second ACK.\n val ackFrame = peer.takeFrame()\n assertThat(ackFrame.type).isEqualTo(Http2.TYPE_SETTINGS)\n assertThat(ackFrame.streamId).isEqualTo(0)\n assertThat(ackFrame.ack).isTrue()\n\n // This stream was created *after* the connection settings were adjusted.\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), false)\n assertThat(connection.peerSettings.initialWindowSize).isEqualTo(3368)\n // New Stream is has the most recent initial window size.\n assertThat(stream.writeBytesTotal).isEqualTo(0L)\n assertThat(stream.writeBytesMaximum).isEqualTo(3368L)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":116,"symbol":"peerHttp2ServerZerosCompressionTable","kind":"function","lang":"kotlin","code":"@Test fun peerHttp2ServerZerosCompressionTable() {\n val client = false // Peer is server, so we are client.\n val settings = Settings()\n settings[Settings.HEADER_TABLE_SIZE] = 0\n val connection = connectWithSettings(client, settings)\n\n // Verify the peer's settings were read and applied.\n assertThat(connection.peerSettings.headerTableSize).isEqualTo(0)\n val writer = connection.writer\n assertThat(writer.hpackWriter.dynamicTableByteCount).isEqualTo(0)\n assertThat(writer.hpackWriter.headerTableSizeSetting).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":129,"symbol":"peerHttp2ClientDisablesPush","kind":"function","lang":"kotlin","code":"@Test fun peerHttp2ClientDisablesPush() {\n val client = false // Peer is client, so we are server.\n val settings = Settings()\n settings[Settings.ENABLE_PUSH] = 0 // The peer client disables push.\n val connection = connectWithSettings(client, settings)\n\n // verify the peer's settings were read and applied.\n assertThat(connection.peerSettings.getEnablePush(true)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":139,"symbol":"peerIncreasesMaxFrameSize","kind":"function","lang":"kotlin","code":"@Test fun peerIncreasesMaxFrameSize() {\n val newMaxFrameSize = 0x4001\n val settings = Settings()\n settings[Settings.MAX_FRAME_SIZE] = newMaxFrameSize\n val connection = connectWithSettings(true, settings)\n\n // verify the peer's settings were read and applied.\n assertThat(connection.peerSettings.getMaxFrameSize(-1)).isEqualTo(newMaxFrameSize)\n assertThat(connection.writer.maxDataLength()).isEqualTo(newMaxFrameSize)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":155,"symbol":"peerSetsZeroFlowControl","kind":"function","lang":"kotlin","doc":"Webservers may set the initial window size to zero, which is a special case because it means that we have to flush headers immediately before any request body can be sent. https://github.com/lysine-dev/okhttp/issues/2543","code":"@Test fun peerSetsZeroFlowControl() {\n peer.setClient(true)\n\n // Write the mocking script.\n peer.sendFrame().settings(Settings().set(Settings.INITIAL_WINDOW_SIZE, 0))\n peer.acceptFrame() // ACK\n peer.sendFrame().windowUpdate(0, 10) // Increase the connection window size.\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.acceptFrame() // HEADERS STREAM 3\n peer.sendFrame().windowUpdate(3, 5)\n peer.acceptFrame() // DATA STREAM 3 \"abcde\"\n peer.sendFrame().windowUpdate(3, 5)\n peer.acceptFrame() // DATA STREAM 3 \"fghi\"\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.writePingAndAwaitPong() // Ensure the SETTINGS have been received.\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), true)\n val sink = stream.sink.buffer()\n sink.writeUtf8(\"abcdefghi\")\n sink.flush()\n\n // Verify the peer received what was expected.\n peer.takeFrame() // PING\n val headers = peer.takeFrame()\n assertThat(headers.type).isEqualTo(Http2.TYPE_HEADERS)\n val data1 = peer.takeFrame()\n assertThat(data1.type).isEqualTo(Http2.TYPE_DATA)\n assertThat(data1.str"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":197,"symbol":"discardedDataFramesAreCounted","kind":"function","lang":"kotlin","doc":"Confirm that we account for discarded data frames. It's possible that data frames are in-flight just prior to us canceling a stream.","code":"@Test fun discardedDataFramesAreCounted() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM 3\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"apple\"))\n peer.sendFrame().data(false, 3, data(1024), 1024)\n peer.acceptFrame() // RST_STREAM\n peer.sendFrame().data(true, 3, data(1024), 1024)\n peer.acceptFrame() // RST_STREAM\n peer.play()\n val connection = connect(peer)\n val stream1 = connection.newStream(headerEntries(\"b\", \"bark\"), false)\n val source = stream1.source\n val buffer = Buffer()\n while (buffer.size != 1024L) source.read(buffer, 1024)\n stream1.close(ErrorCode.CANCEL, null)\n val frame1 = peer.takeFrame()\n assertThat(frame1.type).isEqualTo(Http2.TYPE_HEADERS)\n val frame2 = peer.takeFrame()\n assertThat(frame2.type).isEqualTo(Http2.TYPE_RST_STREAM)\n val frame3 = peer.takeFrame()\n assertThat(frame3.type).isEqualTo(Http2.TYPE_RST_STREAM)\n assertThat(connection.readBytes.acknowledged).isEqualTo(0L)\n assertThat(connection.readBytes.total).isEqualTo(2048L)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":224,"symbol":"receiveGoAwayHttp2","kind":"function","lang":"kotlin","code":"@Test fun receiveGoAwayHttp2() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM 3\n peer.acceptFrame() // SYN_STREAM 5\n peer.sendFrame().goAway(3, ErrorCode.PROTOCOL_ERROR, EMPTY_BYTE_ARRAY)\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.acceptFrame() // DATA STREAM 3\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream1 = connection.newStream(headerEntries(\"a\", \"android\"), true)\n val stream2 = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n connection.writePingAndAwaitPong() // Ensure the GO_AWAY that resets stream2 has been received.\n val sink1 = stream1.sink.buffer()\n val sink2 = stream2.sink.buffer()\n sink1.writeUtf8(\"abc\")\n assertFailsWith {\n sink2.writeUtf8(\"abc\")\n sink2.flush()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream was reset: REFUSED_STREAM\")\n }\n sink1.writeUtf8(\"def\")\n sink1.close()\n assertFailsWith {\n connection.newStream(headerEntries(\"c\", \"cola\"), t"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":272,"symbol":"readSendsWindowUpdateHttp2","kind":"function","lang":"kotlin","code":"@Test fun readSendsWindowUpdateHttp2() {\n val windowSize = 100\n val windowUpdateThreshold = 50\n\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n for (i in 0..2) {\n // Send frames of summing to size 50, which is windowUpdateThreshold.\n peer.sendFrame().data(false, 3, data(24), 24)\n peer.sendFrame().data(false, 3, data(25), 25)\n peer.sendFrame().data(false, 3, data(1), 1)\n peer.acceptFrame() // connection WINDOW UPDATE\n peer.acceptFrame() // stream WINDOW UPDATE\n }\n peer.sendFrame().data(true, 3, data(0), 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.okHttpSettings[Settings.INITIAL_WINDOW_SIZE] = windowSize\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), false)\n assertThat(stream.readBytes.acknowledged).isEqualTo(0L)\n assertThat(stream.readBytes.total).isEqualTo(0L)\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n val source = stream.source\n val buffer = Buffer()\n buffer.wri"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":321,"symbol":"serverSendsEmptyDataClientDoesntSendWindowUpdateHttp2","kind":"function","lang":"kotlin","code":"@Test fun serverSendsEmptyDataClientDoesntSendWindowUpdateHttp2() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.sendFrame().data(true, 3, data(0), 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val client = connection.newStream(headerEntries(\"b\", \"banana\"), false)\n assertThat(client.source.read(Buffer(), 1)).isEqualTo(-1)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(peer.frameCount()).isEqualTo(5)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":341,"symbol":"clientSendsEmptyDataServerDoesntSendWindowUpdateHttp2","kind":"function","lang":"kotlin","code":"@Test fun clientSendsEmptyDataServerDoesntSendWindowUpdateHttp2() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // DATA\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val client = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n val out = client.sink.buffer()\n out.write(EMPTY_BYTE_ARRAY)\n out.flush()\n out.close()\n\n // Verify the peer received what was expected.\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_DATA)\n assertThat(peer.frameCount()).isEqualTo(5)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":364,"symbol":"maxFrameSizeHonored","kind":"function","lang":"kotlin","code":"@Test fun maxFrameSizeHonored() {\n val buff = ByteArray(peer.maxOutboundDataLength() + 1)\n buff.fill('*'.code.toByte())\n\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.acceptFrame() // DATA\n peer.acceptFrame() // DATA\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n val out = stream.sink.buffer()\n out.write(buff)\n out.flush()\n out.close()\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n var data = peer.takeFrame()\n assertThat(data.data!!.size).isEqualTo(peer.maxOutboundDataLength())\n data = peer.takeFrame()\n assertThat(data.data!!.size).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":392,"symbol":"pushPromiseStream","kind":"function","lang":"kotlin","code":"@Test fun pushPromiseStream() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n val expectedRequestHeaders =\n listOf(\n Header(Header.TARGET_METHOD, \"GET\"),\n Header(Header.TARGET_SCHEME, \"https\"),\n Header(Header.TARGET_AUTHORITY, \"squareup.com\"),\n Header(Header.TARGET_PATH, \"/cached\"),\n )\n peer.sendFrame().pushPromise(3, 2, expectedRequestHeaders)\n val expectedResponseHeaders =\n listOf(\n Header(Header.RESPONSE_STATUS, \"200\"),\n )\n peer.sendFrame().headers(true, 2, expectedResponseHeaders)\n peer.sendFrame().data(true, 3, data(0), 0)\n peer.play()\n val observer = RecordingPushObserver()\n\n // Play it back.\n val connection = connect(peer, observer, Http2Connection.Listener.REFUSE_INCOMING_STREAMS)\n val client = connection.newStream(headerEntries(\"b\", \"banana\"), false)\n assertThat(client.source.read(Buffer(), 1)).isEqualTo(-1)\n\n // Verify the peer received what was expected.\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADE"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":426,"symbol":"doublePushPromise","kind":"function","lang":"kotlin","code":"@Test fun doublePushPromise() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.sendFrame().pushPromise(3, 2, headerEntries(\"a\", \"android\"))\n peer.acceptFrame() // SYN_REPLY\n peer.sendFrame().pushPromise(3, 2, headerEntries(\"b\", \"banana\"))\n peer.acceptFrame() // RST_STREAM\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.newStream(headerEntries(\"b\", \"banana\"), false)\n\n // Verify the peer received what was expected.\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(peer.takeFrame().errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":445,"symbol":"pushPromiseStreamsAutomaticallyCancel","kind":"function","lang":"kotlin","code":"@Test fun pushPromiseStreamsAutomaticallyCancel() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer\n .sendFrame()\n .pushPromise(\n streamId = 3,\n promisedStreamId = 2,\n requestHeaders =\n listOf(\n Header(Header.TARGET_METHOD, \"GET\"),\n Header(Header.TARGET_SCHEME, \"https\"),\n Header(Header.TARGET_AUTHORITY, \"squareup.com\"),\n Header(Header.TARGET_PATH, \"/cached\"),\n ),\n )\n peer\n .sendFrame()\n .headers(\n outFinished = true,\n streamId = 2,\n headerBlock =\n listOf(\n Header(Header.RESPONSE_STATUS, \"200\"),\n ),\n )\n peer.acceptFrame() // RST_STREAM\n peer.play()\n\n // Play it back.\n connect(peer, PushObserver.CANCEL, Http2Connection.Listener.REFUSE_INCOMING_STREAMS)\n\n // Verify the peer received what was expected.\n val rstStream = peer.takeFrame()\n assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM)\n assertThat(rstStream.streamId).isEqualTo(2)\n assertThat(rstStream.errorCode).isEqualTo(ErrorCode.CANCEL)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":493,"symbol":"socketExceptionWhileWritingHeaders","kind":"function","lang":"kotlin","doc":"in a consistent state so the next writer also gets an `IOException` also instead of something worse (like an [IllegalStateException]. See https://github.com/lysine-dev/okhttp/issues/1651","code":"@Test fun socketExceptionWhileWritingHeaders() {\n peer.acceptFrame() // SYN_STREAM.\n peer.play()\n val longString = repeat('a', Http2.INITIAL_MAX_FRAME_SIZE + 1)\n val socket = peer.openSocket()\n val connection =\n Http2Connection\n .Builder(true, TaskRunner.INSTANCE)\n .socket(socket.asBufferedSocket(), \"peer\")\n .pushObserver(IGNORE)\n .build()\n connection.start(sendConnectionPreface = false)\n socket.shutdownOutput()\n assertFailsWith {\n connection.newStream(headerEntries(\"a\", longString), false)\n }\n assertFailsWith {\n connection.newStream(headerEntries(\"b\", longString), false)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":514,"symbol":"clientCreatesStreamAndServerReplies","kind":"function","lang":"kotlin","code":"@Test fun clientCreatesStreamAndServerReplies() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // DATA\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.sendFrame().data(true, 3, Buffer().writeUtf8(\"robot\"), 5)\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PING\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n val out = stream.sink.buffer()\n out.writeUtf8(\"c3po\")\n out.close()\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n assertStreamData(\"robot\", stream.source)\n connection.writePingAndAwaitPong()\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.outFinished).isFalse()\n assertThat(synStream.streamId).isEqualTo(3)\n assertThat(synStream.associatedStreamId).isEqual"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":548,"symbol":"serverFinishesStreamWithHeaders","kind":"function","lang":"kotlin","code":"@Test fun serverFinishesStreamWithHeaders() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // PING\n peer.sendFrame().headers(true, 3, headerEntries(\"headers\", \"bam\"))\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"artichaut\"), false)\n connection.writePingAndAwaitPong()\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"headers\", \"bam\"))\n assertThat(stream.peekTrailers()).isEqualTo(Headers.EMPTY)\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.outFinished).isFalse()\n assertThat(synStream.streamId).isEqualTo(3)\n assertThat(synStream.associatedStreamId).isEqualTo(-1)\n assertThat(synStream.headerBlock).isEqualTo(headerEntries(\"a\", \"artichaut\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":575,"symbol":"serverWritesTrailersAndClientReadsTrailers","kind":"function","lang":"kotlin","code":"@Test fun serverWritesTrailersAndClientReadsTrailers() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"headers\", \"bam\"))\n peer.acceptFrame() // PING\n peer.sendFrame().headers(true, 3, headerEntries(\"trailers\", \"boom\"))\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"artichaut\"), false)\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"headers\", \"bam\"))\n connection.writePingAndAwaitPong()\n assertThat(stream.peekTrailers()).isEqualTo(headersOf(\"trailers\", \"boom\"))\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.outFinished).isFalse()\n assertThat(synStream.streamId).isEqualTo(3)\n assertThat(synStream.associatedStreamId).isEqualTo(-1)\n assertThat(synStream.headerBlock).isEqualT"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":604,"symbol":"serverResponseBodyRstStream","kind":"function","lang":"kotlin","doc":"A server RST_STREAM shouldn't prevent the client from consuming the response body.","code":"@Test fun serverResponseBodyRstStream() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // PING\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.sendFrame().data(true, 3, Buffer().writeUtf8(\"robot\"), 5)\n peer.sendFrame().rstStream(3, ErrorCode.NO_ERROR)\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(), false)\n connection.writePingAndAwaitPong()\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n val source = stream.source.buffer()\n assertThat(source.readUtf8(5)).isEqualTo(\"robot\")\n stream.sink.close()\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PING)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":634,"symbol":"serverTrailersRstStream","kind":"function","lang":"kotlin","doc":"A server RST_STREAM shouldn't prevent the client from consuming trailers.","code":"@Test fun serverTrailersRstStream() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // PING\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.sendFrame().headers(true, 3, headerEntries(\"z\", \"zebra\"))\n peer.sendFrame().rstStream(3, ErrorCode.NO_ERROR)\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(), true)\n connection.writePingAndAwaitPong()\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n stream.sink.close()\n assertThat(stream.peekTrailers()).isEqualTo(headersOf(\"z\", \"zebra\"))\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PING)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":666,"symbol":"clientRequestBodyServerResponseBodyRstStream","kind":"function","lang":"kotlin","doc":"A server RST_STREAM shouldn't prevent the client from consuming the response body, even if it follows a truncated request body.","code":"@Test fun clientRequestBodyServerResponseBodyRstStream() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // PING\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.sendFrame().data(true, 3, Buffer().writeUtf8(\"robot\"), 5)\n peer.sendFrame().rstStream(3, ErrorCode.NO_ERROR)\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(), true)\n connection.writePingAndAwaitPong()\n val sink = stream.sink.buffer()\n sink.writeUtf8(\"abc\")\n assertFailsWith {\n sink.close()\n }.also { expected ->\n assertThat(expected.errorCode).isEqualTo(ErrorCode.NO_ERROR)\n }\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n val source = stream.source.buffer()\n assertThat(source.readUtf8(5)).isEqualTo(\"robot\")\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFra"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":701,"symbol":"serverWritesTrailersWithData","kind":"function","lang":"kotlin","code":"@Test fun serverWritesTrailersWithData() {\n // We buffer some outbound data and headers and confirm that the END_STREAM flag comes with the\n // headers (and not with the data).\n\n // Write the mocking script. for the client\n peer.setClient(true)\n\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.sendFrame().headers(true, 3, headerEntries(\"client\", \"abc\"))\n peer.acceptFrame() // ACK\n peer.acceptFrame() // HEADERS STREAM 3\n peer.acceptFrame() // DATA STREAM 3 \"abcde\"\n peer.acceptFrame() // HEADERS STREAM 3\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), true)\n stream.enqueueTrailers(headersOf(\"foo\", \"bar\"))\n val sink = stream.sink.buffer()\n sink.writeUtf8(\"abcdefghi\")\n sink.close()\n\n // Verify the peer received what was expected.\n val headers1 = peer.takeFrame()\n assertThat(headers1.type).isEqualTo(Http2.TYPE_HEADERS)\n val data1 = peer.takeFrame()\n assertThat(data1.type).isEqualTo(Http2.TYPE_DATA)\n assertThat(data1.streamId).isEqualTo(3)\n assertArrayEquals(\"abcdefghi\".toByteArray(), data1.data)\n asse"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":738,"symbol":"clientCannotReadTrailersWithoutExhaustingStream","kind":"function","lang":"kotlin","code":"@Test fun clientCannotReadTrailersWithoutExhaustingStream() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().data(false, 3, Buffer().writeUtf8(\"robot\"), 5)\n peer.sendFrame().headers(true, 3, headerEntries(\"trailers\", \"boom\"))\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"artichaut\"), true)\n connection.writePingAndAwaitPong()\n assertThat(stream.peekTrailers()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":756,"symbol":"clientCannotReadTrailersIfTheStreamFailed","kind":"function","lang":"kotlin","code":"@Test fun clientCannotReadTrailersIfTheStreamFailed() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().rstStream(3, ErrorCode.PROTOCOL_ERROR)\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"artichaut\"), true)\n connection.writePingAndAwaitPong()\n assertFailsWith {\n stream.peekTrailers()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":775,"symbol":"serverCannotEnqueueTrailersAfterFinishingTheStream","kind":"function","lang":"kotlin","code":"@Test fun serverCannotEnqueueTrailersAfterFinishingTheStream() {\n peer.setClient(true)\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.writePingAndAwaitPong()\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), true)\n // finish the stream\n stream.writeHeaders(headerEntries(\"b\", \"berserk\"), true, false)\n assertFailsWith {\n stream.enqueueTrailers(headersOf(\"trailers\", \"boom\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":794,"symbol":"noTrailersFrameYieldsEmptyTrailers","kind":"function","lang":"kotlin","code":"@Test fun noTrailersFrameYieldsEmptyTrailers() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"headers\", \"bam\"))\n peer.sendFrame().data(true, 3, Buffer().writeUtf8(\"robot\"), 5)\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"artichaut\"), false)\n val source = stream.source.buffer()\n connection.writePingAndAwaitPong()\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"headers\", \"bam\"))\n assertThat(source.readUtf8(5)).isEqualTo(\"robot\")\n assertThat(stream.peekTrailers()).isEqualTo(Headers.EMPTY)\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.outFinished).isFalse()\n assertThat(synStream.streamId).isEqualTo(3)\n assertThat(synStream.associatedStream"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":824,"symbol":"serverReadsHeadersDataHeaders","kind":"function","lang":"kotlin","code":"@Test fun serverReadsHeadersDataHeaders() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // DATA\n peer.acceptFrame() // HEADERS\n peer.sendFrame().headers(true, 3, headerEntries(\"a\", \"android\"))\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PING\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n val out = stream.sink.buffer()\n out.writeUtf8(\"c3po\")\n out.close()\n stream.writeHeaders(headerEntries(\"e\", \"elephant\"), false, false)\n connection.writePingAndAwaitPong()\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.outFinished).isFalse()\n assertThat(synStream.streamId).isEqualTo(3)\n assertThat(synStream.associatedStreamId).isEqualTo(-1)\n assertThat(synStream.headerBlock).isEqualTo(headerEntries(\"b\", \"banana\"))\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":859,"symbol":"clientCreatesStreamAndServerRepliesWithFin","kind":"function","lang":"kotlin","code":"@Test fun clientCreatesStreamAndServerRepliesWithFin() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // PING\n peer.sendFrame().headers(true, 3, headerEntries(\"a\", \"android\"))\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.newStream(headerEntries(\"b\", \"banana\"), false)\n assertThat(connection.openStreamCount()).isEqualTo(1)\n connection.writePingAndAwaitPong() // Ensure that the SYN_REPLY has been received.\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PING)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":883,"symbol":"serverPingsClient","kind":"function","lang":"kotlin","code":"@Test fun serverPingsClient() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.sendFrame().ping(false, 2, 0)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n connect(peer)\n\n // Verify the peer received what was expected.\n val ping = peer.takeFrame()\n assertThat(ping.streamId).isEqualTo(0)\n assertThat(ping.payload1).isEqualTo(2)\n assertThat(ping.payload2).isEqualTo(0)\n assertThat(ping.ack).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":902,"symbol":"clientPingsServer","kind":"function","lang":"kotlin","code":"@Test fun clientPingsServer() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 5)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val pingAtNanos = System.nanoTime()\n connection.writePingAndAwaitPong()\n val elapsedNanos = System.nanoTime() - pingAtNanos\n assertThat(elapsedNanos).isGreaterThan(0L)\n assertThat(elapsedNanos).isLessThan(TimeUnit.SECONDS.toNanos(1))\n\n // Verify the peer received what was expected.\n val pingFrame = peer.takeFrame()\n assertThat(pingFrame.type).isEqualTo(Http2.TYPE_PING)\n assertThat(pingFrame.streamId).isEqualTo(0)\n assertThat(pingFrame.payload1).isEqualTo(Http2Connection.AWAIT_PING)\n assertThat(pingFrame.payload2).isEqualTo(0x4f4b6f6b) // OKok.\n assertThat(pingFrame.ack).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":927,"symbol":"unexpectedPongIsNotReturned","kind":"function","lang":"kotlin","code":"@Test fun unexpectedPongIsNotReturned() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.sendFrame().ping(false, 2, 0)\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, 99, 0) // This pong is silently ignored.\n peer.sendFrame().ping(false, 4, 0)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n connect(peer)\n\n // Verify the peer received what was expected.\n val ping2 = peer.takeFrame()\n assertThat(ping2.payload1).isEqualTo(2)\n val ping4 = peer.takeFrame()\n assertThat(ping4.payload1).isEqualTo(4)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":948,"symbol":"serverSendsSettingsToClient","kind":"function","lang":"kotlin","code":"@Test fun serverSendsSettingsToClient() {\n // Write the mocking script.\n val settings = Settings()\n settings[Settings.MAX_CONCURRENT_STREAMS] = 10\n peer.sendFrame().settings(settings)\n peer.acceptFrame() // ACK\n peer.sendFrame().ping(false, 2, 0)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n val maxConcurrentStreamsUpdated = CountDownLatch(1)\n val maxConcurrentStreams = AtomicInteger()\n val listener: Http2Connection.Listener =\n object : Http2Connection.Listener() {\n override fun onStream(stream: Http2Stream): Unit = throw AssertionError()\n\n override fun onSettings(\n connection: Http2Connection,\n settings: Settings,\n ) {\n maxConcurrentStreams.set(settings.getMaxConcurrentStreams())\n maxConcurrentStreamsUpdated.countDown()\n }\n }\n val connection = connect(peer, IGNORE, listener)\n connection.withLock {\n assertThat(connection.peerSettings.getMaxConcurrentStreams()).isEqualTo(10)\n }\n maxConcurrentStreamsUpdated.await()\n assertThat(maxConcurrentStreams.get()).isEqualTo(10)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":963,"symbol":"onStream","kind":"function","lang":"kotlin","code":"override fun onStream(stream: Http2Stream): Unit = throw AssertionError()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":965,"symbol":"onSettings","kind":"function","lang":"kotlin","code":"override fun onSettings(\n connection: Http2Connection,\n settings: Settings,\n ) {\n maxConcurrentStreams.set(settings.getMaxConcurrentStreams())\n maxConcurrentStreamsUpdated.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":981,"symbol":"multipleSettingsFramesAreMerged","kind":"function","lang":"kotlin","code":"@Test fun multipleSettingsFramesAreMerged() {\n // Write the mocking script.\n val settings1 = Settings()\n settings1[Settings.HEADER_TABLE_SIZE] = 10000\n settings1[Settings.INITIAL_WINDOW_SIZE] = 20000\n settings1[Settings.MAX_FRAME_SIZE] = 30000\n peer.sendFrame().settings(settings1)\n peer.acceptFrame() // ACK SETTINGS\n val settings2 = Settings()\n settings2[Settings.INITIAL_WINDOW_SIZE] = 40000\n settings2[Settings.MAX_FRAME_SIZE] = 50000\n settings2[Settings.MAX_CONCURRENT_STREAMS] = 60000\n peer.sendFrame().settings(settings2)\n peer.acceptFrame() // ACK SETTINGS\n peer.sendFrame().ping(false, 2, 0)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_SETTINGS)\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_PING)\n connection.withLock {\n assertThat(connection.peerSettings.headerTableSize).isEqualTo(10000)\n assertThat(connection.peerSettings.initialWindowSize).isEqualTo(40000)\n assertThat(connection.peerSettings.getMaxFrameSize(-1)).isEqualTo(50000)\n assertThat(connection.peerSettings.getMaxConcurrentStrea"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1011,"symbol":"clearSettingsBeforeMerge","kind":"function","lang":"kotlin","code":"@Test fun clearSettingsBeforeMerge() {\n // Write the mocking script.\n val settings1 = Settings()\n settings1[Settings.HEADER_TABLE_SIZE] = 10000\n settings1[Settings.INITIAL_WINDOW_SIZE] = 20000\n settings1[Settings.MAX_FRAME_SIZE] = 30000\n peer.sendFrame().settings(settings1)\n peer.acceptFrame() // ACK\n peer.sendFrame().ping(false, 2, 0)\n peer.acceptFrame()\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n\n // fake a settings frame with clear flag set.\n val settings2 = Settings()\n settings2[Settings.MAX_CONCURRENT_STREAMS] = 60000\n connection.readerRunnable.applyAndAckSettings(true, settings2)\n connection.withLock {\n assertThat(connection.peerSettings.headerTableSize).isEqualTo(-1)\n assertThat(connection.peerSettings.initialWindowSize)\n .isEqualTo(Settings.DEFAULT_INITIAL_WINDOW_SIZE)\n assertThat(connection.peerSettings.getMaxFrameSize(-1)).isEqualTo(-1)\n assertThat(connection.peerSettings.getMaxConcurrentStreams()).isEqualTo(60000)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1039,"symbol":"bogusDataFrameDoesNotDisruptConnection","kind":"function","lang":"kotlin","code":"@Test fun bogusDataFrameDoesNotDisruptConnection() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.sendFrame().data(true, 41, Buffer().writeUtf8(\"bogus\"), 5)\n peer.acceptFrame() // RST_STREAM\n peer.sendFrame().ping(false, 2, 0)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n connect(peer)\n\n // Verify the peer received what was expected.\n val rstStream = peer.takeFrame()\n assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM)\n assertThat(rstStream.streamId).isEqualTo(41)\n assertThat(rstStream.errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR)\n val ping = peer.takeFrame()\n assertThat(ping.payload1).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1061,"symbol":"bogusReplySilentlyIgnored","kind":"function","lang":"kotlin","code":"@Test fun bogusReplySilentlyIgnored() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.sendFrame().headers(false, 41, headerEntries(\"a\", \"android\"))\n peer.sendFrame().ping(false, 2, 0)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n connect(peer)\n\n // Verify the peer received what was expected.\n val ping = peer.takeFrame()\n assertThat(ping.payload1).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1078,"symbol":"serverClosesClientOutputStream","kind":"function","lang":"kotlin","code":"@Test fun serverClosesClientOutputStream() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().rstStream(3, ErrorCode.CANCEL)\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), true)\n val out = stream.sink.buffer()\n connection.writePingAndAwaitPong() // Ensure that the RST_CANCEL has been received.\n assertFailsWith {\n out.writeUtf8(\"square\")\n out.flush()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream was reset: CANCEL\")\n }\n // Close throws because buffered data wasn't flushed.\n assertFailsWith {\n out.close()\n }\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.inFinished).isFalse()\n assertThat(synStream.outFinished)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1117,"symbol":"clientClosesClientInputStream","kind":"function","lang":"kotlin","doc":"Test that the client sends a RST_STREAM if doing so won't disrupt the output stream.","code":"@Test fun clientClosesClientInputStream() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // RST_STREAM\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), false)\n val source = stream.source\n val out = stream.sink.buffer()\n source.close()\n assertFailsWith {\n source.read(Buffer(), 1)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream closed\")\n }\n assertFailsWith {\n out.writeUtf8(\"a\")\n out.flush()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream finished\")\n }\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.inFinished).isTrue()\n assertThat(synStream.outFinished).isFalse()\n val rstStream = peer.takeFrame()\n assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM)\n asse"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1157,"symbol":"clientClosesClientInputStreamIfOutputStreamIsClosed","kind":"function","lang":"kotlin","doc":"Test that the client doesn't send a RST_STREAM if doing so will disrupt the output stream.","code":"@Test fun clientClosesClientInputStreamIfOutputStreamIsClosed() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // DATA\n peer.acceptFrame() // DATA with FLAG_FIN\n peer.acceptFrame() // RST_STREAM\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), true)\n val source = stream.source\n val out = stream.sink.buffer()\n source.close()\n assertFailsWith {\n source.read(Buffer(), 1)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream closed\")\n }\n out.writeUtf8(\"square\")\n out.flush()\n out.close()\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.inFinished).isFalse()\n assertThat(synStream.outFinished).isFalse()\n val data = peer.takeFrame()\n assertThat(data.type).isEqualTo(Http2.TYPE_DATA)\n assertArrayEquals(\"square\".toByteAr"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1200,"symbol":"serverClosesClientInputStream","kind":"function","lang":"kotlin","code":"@Test fun serverClosesClientInputStream() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"b\", \"banana\"))\n peer.sendFrame().data(true, 3, Buffer().writeUtf8(\"square\"), 6)\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), false)\n val source = stream.source\n assertStreamData(\"square\", source)\n connection.writePingAndAwaitPong() // Ensure that inFinished has been received.\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(synStream.inFinished).isTrue()\n assertThat(synStream.outFinished).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1226,"symbol":"remoteDoubleSynReply","kind":"function","lang":"kotlin","code":"@Test fun remoteDoubleSynReply() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.acceptFrame() // PING\n peer.sendFrame().headers(false, 3, headerEntries(\"b\", \"banana\"))\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"c\", \"cola\"), false)\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n connection.writePingAndAwaitPong() // Ensure that the 2nd SYN REPLY has been received.\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PING)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1250,"symbol":"remoteSendsDataAfterInFinished","kind":"function","lang":"kotlin","code":"@Test fun remoteSendsDataAfterInFinished() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.sendFrame().data(true, 3, Buffer().writeUtf8(\"robot\"), 5)\n peer.sendFrame().data(true, 3, Buffer().writeUtf8(\"c3po\"), 4)\n peer.acceptFrame() // RST_STREAM\n peer.sendFrame().ping(false, 2, 0) // Ping just to make sure the stream was fastforwarded.\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), false)\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n assertStreamData(\"robot\", stream.source)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n val rstStream = peer.takeFrame()\n assertThat(rstStream.type).isEqualTo(Http2.TYPE_RST_STREAM)\n assertThat(rstStream.streamId).isEqualTo(3)\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PI"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1280,"symbol":"clientDoesNotLimitFlowControl","kind":"function","lang":"kotlin","code":"@Test fun clientDoesNotLimitFlowControl() {\n val dataLength = 16384\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"b\", \"banana\"))\n peer.sendFrame().data(false, 3, Buffer().write(ByteArray(dataLength)), dataLength)\n peer.sendFrame().data(false, 3, Buffer().write(ByteArray(dataLength)), dataLength)\n peer.sendFrame().data(false, 3, Buffer().write(ByteArray(dataLength)), dataLength)\n peer.sendFrame().data(false, 3, Buffer().write(ByteArray(dataLength)), dataLength)\n peer.sendFrame().data(false, 3, Buffer().write(ByteArray(1)), 1)\n peer.sendFrame().ping(false, 2, 0) // Ping just to make sure the stream was fastforwarded.\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), false)\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"b\", \"banana\"))\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1309,"symbol":"remoteSendsRefusedStreamBeforeReplyHeaders","kind":"function","lang":"kotlin","code":"@Test fun remoteSendsRefusedStreamBeforeReplyHeaders() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().rstStream(3, ErrorCode.REFUSED_STREAM)\n peer.sendFrame().ping(false, 2, 0)\n peer.acceptFrame() // PING\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), false)\n assertFailsWith {\n stream.takeHeaders()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream was reset: REFUSED_STREAM\")\n }\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PING)\n assertThat(ping.payload1).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1337,"symbol":"receiveGoAway","kind":"function","lang":"kotlin","code":"@Test fun receiveGoAway() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM 1\n peer.acceptFrame() // SYN_STREAM 3\n peer.acceptFrame() // PING.\n peer.sendFrame().goAway(3, ErrorCode.PROTOCOL_ERROR, EMPTY_BYTE_ARRAY)\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.acceptFrame() // DATA STREAM 1\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream1 = connection.newStream(headerEntries(\"a\", \"android\"), true)\n val stream2 = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n connection.writePingAndAwaitPong() // Ensure the GO_AWAY that resets stream2 has been received.\n val sink1 = stream1.sink.buffer()\n val sink2 = stream2.sink.buffer()\n sink1.writeUtf8(\"abc\")\n assertFailsWith {\n sink2.writeUtf8(\"abc\")\n sink2.flush()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream was reset: REFUSED_STREAM\")\n }\n sink1.writeUtf8(\"def\")\n sink1.close()\n assertFailsWith {\n connection.newStream(headerEntries(\"c\", \"cola\"), false"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1385,"symbol":"sendGoAway","kind":"function","lang":"kotlin","code":"@Test fun sendGoAway() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM 1\n peer.acceptFrame() // GOAWAY\n peer.acceptFrame() // PING\n peer.sendFrame().headers(false, 2, headerEntries(\"b\", \"b\")) // Should be ignored!\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.newStream(headerEntries(\"a\", \"android\"), false)\n connection.withLock {\n if (!connection.isHealthy(System.nanoTime())) {\n throw ConnectionShutdownException()\n }\n }\n connection.writePing()\n connection.shutdown(ErrorCode.PROTOCOL_ERROR)\n assertThat(connection.openStreamCount()).isEqualTo(1)\n connection.awaitPong() // Prevent the peer from exiting prematurely.\n\n // Verify the peer received what was expected.\n val synStream1 = peer.takeFrame()\n assertThat(synStream1.type).isEqualTo(Http2.TYPE_HEADERS)\n val pingFrame = peer.takeFrame()\n assertThat(pingFrame.type).isEqualTo(Http2.TYPE_PING)\n val goaway = peer.takeFrame()\n assertThat(goaway.type).isEqualTo(Http2.TYPE_GOAWAY"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1420,"symbol":"close","kind":"function","lang":"kotlin","code":"@Test fun close() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // GOAWAY\n peer.acceptFrame() // RST_STREAM\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"a\", \"android\"), false)\n assertThat(connection.openStreamCount()).isEqualTo(1)\n connection.close()\n assertThat(connection.openStreamCount()).isEqualTo(0)\n assertFailsWith {\n connection.newStream(headerEntries(\"b\", \"banana\"), false)\n }\n val sink = stream.sink.buffer()\n assertFailsWith {\n sink.writeByte(0)\n sink.flush()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream finished\")\n }\n assertFailsWith {\n stream.source.read(Buffer(), 1)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"stream was reset: CANCEL\")\n }\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n val goaway = peer.t"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1461,"symbol":"getResponseHeadersTimesOut","kind":"function","lang":"kotlin","code":"@Test fun getResponseHeadersTimesOut() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // RST_STREAM\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), false)\n stream.readTimeout().timeout(500, TimeUnit.MILLISECONDS)\n val startNanos = System.nanoTime()\n assertFailsWith {\n stream.takeHeaders()\n }\n val elapsedNanos = System.nanoTime() - startNanos\n awaitWatchdogIdle()\n // 200ms delta\n assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedNanos).toDouble())\n .isCloseTo(500.0, 200.0)\n assertThat(connection.openStreamCount()).isEqualTo(0)\n\n // Verify the peer received what was expected.\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_RST_STREAM)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1494,"symbol":"readTimesOut","kind":"function","lang":"kotlin","doc":"Confirm that the client times out if the server stalls after 3 bytes. After the timeout the connection is still considered healthy while we await the degraded pong. When that doesn't arrive the connection goes unhealthy.","code":"@Test fun readTimesOut() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.sendFrame().data(false, 3, Buffer().writeUtf8(\"abc\"), 3)\n peer.acceptFrame() // RST_STREAM\n peer.acceptFrame() // DEGRADED PING\n peer.acceptFrame() // AWAIT PING\n peer.sendFrame().ping(true, Http2Connection.DEGRADED_PING, 1) // DEGRADED PONG\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // AWAIT PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), false)\n stream.readTimeout().timeout(500, TimeUnit.MILLISECONDS)\n val source = stream.source.buffer()\n source.require(3)\n val startNanos = System.nanoTime()\n assertFailsWith {\n source.require(4)\n }\n val elapsedNanos = System.nanoTime() - startNanos\n awaitWatchdogIdle()\n // 200ms delta\n assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedNanos).toDouble())\n .isCloseTo(500.0, 200.0)\n assertThat(connection.openStream"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1543,"symbol":"writeTimesOutAwaitingStreamWindow","kind":"function","lang":"kotlin","code":"@Test fun writeTimesOutAwaitingStreamWindow() {\n // Set the peer's receive window to 5 bytes!\n val peerSettings = Settings().set(Settings.INITIAL_WINDOW_SIZE, 5)\n\n // Write the mocking script.\n peer.sendFrame().settings(peerSettings)\n peer.acceptFrame() // ACK SETTINGS\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.acceptFrame() // DATA\n peer.acceptFrame() // RST_STREAM\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.writePingAndAwaitPong() // Make sure settings have been received.\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n val sink = stream.sink\n sink.write(Buffer().writeUtf8(\"abcde\"), 5)\n stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS)\n val startNanos = System.nanoTime()\n sink.write(Buffer().writeUtf8(\"f\"), 1)\n assertFailsWith {\n sink.flush() // This will time out waiting on the write window.\n }\n val elapsedNanos = System.nanoTime() - startNanos\n awaitWatchdogIdle()\n"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1584,"symbol":"writeTimesOutAwaitingConnectionWindow","kind":"function","lang":"kotlin","code":"@Test fun writeTimesOutAwaitingConnectionWindow() {\n // Set the peer's receive window to 5 bytes. Give the stream 5 bytes back, so only the\n // connection-level window is applicable.\n val peerSettings = Settings().set(Settings.INITIAL_WINDOW_SIZE, 5)\n\n // Write the mocking script.\n peer.sendFrame().settings(peerSettings)\n peer.acceptFrame() // ACK SETTINGS\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.acceptFrame() // PING\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.acceptFrame() // DATA\n peer.acceptFrame() // RST_STREAM\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.writePingAndAwaitPong() // Make sure settings have been acked.\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n connection.writePingAndAwaitPong() // Make sure the window update has been received.\n val sink = stream.sink\n stream.writeTimeout().timeout(500, TimeUnit.MILLISECONDS)\n sink.write(Buffer().writeUtf8(\"abcdef\"), 6)\n val s"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1629,"symbol":"outgoingWritesAreBatched","kind":"function","lang":"kotlin","code":"@Test fun outgoingWritesAreBatched() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.acceptFrame() // DATA\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n\n // two outgoing writes\n val sink = stream.sink\n sink.write(Buffer().writeUtf8(\"abcde\"), 5)\n sink.write(Buffer().writeUtf8(\"fghij\"), 5)\n sink.close()\n\n // verify the peer received one incoming frame\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS)\n val data = peer.takeFrame()\n assertThat(data.type).isEqualTo(Http2.TYPE_DATA)\n assertArrayEquals(\"abcdefghij\".toByteArray(), data.data)\n assertThat(data.inFinished).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1656,"symbol":"headers","kind":"function","lang":"kotlin","code":"@Test fun headers() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.acceptFrame() // PING\n peer\n .sendFrame()\n .headers(false, 3, headerEntries(Header.RESPONSE_STATUS_UTF8, \"HTTP/1.1 100\"))\n peer\n .sendFrame()\n .headers(false, 3, headerEntries(Header.RESPONSE_STATUS_UTF8, \"HTTP/1.1 200\"))\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n connection.writePingAndAwaitPong() // Ensure that the HEADERS has been received.\n assertThat(stream.takeHeaders())\n .isEqualTo(headersOf(Header.RESPONSE_STATUS_UTF8, \"HTTP/1.1 100\"))\n assertThat(stream.takeHeaders())\n .isEqualTo(headersOf(Header.RESPONSE_STATUS_UTF8, \"HTTP/1.1 200\"))\n\n // Verify the peer received what was expected.\n val synStream = peer.takeFrame()\n assertThat(synStream.type).isEqualTo(Http2.TYPE_HEADERS)\n val ping = peer.takeFrame()\n assertThat(ping.type).isEqualTo(Http2.TYPE_PING)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1687,"symbol":"readMultipleSetsOfResponseHeaders","kind":"function","lang":"kotlin","code":"@Test fun readMultipleSetsOfResponseHeaders() {\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n peer.acceptFrame() // PING\n peer.sendFrame().headers(true, 3, headerEntries(\"c\", \"cola\"))\n peer.sendFrame().ping(true, Http2Connection.AWAIT_PING, 0) // PONG\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), true)\n stream.connection.flush()\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n connection.writePingAndAwaitPong()\n assertThat(stream.peekTrailers()).isEqualTo(headersOf(\"c\", \"cola\"))\n\n // Verify the peer received what was expected.\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_HEADERS)\n assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_PING)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt","line":1711,"symbol":"readSendsWindowUpdate","kind":"function","lang":"kotlin","code":"@Test fun readSendsWindowUpdate() {\n val windowSize = 100\n val windowUpdateThreshold = 50\n\n // Write the mocking script.\n peer.sendFrame().settings(Settings())\n peer.acceptFrame() // ACK\n peer.acceptFrame() // SYN_STREAM\n peer.sendFrame().headers(false, 3, headerEntries(\"a\", \"android\"))\n for (i in 0..2) {\n // Send frames of summing to size 50, which is windowUpdateThreshold.\n peer.sendFrame().data(false, 3, data(24), 24)\n peer.sendFrame().data(false, 3, data(25), 25)\n peer.sendFrame().data(false, 3, data(1), 1)\n peer.acceptFrame() // connection WINDOW UPDATE\n peer.acceptFrame() // stream WINDOW UPDATE\n }\n peer.sendFrame().data(true, 3, data(0), 0)\n peer.play()\n\n // Play it back.\n val connection = connect(peer)\n connection.okHttpSettings[Settings.INITIAL_WINDOW_SIZE] = windowSize\n val stream = connection.newStream(headerEntries(\"b\", \"banana\"), false)\n assertThat(stream.readBytes.acknowledged).isEqualTo(0L)\n assertThat(stream.readBytes.total).isEqualTo(0L)\n assertThat(stream.takeHeaders()).isEqualTo(headersOf(\"a\", \"android\"))\n val source = stream.source\n val buffer = Buffer()\n buffer.writeAll"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":46,"symbol":"Http2Test","kind":"class","lang":"kotlin","code":"class Http2Test {\n val frame = Buffer()\n val reader = Http2Reader(frame, false)\n val expectedStreamId = 15\n\n @Test fun unknownFrameTypeSkipped() {\n writeMedium(frame, 4) // has a 4-byte field\n frame.writeByte(99) // type 99\n frame.writeByte(FLAG_NONE)\n frame.writeInt(expectedStreamId)\n frame.writeInt(111111111) // custom data\n reader.nextFrame(requireSettings = false, BaseTestHandler()) // Should not callback.\n }\n\n @Test fun onlyOneLiteralHeadersFrame() {\n val sentHeaders = headerEntries(\"name\", \"value\")\n val headerBytes = literalHeaders(sentHeaders)\n writeMedium(frame, headerBytes.size.toInt())\n frame.writeByte(Http2.TYPE_HEADERS)\n frame.writeByte(FLAG_END_HEADERS or FLAG_END_STREAM)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeAll(headerBytes)\n\n // Check writer sends the same bytes.\n assertThat(sendHeaderFrames(true, sentHeaders)).isEqualTo(frame)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n ass"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":51,"symbol":"unknownFrameTypeSkipped","kind":"function","lang":"kotlin","code":"@Test fun unknownFrameTypeSkipped() {\n writeMedium(frame, 4) // has a 4-byte field\n frame.writeByte(99) // type 99\n frame.writeByte(FLAG_NONE)\n frame.writeInt(expectedStreamId)\n frame.writeInt(111111111) // custom data\n reader.nextFrame(requireSettings = false, BaseTestHandler()) // Should not callback.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":60,"symbol":"onlyOneLiteralHeadersFrame","kind":"function","lang":"kotlin","code":"@Test fun onlyOneLiteralHeadersFrame() {\n val sentHeaders = headerEntries(\"name\", \"value\")\n val headerBytes = literalHeaders(sentHeaders)\n writeMedium(frame, headerBytes.size.toInt())\n frame.writeByte(Http2.TYPE_HEADERS)\n frame.writeByte(FLAG_END_HEADERS or FLAG_END_STREAM)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeAll(headerBytes)\n\n // Check writer sends the same bytes.\n assertThat(sendHeaderFrames(true, sentHeaders)).isEqualTo(frame)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n assertThat(inFinished).isTrue()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(associatedStreamId).isEqualTo(-1)\n assertThat(headerBlock).isEqualTo(sentHeaders)\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":74,"symbol":"headers","kind":"function","lang":"kotlin","code":"override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n assertThat(inFinished).isTrue()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(associatedStreamId).isEqualTo(-1)\n assertThat(headerBlock).isEqualTo(sentHeaders)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":89,"symbol":"headersWithPriority","kind":"function","lang":"kotlin","code":"@Test fun headersWithPriority() {\n val sentHeaders = headerEntries(\"name\", \"value\")\n val headerBytes = literalHeaders(sentHeaders)\n writeMedium(frame, (headerBytes.size + 5).toInt())\n frame.writeByte(Http2.TYPE_HEADERS)\n frame.writeByte(FLAG_END_HEADERS or FLAG_PRIORITY)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeInt(0) // Independent stream.\n frame.writeByte(255) // Heaviest weight, zero-indexed.\n frame.writeAll(headerBytes)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun priority(\n streamId: Int,\n streamDependency: Int,\n weight: Int,\n exclusive: Boolean,\n ) {\n assertThat(streamDependency).isEqualTo(0)\n assertThat(weight).isEqualTo(256)\n assertThat(exclusive).isFalse()\n }\n\n override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(associatedStreamId).isEqualTo(-1)\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":102,"symbol":"priority","kind":"function","lang":"kotlin","code":"override fun priority(\n streamId: Int,\n streamDependency: Int,\n weight: Int,\n exclusive: Boolean,\n ) {\n assertThat(streamDependency).isEqualTo(0)\n assertThat(weight).isEqualTo(256)\n assertThat(exclusive).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":113,"symbol":"headers","kind":"function","lang":"kotlin","code":"override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(associatedStreamId).isEqualTo(-1)\n assertThat(headerBlock).isEqualTo(sentHeaders)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":129,"symbol":"headersFrameThenContinuation","kind":"function","lang":"kotlin","doc":"Headers are compressed, then framed.","code":"@Test fun headersFrameThenContinuation() {\n val sentHeaders = largeHeaders()\n val headerBlock = literalHeaders(sentHeaders)\n\n // Write the first headers frame.\n writeMedium(frame, Http2.INITIAL_MAX_FRAME_SIZE)\n frame.writeByte(Http2.TYPE_HEADERS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.write(headerBlock, Http2.INITIAL_MAX_FRAME_SIZE.toLong())\n\n // Write the continuation frame, specifying no more frames are expected.\n writeMedium(frame, headerBlock.size.toInt())\n frame.writeByte(Http2.TYPE_CONTINUATION)\n frame.writeByte(FLAG_END_HEADERS)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeAll(headerBlock)\n\n // Check writer sends the same bytes.\n assertThat(sendHeaderFrames(false, sentHeaders)).isEqualTo(frame)\n\n // Reading the above frames should result in a concatenated headerBlock.\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n assertThat(inFinished).isFalse()\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":154,"symbol":"headers","kind":"function","lang":"kotlin","code":"override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(associatedStreamId).isEqualTo(-1)\n assertThat(headerBlock).isEqualTo(sentHeaders)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":169,"symbol":"pushPromise","kind":"function","lang":"kotlin","code":"@Test fun pushPromise() {\n val expectedPromisedStreamId = 11\n val pushPromise =\n listOf(\n Header(Header.TARGET_METHOD, \"GET\"),\n Header(Header.TARGET_SCHEME, \"https\"),\n Header(Header.TARGET_AUTHORITY, \"squareup.com\"),\n Header(Header.TARGET_PATH, \"/\"),\n )\n\n // Write the push promise frame, specifying the associated stream ID.\n val headerBytes = literalHeaders(pushPromise)\n writeMedium(frame, (headerBytes.size + 4).toInt())\n frame.writeByte(Http2.TYPE_PUSH_PROMISE)\n frame.writeByte(Http2.FLAG_END_PUSH_PROMISE)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeInt(expectedPromisedStreamId and 0x7fffffff)\n frame.writeAll(headerBytes)\n assertThat(sendPushPromiseFrames(expectedPromisedStreamId, pushPromise)).isEqualTo(\n frame,\n )\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun pushPromise(\n streamId: Int,\n promisedStreamId: Int,\n requestHeaders: List
,\n ) {\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(promisedStreamId).isEqualTo(expectedPromisedStreamId)\n a"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":193,"symbol":"pushPromise","kind":"function","lang":"kotlin","code":"override fun pushPromise(\n streamId: Int,\n promisedStreamId: Int,\n requestHeaders: List
,\n ) {\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(promisedStreamId).isEqualTo(expectedPromisedStreamId)\n assertThat(requestHeaders).isEqualTo(pushPromise)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":207,"symbol":"pushPromiseThenContinuation","kind":"function","lang":"kotlin","doc":"Headers are compressed, then framed.","code":"@Test fun pushPromiseThenContinuation() {\n val expectedPromisedStreamId = 11\n val pushPromise = largeHeaders()\n\n // Decoding the first header will cross frame boundaries.\n val headerBlock = literalHeaders(pushPromise)\n\n // Write the first headers frame.\n writeMedium(frame, Http2.INITIAL_MAX_FRAME_SIZE)\n frame.writeByte(Http2.TYPE_PUSH_PROMISE)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeInt(expectedPromisedStreamId and 0x7fffffff)\n frame.write(headerBlock, (Http2.INITIAL_MAX_FRAME_SIZE - 4).toLong())\n\n // Write the continuation frame, specifying no more frames are expected.\n writeMedium(frame, headerBlock.size.toInt())\n frame.writeByte(Http2.TYPE_CONTINUATION)\n frame.writeByte(FLAG_END_HEADERS)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeAll(headerBlock)\n assertThat(sendPushPromiseFrames(expectedPromisedStreamId, pushPromise)).isEqualTo(\n frame,\n )\n\n // Reading the above frames should result in a concatenated headerBlock.\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun pushPromise(\n strea"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":236,"symbol":"pushPromise","kind":"function","lang":"kotlin","code":"override fun pushPromise(\n streamId: Int,\n promisedStreamId: Int,\n requestHeaders: List
,\n ) {\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(promisedStreamId).isEqualTo(expectedPromisedStreamId)\n assertThat(requestHeaders).isEqualTo(pushPromise)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":249,"symbol":"readRstStreamFrame","kind":"function","lang":"kotlin","code":"@Test fun readRstStreamFrame() {\n writeMedium(frame, 4)\n frame.writeByte(Http2.TYPE_RST_STREAM)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeInt(ErrorCode.PROTOCOL_ERROR.httpCode)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR)\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":258,"symbol":"rstStream","kind":"function","lang":"kotlin","code":"override fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":269,"symbol":"readSettingsFrame","kind":"function","lang":"kotlin","code":"@Test fun readSettingsFrame() {\n val reducedTableSizeBytes = 16\n writeMedium(frame, 12) // 2 settings * 6 bytes (2 for the code and 4 for the value).\n frame.writeByte(Http2.TYPE_SETTINGS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // Settings are always on the connection stream 0.\n frame.writeShort(1) // SETTINGS_HEADER_TABLE_SIZE\n frame.writeInt(reducedTableSizeBytes)\n frame.writeShort(2) // SETTINGS_ENABLE_PUSH\n frame.writeInt(0)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n // No clearPrevious in HTTP/2.\n assertThat(clearPrevious).isFalse()\n assertThat(settings.headerTableSize).isEqualTo(reducedTableSizeBytes)\n assertThat(settings.getEnablePush(true)).isFalse()\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":282,"symbol":"settings","kind":"function","lang":"kotlin","code":"override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n // No clearPrevious in HTTP/2.\n assertThat(clearPrevious).isFalse()\n assertThat(settings.headerTableSize).isEqualTo(reducedTableSizeBytes)\n assertThat(settings.getEnablePush(true)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":295,"symbol":"readSettingsFrameInvalidPushValue","kind":"function","lang":"kotlin","code":"@Test fun readSettingsFrameInvalidPushValue() {\n writeMedium(frame, 6) // 2 for the code and 4 for the value\n frame.writeByte(Http2.TYPE_SETTINGS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // Settings are always on the connection stream 0.\n frame.writeShort(2)\n frame.writeInt(2)\n assertFailsWith {\n reader.nextFrame(requireSettings = false, BaseTestHandler())\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"PROTOCOL_ERROR SETTINGS_ENABLE_PUSH != 0 or 1\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":309,"symbol":"readSettingsFrameUnknownSettingId","kind":"function","lang":"kotlin","code":"@Test fun readSettingsFrameUnknownSettingId() {\n writeMedium(frame, 6) // 2 for the code and 4 for the value\n frame.writeByte(Http2.TYPE_SETTINGS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // Settings are always on the connection stream 0.\n frame.writeShort(7) // old number for SETTINGS_INITIAL_WINDOW_SIZE\n frame.writeInt(1)\n val settingValue = AtomicInteger()\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n settingValue.set(settings[7])\n }\n },\n )\n assertThat(1).isEqualTo(settingValue.toInt())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":320,"symbol":"settings","kind":"function","lang":"kotlin","code":"override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n settingValue.set(settings[7])\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":331,"symbol":"readSettingsFrameExperimentalId","kind":"function","lang":"kotlin","code":"@Test fun readSettingsFrameExperimentalId() {\n writeMedium(frame, 6) // 2 for the code and 4 for the value\n frame.writeByte(Http2.TYPE_SETTINGS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // Settings are always on the connection stream 0.\n frame.write(\"f000\".decodeHex()) // Id reserved for experimental use.\n frame.writeInt(1)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n // no-op\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":341,"symbol":"settings","kind":"function","lang":"kotlin","code":"override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n // no-op\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":351,"symbol":"readSettingsFrameNegativeWindowSize","kind":"function","lang":"kotlin","code":"@Test fun readSettingsFrameNegativeWindowSize() {\n writeMedium(frame, 6) // 2 for the code and 4 for the value\n frame.writeByte(Http2.TYPE_SETTINGS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // Settings are always on the connection stream 0.\n frame.writeShort(4) // SETTINGS_INITIAL_WINDOW_SIZE\n frame.writeInt(Int.MIN_VALUE)\n assertFailsWith {\n reader.nextFrame(requireSettings = false, BaseTestHandler())\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"PROTOCOL_ERROR SETTINGS_INITIAL_WINDOW_SIZE > 2^31 - 1\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":367,"symbol":"readSettingsFrameNegativeFrameLength","kind":"function","lang":"kotlin","code":"@Test fun readSettingsFrameNegativeFrameLength() {\n writeMedium(frame, 6) // 2 for the code and 4 for the value\n frame.writeByte(Http2.TYPE_SETTINGS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // Settings are always on the connection stream 0.\n frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE\n frame.writeInt(Int.MIN_VALUE)\n assertFailsWith {\n reader.nextFrame(requireSettings = false, BaseTestHandler())\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: -2147483648\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":383,"symbol":"readSettingsFrameTooShortFrameLength","kind":"function","lang":"kotlin","code":"@Test fun readSettingsFrameTooShortFrameLength() {\n writeMedium(frame, 6) // 2 for the code and 4 for the value\n frame.writeByte(Http2.TYPE_SETTINGS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // Settings are always on the connection stream 0.\n frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE\n frame.writeInt(2.0.pow(14.0).toInt() - 1)\n assertFailsWith {\n reader.nextFrame(requireSettings = false, BaseTestHandler())\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16383\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":397,"symbol":"readSettingsFrameTooLongFrameLength","kind":"function","lang":"kotlin","code":"@Test fun readSettingsFrameTooLongFrameLength() {\n writeMedium(frame, 6) // 2 for the code and 4 for the value\n frame.writeByte(Http2.TYPE_SETTINGS)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // Settings are always on the connection stream 0.\n frame.writeShort(5) // SETTINGS_MAX_FRAME_SIZE\n frame.writeInt(2.0.pow(24.0).toInt())\n assertFailsWith {\n reader.nextFrame(requireSettings = false, BaseTestHandler())\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"PROTOCOL_ERROR SETTINGS_MAX_FRAME_SIZE: 16777216\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":411,"symbol":"pingRoundTrip","kind":"function","lang":"kotlin","code":"@Test fun pingRoundTrip() {\n val expectedPayload1 = 7\n val expectedPayload2 = 8\n writeMedium(frame, 8) // length\n frame.writeByte(Http2.TYPE_PING)\n frame.writeByte(Http2.FLAG_ACK)\n frame.writeInt(0) // connection-level\n frame.writeInt(expectedPayload1)\n frame.writeInt(expectedPayload2)\n\n // Check writer sends the same bytes.\n assertThat(sendPingFrame(true, expectedPayload1, expectedPayload2)).isEqualTo(frame)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n ) {\n assertThat(ack).isTrue()\n assertThat(payload1).isEqualTo(expectedPayload1)\n assertThat(payload2).isEqualTo(expectedPayload2)\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":426,"symbol":"ping","kind":"function","lang":"kotlin","code":"override fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n ) {\n assertThat(ack).isTrue()\n assertThat(payload1).isEqualTo(expectedPayload1)\n assertThat(payload2).isEqualTo(expectedPayload2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":439,"symbol":"maxLengthDataFrame","kind":"function","lang":"kotlin","code":"@Test fun maxLengthDataFrame() {\n val expectedData = ByteArray(Http2.INITIAL_MAX_FRAME_SIZE)\n Arrays.fill(expectedData, 2.toByte())\n writeMedium(frame, expectedData.size)\n frame.writeByte(Http2.TYPE_DATA)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.write(expectedData)\n\n // Check writer sends the same bytes.\n assertThat(sendDataFrame(Buffer().write(expectedData))).isEqualTo(frame)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(length).isEqualTo(Http2.INITIAL_MAX_FRAME_SIZE)\n val data = source.readByteString(length.toLong())\n for (b in data.toByteArray()) {\n assertThat(b).isEqualTo(2.toByte())\n }\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":453,"symbol":"data","kind":"function","lang":"kotlin","code":"override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(length).isEqualTo(Http2.INITIAL_MAX_FRAME_SIZE)\n val data = source.readByteString(length.toLong())\n for (b in data.toByteArray()) {\n assertThat(b).isEqualTo(2.toByte())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":471,"symbol":"dataFrameNotAssociateWithStream","kind":"function","lang":"kotlin","code":"@Test fun dataFrameNotAssociateWithStream() {\n val payload = byteArrayOf(0x01, 0x02)\n writeMedium(frame, payload.size)\n frame.writeByte(Http2.TYPE_DATA)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0)\n frame.write(payload)\n assertFailsWith {\n reader.nextFrame(requireSettings = false, BaseTestHandler())\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"PROTOCOL_ERROR: TYPE_DATA streamId == 0\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":486,"symbol":"compressedDataFrameWhenSettingDisabled","kind":"function","lang":"kotlin","doc":"We do not send SETTINGS_COMPRESS_DATA = 1, nor want to. Let's make sure we error.","code":"@Test fun compressedDataFrameWhenSettingDisabled() {\n val expectedData = ByteArray(Http2.INITIAL_MAX_FRAME_SIZE)\n Arrays.fill(expectedData, 2.toByte())\n val zipped = gzip(expectedData)\n val zippedSize = zipped.size.toInt()\n writeMedium(frame, zippedSize)\n frame.writeByte(Http2.TYPE_DATA)\n frame.writeByte(FLAG_COMPRESSED)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n zipped.readAll(frame)\n assertFailsWith {\n reader.nextFrame(requireSettings = false, BaseTestHandler())\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"PROTOCOL_ERROR: FLAG_COMPRESSED without SETTINGS_COMPRESS_DATA\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":504,"symbol":"readPaddedDataFrame","kind":"function","lang":"kotlin","code":"@Test fun readPaddedDataFrame() {\n val dataLength = 1123\n val expectedData = ByteArray(dataLength)\n Arrays.fill(expectedData, 2.toByte())\n val paddingLength = 254\n val padding = ByteArray(paddingLength)\n Arrays.fill(padding, 0.toByte())\n writeMedium(frame, dataLength + paddingLength + 1)\n frame.writeByte(Http2.TYPE_DATA)\n frame.writeByte(FLAG_PADDED)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeByte(paddingLength)\n frame.write(expectedData)\n frame.write(padding)\n reader.nextFrame(requireSettings = false, assertData())\n // Padding was skipped.\n assertThat(frame.exhausted()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":523,"symbol":"readPaddedDataFrameZeroPadding","kind":"function","lang":"kotlin","code":"@Test fun readPaddedDataFrameZeroPadding() {\n val dataLength = 1123\n val expectedData = ByteArray(dataLength)\n Arrays.fill(expectedData, 2.toByte())\n writeMedium(frame, dataLength + 1)\n frame.writeByte(Http2.TYPE_DATA)\n frame.writeByte(FLAG_PADDED)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeByte(0)\n frame.write(expectedData)\n reader.nextFrame(requireSettings = false, assertData())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":536,"symbol":"readPaddedHeadersFrame","kind":"function","lang":"kotlin","code":"@Test fun readPaddedHeadersFrame() {\n val paddingLength = 254\n val padding = ByteArray(paddingLength)\n Arrays.fill(padding, 0.toByte())\n val headerBlock = literalHeaders(headerEntries(\"foo\", \"barrr\", \"baz\", \"qux\"))\n writeMedium(frame, headerBlock.size.toInt() + paddingLength + 1)\n frame.writeByte(Http2.TYPE_HEADERS)\n frame.writeByte(FLAG_END_HEADERS or FLAG_PADDED)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeByte(paddingLength)\n frame.writeAll(headerBlock)\n frame.write(padding)\n reader.nextFrame(requireSettings = false, assertHeaderBlock())\n // Padding was skipped.\n assertThat(frame.exhausted()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":553,"symbol":"readPaddedHeadersFrameZeroPadding","kind":"function","lang":"kotlin","code":"@Test fun readPaddedHeadersFrameZeroPadding() {\n val headerBlock = literalHeaders(headerEntries(\"foo\", \"barrr\", \"baz\", \"qux\"))\n writeMedium(frame, headerBlock.size.toInt() + 1)\n frame.writeByte(Http2.TYPE_HEADERS)\n frame.writeByte(FLAG_END_HEADERS or FLAG_PADDED)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeByte(0)\n frame.writeAll(headerBlock)\n reader.nextFrame(requireSettings = false, assertHeaderBlock())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":565,"symbol":"readPaddedHeadersFrameThenContinuation","kind":"function","lang":"kotlin","doc":"Headers are compressed, then framed.","code":"@Test fun readPaddedHeadersFrameThenContinuation() {\n val paddingLength = 254\n val padding = ByteArray(paddingLength)\n Arrays.fill(padding, 0.toByte())\n\n // Decoding the first header will cross frame boundaries.\n val headerBlock = literalHeaders(headerEntries(\"foo\", \"barrr\", \"baz\", \"qux\"))\n\n // Write the first headers frame.\n writeMedium(frame, (headerBlock.size / 2).toInt() + paddingLength + 1)\n frame.writeByte(Http2.TYPE_HEADERS)\n frame.writeByte(FLAG_PADDED)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeByte(paddingLength)\n frame.write(headerBlock, headerBlock.size / 2)\n frame.write(padding)\n\n // Write the continuation frame, specifying no more frames are expected.\n writeMedium(frame, headerBlock.size.toInt())\n frame.writeByte(Http2.TYPE_CONTINUATION)\n frame.writeByte(FLAG_END_HEADERS)\n frame.writeInt(expectedStreamId and 0x7fffffff)\n frame.writeAll(headerBlock)\n reader.nextFrame(requireSettings = false, assertHeaderBlock())\n assertThat(frame.exhausted()).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":592,"symbol":"tooLargeDataFrame","kind":"function","lang":"kotlin","code":"@Test fun tooLargeDataFrame() {\n assertFailsWith {\n sendDataFrame(Buffer().write(ByteArray(0x1000000)))\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"FRAME_SIZE_ERROR length > 16384: 16777216\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":600,"symbol":"windowUpdateRoundTrip","kind":"function","lang":"kotlin","code":"@Test fun windowUpdateRoundTrip() {\n val expectedWindowSizeIncrement: Long = 0x7fffffff\n writeMedium(frame, 4) // length\n frame.writeByte(Http2.TYPE_WINDOW_UPDATE)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(expectedStreamId)\n frame.writeInt(expectedWindowSizeIncrement.toInt())\n\n // Check writer sends the same bytes.\n assertThat(windowUpdate(expectedWindowSizeIncrement)).isEqualTo(frame)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun windowUpdate(\n streamId: Int,\n windowSizeIncrement: Long,\n ) {\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(windowSizeIncrement).isEqualTo(expectedWindowSizeIncrement)\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":613,"symbol":"windowUpdate","kind":"function","lang":"kotlin","code":"override fun windowUpdate(\n streamId: Int,\n windowSizeIncrement: Long,\n ) {\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(windowSizeIncrement).isEqualTo(expectedWindowSizeIncrement)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":624,"symbol":"badWindowSizeIncrement","kind":"function","lang":"kotlin","code":"@Test fun badWindowSizeIncrement() {\n assertFailsWith {\n windowUpdate(0)\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 0\")\n }\n assertFailsWith {\n windowUpdate(0x80000000L)\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"windowSizeIncrement == 0 || windowSizeIncrement > 0x7fffffffL: 2147483648\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":639,"symbol":"goAwayWithoutDebugDataRoundTrip","kind":"function","lang":"kotlin","code":"@Test fun goAwayWithoutDebugDataRoundTrip() {\n val expectedError = ErrorCode.PROTOCOL_ERROR\n writeMedium(frame, 8) // Without debug data there's only 2 32-bit fields.\n frame.writeByte(TYPE_GOAWAY)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // connection-scope\n frame.writeInt(expectedStreamId) // last good stream.\n frame.writeInt(expectedError.httpCode)\n\n // Check writer sends the same bytes.\n assertThat(sendGoAway(expectedStreamId, expectedError, EMPTY_BYTE_ARRAY))\n .isEqualTo(frame)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n ) {\n assertThat(lastGoodStreamId).isEqualTo(expectedStreamId)\n assertThat(errorCode).isEqualTo(expectedError)\n assertThat(debugData.size).isEqualTo(0)\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":654,"symbol":"goAway","kind":"function","lang":"kotlin","code":"override fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n ) {\n assertThat(lastGoodStreamId).isEqualTo(expectedStreamId)\n assertThat(errorCode).isEqualTo(expectedError)\n assertThat(debugData.size).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":667,"symbol":"goAwayWithDebugDataRoundTrip","kind":"function","lang":"kotlin","code":"@Test fun goAwayWithDebugDataRoundTrip() {\n val expectedError = ErrorCode.PROTOCOL_ERROR\n val expectedData: ByteString = \"abcdefgh\".encodeUtf8()\n\n // Compose the expected GOAWAY frame without debug data.\n writeMedium(frame, 8 + expectedData.size)\n frame.writeByte(TYPE_GOAWAY)\n frame.writeByte(FLAG_NONE)\n frame.writeInt(0) // connection-scope\n frame.writeInt(0) // never read any stream!\n frame.writeInt(expectedError.httpCode)\n frame.write(expectedData.toByteArray())\n\n // Check writer sends the same bytes.\n assertThat(sendGoAway(0, expectedError, expectedData.toByteArray())).isEqualTo(frame)\n reader.nextFrame(\n requireSettings = false,\n object : BaseTestHandler() {\n override fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n ) {\n assertThat(lastGoodStreamId).isEqualTo(0)\n assertThat(errorCode).isEqualTo(expectedError)\n assertThat(debugData).isEqualTo(expectedData)\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":685,"symbol":"goAway","kind":"function","lang":"kotlin","code":"override fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n ) {\n assertThat(lastGoodStreamId).isEqualTo(0)\n assertThat(errorCode).isEqualTo(expectedError)\n assertThat(debugData).isEqualTo(expectedData)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":698,"symbol":"frameSizeError","kind":"function","lang":"kotlin","code":"@Test fun frameSizeError() {\n val writer = Http2Writer(Buffer(), true)\n assertFailsWith {\n writer.frameHeader(0, 16777216, Http2.TYPE_DATA, FLAG_NONE)\n }.also { expected ->\n // TODO: real max is based on settings between 16384 and 16777215\n assertThat(expected.message).isEqualTo(\"FRAME_SIZE_ERROR length > 16384: 16777216\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":708,"symbol":"ackSettingsAppliesMaxFrameSize","kind":"function","lang":"kotlin","code":"@Test fun ackSettingsAppliesMaxFrameSize() {\n val newMaxFrameSize = 16777215\n val writer = Http2Writer(Buffer(), true)\n writer.applyAndAckSettings(Settings().set(Settings.MAX_FRAME_SIZE, newMaxFrameSize))\n assertThat(writer.maxDataLength()).isEqualTo(newMaxFrameSize)\n writer.frameHeader(0, newMaxFrameSize, Http2.TYPE_DATA, FLAG_NONE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":716,"symbol":"streamIdHasReservedBit","kind":"function","lang":"kotlin","code":"@Test fun streamIdHasReservedBit() {\n val writer = Http2Writer(Buffer(), true)\n assertFailsWith {\n var streamId = 3\n streamId = streamId or (1L shl 31).toInt() // set reserved bit\n writer.frameHeader(streamId, Http2.INITIAL_MAX_FRAME_SIZE, Http2.TYPE_DATA, FLAG_NONE)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"reserved bit set: -2147483645\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":727,"symbol":"literalHeaders","kind":"function","lang":"kotlin","code":"private fun literalHeaders(sentHeaders: List
): Buffer {\n val out = Buffer()\n Hpack.Writer(out = out).writeHeaders(sentHeaders)\n return out\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":733,"symbol":"sendHeaderFrames","kind":"function","lang":"kotlin","code":"private fun sendHeaderFrames(\n outFinished: Boolean,\n headers: List
,\n ): Buffer {\n val out = Buffer()\n Http2Writer(out, true).headers(outFinished, expectedStreamId, headers)\n return out\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":742,"symbol":"sendPushPromiseFrames","kind":"function","lang":"kotlin","code":"private fun sendPushPromiseFrames(\n streamId: Int,\n headers: List
,\n ): Buffer {\n val out = Buffer()\n Http2Writer(out, true).pushPromise(expectedStreamId, streamId, headers)\n return out\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":751,"symbol":"sendPingFrame","kind":"function","lang":"kotlin","code":"private fun sendPingFrame(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n ): Buffer {\n val out = Buffer()\n Http2Writer(out, true).ping(ack, payload1, payload2)\n return out\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":761,"symbol":"sendGoAway","kind":"function","lang":"kotlin","code":"private fun sendGoAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteArray,\n ): Buffer {\n val out = Buffer()\n Http2Writer(out, true).goAway(lastGoodStreamId, errorCode, debugData)\n return out\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":771,"symbol":"sendDataFrame","kind":"function","lang":"kotlin","code":"private fun sendDataFrame(data: Buffer): Buffer {\n val out = Buffer()\n Http2Writer(out, true).dataFrame(expectedStreamId, FLAG_NONE, data, data.size.toInt())\n return out\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":777,"symbol":"windowUpdate","kind":"function","lang":"kotlin","code":"private fun windowUpdate(windowSizeIncrement: Long): Buffer {\n val out = Buffer()\n Http2Writer(out, true).windowUpdate(expectedStreamId, windowSizeIncrement)\n return out\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":783,"symbol":"assertHeaderBlock","kind":"function","lang":"kotlin","code":"private fun assertHeaderBlock(): Http2Reader.Handler =\n object : BaseTestHandler() {\n override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(associatedStreamId).isEqualTo(-1)\n assertThat(headerBlock).isEqualTo(headerEntries(\"foo\", \"barrr\", \"baz\", \"qux\"))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":785,"symbol":"headers","kind":"function","lang":"kotlin","code":"override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(associatedStreamId).isEqualTo(-1)\n assertThat(headerBlock).isEqualTo(headerEntries(\"foo\", \"barrr\", \"baz\", \"qux\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":798,"symbol":"assertData","kind":"function","lang":"kotlin","code":"private fun assertData(): Http2Reader.Handler =\n object : BaseTestHandler() {\n override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(length).isEqualTo(1123)\n val data = source.readByteString(length.toLong())\n for (b in data.toByteArray()) {\n assertThat(b).isEqualTo(2.toByte())\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":800,"symbol":"data","kind":"function","lang":"kotlin","code":"override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n assertThat(inFinished).isFalse()\n assertThat(streamId).isEqualTo(expectedStreamId)\n assertThat(length).isEqualTo(1123)\n val data = source.readByteString(length.toLong())\n for (b in data.toByteArray()) {\n assertThat(b).isEqualTo(2.toByte())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2Test.kt","line":816,"symbol":"gzip","kind":"function","lang":"kotlin","code":"private fun gzip(data: ByteArray): Buffer {\n val buffer = Buffer()\n GzipSink(buffer).buffer().write(data).close()\n return buffer\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":103,"symbol":"HttpOverHttp2Test","kind":"class","lang":"kotlin","doc":"Test how HTTP/2 interacts with HTTP features.","code":"@Timeout(60)\n@Flaky\n@Tag(\"Slow\")\n@Burst\nclass HttpOverHttp2Test(\n val protocol: Protocol = burstValues(Protocol.H2_PRIOR_KNOWLEDGE, Protocol.HTTP_2),\n) {\n @RegisterExtension\n val platform: PlatformRule = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = configureClientTestRule()\n\n @RegisterExtension\n val testLogHandler: TestLogHandler = TestLogHandler(Http2::class.java)\n\n // Flaky https://github.com/lysine-dev/okhttp/issues/4632\n // Flaky https://github.com/lysine-dev/okhttp/issues/4633\n private val handshakeCertificates: HandshakeCertificates =\n platform.localhostHandshakeCertificates()\n\n @StartStop\n private val server = MockWebServer()\n\n private lateinit var client: OkHttpClient\n private val fileSystem: FakeFileSystem = FakeFileSystem()\n private val cache: Cache = Cache(fileSystem, \"/tmp/cache\".toPath(), Long.MAX_VALUE)\n private lateinit var scheme: String\n\n private fun configureClientTestRule(): OkHttpClientTestRule {\n val clientTestRule = OkHttpClientTestRule()\n clientTestRule.recordTaskRunner = true\n return clientTestRule\n }\n\n @BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n if (protocol === Protocol.HTTP_2) {\n platfo"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":132,"symbol":"configureClientTestRule","kind":"function","lang":"kotlin","code":"private fun configureClientTestRule(): OkHttpClientTestRule {\n val clientTestRule = OkHttpClientTestRule()\n clientTestRule.recordTaskRunner = true\n return clientTestRule\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":138,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n if (protocol === Protocol.HTTP_2) {\n platform.assumeHttp2Support()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n client =\n clientTestRule\n .newClientBuilder()\n .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n scheme = \"https\"\n } else {\n server.protocols = listOf(Protocol.H2_PRIOR_KNOWLEDGE)\n client =\n clientTestRule\n .newClientBuilder()\n .protocols(listOf(Protocol.H2_PRIOR_KNOWLEDGE))\n .build()\n scheme = \"http\"\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":165,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n// TODO reenable after https://github.com/lysine-dev/okhttp/issues/8206\n// fileSystem.checkNoOpenFiles()\n cache.close()\n\n java.net.Authenticator.setDefault(null)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":173,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test\n fun get() {\n server.enqueue(MockResponse(body = \"ABCDE\"))\n val call = client.newCall(Request(server.url(\"/foo\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"ABCDE\")\n assertThat(response.code).isEqualTo(200)\n assertThat(response.message).isEqualTo(\"\")\n assertThat(response.protocol).isEqualTo(protocol)\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"GET /foo HTTP/2\")\n assertThat(request.headers[\":scheme\"]).isEqualTo(scheme)\n assertThat(request.headers[\":authority\"]).isEqualTo(\"${server.hostName}:${server.port}\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":188,"symbol":"get204Response","kind":"function","lang":"kotlin","code":"@Test\n fun get204Response() {\n val responseWithoutBody =\n MockResponse\n .Builder()\n .status(\"HTTP/1.1 204\")\n .removeHeader(\"Content-Length\")\n .build()\n server.enqueue(responseWithoutBody)\n val call = client.newCall(Request(server.url(\"/foo\")))\n val response = call.execute()\n\n // Body contains nothing.\n assertThat(response.body.bytes().size).isEqualTo(0)\n assertThat(response.body.contentLength()).isEqualTo(0)\n\n // Content-Length header doesn't exist in a 204 response.\n assertThat(response.header(\"content-length\")).isNull()\n assertThat(response.code).isEqualTo(204)\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"GET /foo HTTP/2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":211,"symbol":"head","kind":"function","lang":"kotlin","code":"@Test\n fun head() {\n val mockResponse =\n MockResponse\n .Builder()\n .setHeader(\"Content-Length\", 5)\n .status(\"HTTP/1.1 200\")\n .build()\n server.enqueue(mockResponse)\n val call =\n client.newCall(\n Request\n .Builder()\n .head()\n .url(server.url(\"/foo\"))\n .build(),\n )\n val response = call.execute()\n\n // Body contains nothing.\n assertThat(response.body.bytes().size).isEqualTo(0)\n assertThat(response.body.contentLength()).isEqualTo(0)\n\n // Content-Length header stays correctly.\n assertThat(response.header(\"content-length\")).isEqualTo(\"5\")\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"HEAD /foo HTTP/2\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":240,"symbol":"emptyResponse","kind":"function","lang":"kotlin","code":"@Test\n fun emptyResponse() {\n server.enqueue(MockResponse())\n val call = client.newCall(Request(server.url(\"/foo\")))\n val response = call.execute()\n assertThat(response.body.byteStream().read()).isEqualTo(-1)\n response.body.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":249,"symbol":"noDefaultContentLengthOnStreamingPost","kind":"function","lang":"kotlin","code":"@Test\n fun noDefaultContentLengthOnStreamingPost() {\n val postBytes = \"FGHIJ\".toByteArray()\n server.enqueue(MockResponse(body = \"ABCDE\"))\n val call =\n client.newCall(\n Request(\n url = server.url(\"/foo\"),\n body =\n object : RequestBody() {\n override fun contentType(): MediaType = \"text/plain; charset=utf-8\".toMediaType()\n\n override fun writeTo(sink: BufferedSink) {\n sink.write(postBytes)\n }\n },\n ),\n )\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"ABCDE\")\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"POST /foo HTTP/2\")\n assertArrayEquals(postBytes, request.body?.toByteArray())\n assertThat(request.headers[\"Content-Length\"]).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":259,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType = \"text/plain; charset=utf-8\".toMediaType()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":261,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.write(postBytes)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":275,"symbol":"userSuppliedContentLengthHeader","kind":"function","lang":"kotlin","code":"@Test\n fun userSuppliedContentLengthHeader() {\n val postBytes = \"FGHIJ\".toByteArray()\n server.enqueue(MockResponse(body = \"ABCDE\"))\n val call =\n client.newCall(\n Request(\n url = server.url(\"/foo\"),\n body =\n object : RequestBody() {\n override fun contentType(): MediaType = \"text/plain; charset=utf-8\".toMediaType()\n\n override fun contentLength(): Long = postBytes.size.toLong()\n\n override fun writeTo(sink: BufferedSink) {\n sink.write(postBytes)\n }\n },\n ),\n )\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"ABCDE\")\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"POST /foo HTTP/2\")\n assertArrayEquals(postBytes, request.body?.toByteArray())\n assertThat(request.headers[\"Content-Length\"]!!.toInt()).isEqualTo(postBytes.size)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":285,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType = \"text/plain; charset=utf-8\".toMediaType()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":287,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = postBytes.size.toLong()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":289,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.write(postBytes)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":303,"symbol":"closeAfterFlush","kind":"function","lang":"kotlin","code":"@Test\n fun closeAfterFlush() {\n val postBytes = \"FGHIJ\".toByteArray()\n server.enqueue(MockResponse(body = \"ABCDE\"))\n val call =\n client.newCall(\n Request(\n url = server.url(\"/foo\"),\n body =\n object : RequestBody() {\n override fun contentType(): MediaType = \"text/plain; charset=utf-8\".toMediaType()\n\n override fun contentLength(): Long = postBytes.size.toLong()\n\n override fun writeTo(sink: BufferedSink) {\n sink.write(postBytes) // push bytes into the stream's buffer\n sink.flush() // Http2Connection.writeData subject to write window\n sink.close() // Http2Connection.writeData empty frame\n }\n },\n ),\n )\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"ABCDE\")\n val request = server.takeRequest()\n assertThat(request.requestLine).isEqualTo(\"POST /foo HTTP/2\")\n assertArrayEquals(postBytes, request.body?.toByteArray())\n assertThat(request.headers[\"Content-Length\"]!!.toInt()).isEqualTo(postBytes.size)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":313,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType = \"text/plain; charset=utf-8\".toMediaType()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":315,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = postBytes.size.toLong()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":317,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.write(postBytes) // push bytes into the stream's buffer\n sink.flush() // Http2Connection.writeData subject to write window\n sink.close() // Http2Connection.writeData empty frame\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":333,"symbol":"connectionReuse","kind":"function","lang":"kotlin","code":"@Test\n fun connectionReuse() {\n server.enqueue(MockResponse(body = \"ABCDEF\"))\n server.enqueue(MockResponse(body = \"GHIJKL\"))\n val call1 = client.newCall(Request(server.url(\"/r1\")))\n val call2 = client.newCall(Request(server.url(\"/r1\")))\n val response1 = call1.execute()\n val response2 = call2.execute()\n assertThat(response1.body.source().readUtf8(3)).isEqualTo(\"ABC\")\n assertThat(response2.body.source().readUtf8(3)).isEqualTo(\"GHI\")\n assertThat(response1.body.source().readUtf8(3)).isEqualTo(\"DEF\")\n assertThat(response2.body.source().readUtf8(3)).isEqualTo(\"JKL\")\n val c0e0 = server.takeRequest()\n assertThat(c0e0.connectionIndex).isEqualTo(0)\n assertThat(c0e0.exchangeIndex).isEqualTo(0)\n val c0e1 = server.takeRequest()\n assertThat(c0e1.connectionIndex).isEqualTo(0)\n assertThat(c0e1.exchangeIndex).isEqualTo(1)\n response1.close()\n response2.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":355,"symbol":"connectionWindowUpdateAfterCanceling","kind":"function","lang":"kotlin","code":"@Test\n fun connectionWindowUpdateAfterCanceling() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(Buffer().write(ByteArray(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE + 1)))\n .build(),\n )\n server.enqueue(\n MockResponse(body = \"abc\"),\n )\n val call1 = client.newCall(Request(server.url(\"/\")))\n val response1 = call1.execute()\n waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE)\n\n // Cancel the call and discard what we've buffered for the response body. This should free up\n // the connection flow-control window so new requests can proceed.\n call1.cancel()\n assertThat(\n response1.body.source().discard(1, TimeUnit.SECONDS),\n \"Call should not have completed successfully.\",\n ).isFalse()\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":383,"symbol":"waitForDataFrames","kind":"function","lang":"kotlin","doc":"Wait for the client to receive `dataLength` DATA frames.","code":"private fun waitForDataFrames(dataLength: Int) {\n val expectedFrameCount = dataLength / 16384\n var dataFrameCount = 0\n while (dataFrameCount < expectedFrameCount) {\n val log = testLogHandler.take()\n if (log == \"FINE: << 0x00000003 16384 DATA \") {\n dataFrameCount++\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":394,"symbol":"connectionWindowUpdateOnClose","kind":"function","lang":"kotlin","code":"@Test\n fun connectionWindowUpdateOnClose() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(Buffer().write(ByteArray(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE + 1)))\n .build(),\n )\n server.enqueue(\n MockResponse(body = \"abc\"),\n )\n // Enqueue an additional response that show if we burnt a good prior response.\n server.enqueue(\n MockResponse(body = \"XXX\"),\n )\n val call1 = client.newCall(Request(server.url(\"/\")))\n val response1 = call1.execute()\n waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE)\n\n // Cancel the call and close the response body. This should discard the buffered data and update\n // the connection flow-control window.\n call1.cancel()\n response1.close()\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":422,"symbol":"concurrentRequestWithEmptyFlowControlWindow","kind":"function","lang":"kotlin","code":"@Test\n fun concurrentRequestWithEmptyFlowControlWindow() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(Buffer().write(ByteArray(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE)))\n .build(),\n )\n server.enqueue(\n MockResponse(body = \"abc\"),\n )\n val call1 = client.newCall(Request(server.url(\"/\")))\n val response1 = call1.execute()\n waitForDataFrames(Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE)\n assertThat(response1.body.contentLength()).isEqualTo(\n Http2Connection.OKHTTP_CLIENT_WINDOW_SIZE.toLong(),\n )\n val read = response1.body.source().read(ByteArray(8192))\n assertThat(read).isEqualTo(8192)\n\n // Make a second call that should transmit the response headers. The response body won't be\n // transmitted until the flow-control window is updated from the first request.\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.code).isEqualTo(200)\n\n // Close the response body. This should discard the buffered data and update the connection\n // flow-control window.\n response1.close()\n assertThat(response2.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":455,"symbol":"synchronousRequest","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/373","code":"@Test\n @Disabled\n fun synchronousRequest() {\n server.enqueue(MockResponse(body = \"A\"))\n server.enqueue(MockResponse(body = \"A\"))\n val executor = Executors.newCachedThreadPool(threadFactory(\"HttpOverHttp2Test\"))\n val countDownLatch = CountDownLatch(2)\n executor.execute(AsyncRequest(\"/r1\", countDownLatch))\n executor.execute(AsyncRequest(\"/r2\", countDownLatch))\n countDownLatch.await()\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":469,"symbol":"gzippedResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun gzippedResponseBody() {\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"Content-Encoding: gzip\")\n .body(gzip(\"ABCABCABC\"))\n .build(),\n )\n val call = client.newCall(Request(server.url(\"/r1\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"ABCABCABC\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":483,"symbol":"authenticate","kind":"function","lang":"kotlin","code":"@Test\n fun authenticate() {\n server.enqueue(\n MockResponse(\n code = HttpURLConnection.HTTP_UNAUTHORIZED,\n headers = headersOf(\"www-authenticate\", \"Basic realm=\\\"protected area\\\"\"),\n body = \"Please authenticate.\",\n ),\n )\n server.enqueue(\n MockResponse(body = \"Successful auth!\"),\n )\n val credential = basic(\"username\", \"password\")\n client =\n client\n .newBuilder()\n .authenticator(RecordingOkAuthenticator(credential, \"Basic\"))\n .build()\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"Successful auth!\")\n val denied = server.takeRequest()\n assertThat(denied.headers[\"Authorization\"]).isNull()\n val accepted = server.takeRequest()\n assertThat(accepted.requestLine).isEqualTo(\"GET / HTTP/2\")\n assertThat(accepted.headers[\"Authorization\"]).isEqualTo(credential)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":511,"symbol":"redirect","kind":"function","lang":"kotlin","code":"@Test\n fun redirect() {\n server.enqueue(\n MockResponse(\n code = HttpURLConnection.HTTP_MOVED_TEMP,\n headers = headersOf(\"Location\", \"/foo\"),\n body = \"This page has moved!\",\n ),\n )\n server.enqueue(MockResponse(body = \"This is the new location!\"))\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"This is the new location!\")\n val request1 = server.takeRequest()\n assertThat(request1.url.encodedPath).isEqualTo(\"/\")\n val request2 = server.takeRequest()\n assertThat(request2.url.encodedPath).isEqualTo(\"/foo\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":530,"symbol":"readAfterLastByte","kind":"function","lang":"kotlin","code":"@Test\n fun readAfterLastByte() {\n server.enqueue(MockResponse(body = \"ABC\"))\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n val inputStream = response.body.byteStream()\n assertThat(inputStream.read()).isEqualTo('A'.code)\n assertThat(inputStream.read()).isEqualTo('B'.code)\n assertThat(inputStream.read()).isEqualTo('C'.code)\n assertThat(inputStream.read()).isEqualTo(-1)\n assertThat(inputStream.read()).isEqualTo(-1)\n inputStream.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":544,"symbol":"readResponseHeaderTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun readResponseHeaderTimeout() {\n server.enqueue(MockResponse.Builder().onResponseStart(Stall).build())\n server.enqueue(MockResponse(body = \"A\"))\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofSeconds(1))\n .build()\n\n // Make a call expecting a timeout reading the response headers.\n val call1 = client.newCall(Request(server.url(\"/\")))\n assertFailsWith {\n call1.execute()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n }\n\n // Confirm that a subsequent request on the same connection is not impacted.\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.body.string()).isEqualTo(\"A\")\n\n // Confirm that the connection was reused.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":577,"symbol":"readTimeoutMoreGranularThanBodySize","kind":"function","lang":"kotlin","doc":"Test to ensure we don't throw a read timeout on responses that are progressing. For this case, we take a 4KiB body and throttle it to 1KiB/second. We set the read timeout to two seconds. If our implementation is acting correctly, it will not throw, as it is progressing.","code":"@Test\n fun readTimeoutMoreGranularThanBodySize() {\n val body = CharArray(4096) // 4KiB to read.\n Arrays.fill(body, 'y')\n server.enqueue(\n MockResponse\n .Builder()\n .body(String(body))\n .throttleBody(1024, 1, TimeUnit.SECONDS) // Slow connection 1KiB/second.\n .build(),\n )\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofSeconds(2))\n .build()\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(String(body))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":604,"symbol":"readTimeoutOnSlowConnection","kind":"function","lang":"kotlin","doc":"Test to ensure we throw a read timeout on responses that are progressing too slowly. For this case, we take a 2KiB body and throttle it to 1KiB/second. We set the read timeout to half a second. If our implementation is acting correctly, it will throw, as a byte doesn't arrive in time.","code":"@Test\n fun readTimeoutOnSlowConnection() {\n val body = repeat('y', 2048)\n server.enqueue(\n MockResponse\n .Builder()\n .body(body)\n .throttleBody(1024, 1, TimeUnit.SECONDS)\n .build(),\n ) // Slow connection 1KiB/second.\n server.enqueue(\n MockResponse(body = body),\n )\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ofMillis(500)) // Half a second to read something.\n .build()\n\n // Make a call expecting a timeout reading the response body.\n val call1 = client.newCall(Request(server.url(\"/\")))\n val response1 = call1.execute()\n assertFailsWith {\n response1.body.string()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"timeout\")\n }\n\n // Confirm that a subsequent request on the same connection is not impacted.\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.body.string()).isEqualTo(body)\n\n // Confirm that the connection was reused.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":642,"symbol":"connectionTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun connectionTimeout() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"A\")\n .bodyDelay(1, TimeUnit.SECONDS)\n .build(),\n )\n val client1 =\n client\n .newBuilder()\n .readTimeout(Duration.ofSeconds(2))\n .build()\n val call1 =\n client1\n .newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val client2 =\n client\n .newBuilder()\n .readTimeout(Duration.ofMillis(200))\n .build()\n val call2 =\n client2\n .newCall(\n Request\n .Builder()\n .url(server.url(\"/\"))\n .build(),\n )\n val response1 = call1.execute()\n assertThat(response1.body.string()).isEqualTo(\"A\")\n assertFailsWith {\n call2.execute()\n }\n\n // Confirm that the connection was reused.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":688,"symbol":"responsesAreCached","kind":"function","lang":"kotlin","code":"@Test\n fun responsesAreCached() {\n client =\n client\n .newBuilder()\n .cache(cache)\n .build()\n server.enqueue(\n MockResponse(\n headers = headersOf(\"cache-control\", \"max-age=60\"),\n body = \"A\",\n ),\n )\n val call1 = client.newCall(Request(server.url(\"/\")))\n val response1 = call1.execute()\n assertThat(response1.body.string()).isEqualTo(\"A\")\n assertThat(cache.requestCount()).isEqualTo(1)\n assertThat(cache.networkCount()).isEqualTo(1)\n assertThat(cache.hitCount()).isEqualTo(0)\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.body.string()).isEqualTo(\"A\")\n val call3 = client.newCall(Request(server.url(\"/\")))\n val response3 = call3.execute()\n assertThat(response3.body.string()).isEqualTo(\"A\")\n assertThat(cache.requestCount()).isEqualTo(3)\n assertThat(cache.networkCount()).isEqualTo(1)\n assertThat(cache.hitCount()).isEqualTo(2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":718,"symbol":"conditionalCache","kind":"function","lang":"kotlin","code":"@Test\n fun conditionalCache() {\n client =\n client\n .newBuilder()\n .cache(cache)\n .build()\n server.enqueue(\n MockResponse(\n headers = headersOf(\"ETag\", \"v1\"),\n body = \"A\",\n ),\n )\n server.enqueue(\n MockResponse(code = HttpURLConnection.HTTP_NOT_MODIFIED),\n )\n val call1 = client.newCall(Request(server.url(\"/\")))\n val response1 = call1.execute()\n assertThat(response1.body.string()).isEqualTo(\"A\")\n assertThat(cache.requestCount()).isEqualTo(1)\n assertThat(cache.networkCount()).isEqualTo(1)\n assertThat(cache.hitCount()).isEqualTo(0)\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.body.string()).isEqualTo(\"A\")\n assertThat(cache.requestCount()).isEqualTo(2)\n assertThat(cache.networkCount()).isEqualTo(2)\n assertThat(cache.hitCount()).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":748,"symbol":"responseCachedWithoutConsumingFullBody","kind":"function","lang":"kotlin","code":"@Test\n fun responseCachedWithoutConsumingFullBody() {\n client =\n client\n .newBuilder()\n .cache(cache)\n .build()\n server.enqueue(\n MockResponse(\n headers = headersOf(\"cache-control\", \"max-age=60\"),\n body = \"ABCD\",\n ),\n )\n server.enqueue(\n MockResponse(\n headers = headersOf(\"cache-control\", \"max-age=60\"),\n body = \"EFGH\",\n ),\n )\n val call1 = client.newCall(Request(server.url(\"/\")))\n val response1 = call1.execute()\n assertThat(response1.body.source().readUtf8(2)).isEqualTo(\"AB\")\n response1.body.close()\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.body.source().readUtf8()).isEqualTo(\"ABCD\")\n response2.body.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":777,"symbol":"sendRequestCookies","kind":"function","lang":"kotlin","code":"@Test\n fun sendRequestCookies() {\n val cookieJar = RecordingCookieJar()\n val requestCookie =\n Cookie\n .Builder()\n .name(\"a\")\n .value(\"b\")\n .domain(server.hostName)\n .build()\n cookieJar.enqueueRequestCookies(requestCookie)\n client =\n client\n .newBuilder()\n .cookieJar(cookieJar)\n .build()\n server.enqueue(MockResponse())\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"\")\n val request = server.takeRequest()\n assertThat(request.headers[\"Cookie\"]).isEqualTo(\"a=b\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":801,"symbol":"receiveResponseCookies","kind":"function","lang":"kotlin","code":"@Test\n fun receiveResponseCookies() {\n val cookieJar = RecordingCookieJar()\n client =\n client\n .newBuilder()\n .cookieJar(cookieJar)\n .build()\n server.enqueue(\n MockResponse(headers = headersOf(\"set-cookie\", \"a=b\")),\n )\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"\")\n cookieJar.assertResponseCookies(\"a=b; path=/\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":818,"symbol":"cancelWithStreamNotCompleted","kind":"function","lang":"kotlin","code":"@Test\n fun cancelWithStreamNotCompleted() {\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n\n // Disconnect before the stream is created. A connection is still established!\n val call1 = client.newCall(Request(server.url(\"/\")))\n val response = call1.execute()\n call1.cancel()\n\n // That connection is pooled, and it works.\n assertThat(client.connectionPool.connectionCount()).isEqualTo(1)\n val call2 = client.newCall(Request(server.url(\"/\")))\n val response2 = call2.execute()\n assertThat(response2.body.string()).isEqualTo(\"def\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n\n // Clean up the connection.\n response.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":839,"symbol":"noRecoveryFromOneRefusedStream","kind":"function","lang":"kotlin","code":"@Test\n fun noRecoveryFromOneRefusedStream() {\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(MockResponse(body = \"abc\"))\n val call = client.newCall(Request(server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":856,"symbol":"recoverFromRefusedStreamWhenAnotherRouteExists","kind":"function","lang":"kotlin","code":"@Test\n fun recoverFromRefusedStreamWhenAnotherRouteExists() {\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns()) // Two routes!\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(MockResponse(body = \"abc\"))\n\n val request = Request(server.url(\"/\"))\n val response = client.newCall(request).execute()\n assertThat(response.body.string()).isEqualTo(\"abc\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n\n // Note that although we have two routes available, we only use one. The retry is permitted\n // because there are routes available, but it chooses the existing connection since it isn't\n // yet considered unhealthy.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":882,"symbol":"noRecoveryWhenRoutesExhausted","kind":"function","lang":"kotlin","code":"@Test\n fun noRecoveryWhenRoutesExhausted() {\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns()) // Two routes!\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n\n val request = Request(server.url(\"/\"))\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)\n }\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0) // New connection.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1) // Pooled connection.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0) // New connection.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":919,"symbol":"connectionWithOneRefusedStreamIsPooled","kind":"function","lang":"kotlin","code":"@Test\n fun connectionWithOneRefusedStreamIsPooled() {\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(MockResponse(body = \"abc\"))\n val request = Request(server.url(\"/\"))\n\n // First call fails because it only has one route.\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)\n }\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n\n // Second call succeeds on the pooled connection.\n val response = client.newCall(request).execute()\n assertThat(response.body.string()).isEqualTo(\"abc\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":944,"symbol":"connectionWithTwoRefusedStreamsIsNotPooled","kind":"function","lang":"kotlin","code":"@Test\n fun connectionWithTwoRefusedStreamsIsNotPooled() {\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(MockResponse(body = \"abc\"))\n server.enqueue(MockResponse(body = \"def\"))\n val request = Request(server.url(\"/\"))\n\n // First call makes a new connection and fails because it is the only route.\n assertFailsWith {\n client.newCall(request).execute()\n }.also { expected ->\n assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)\n }\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0) // New connection.\n\n // Second call attempts the pooled connection, and it fails. Then it retries a new route which\n // succeeds.\n val response2 = client.newCall(request).execute()\n assertThat(response2.body.string()).isEqualTo(\"abc\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1) // Pooled connection.\n assertThat(server.takeReq"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":988,"symbol":"noRecoveryFromTwoRefusedStreams","kind":"function","lang":"kotlin","doc":"We had a bug where we'd perform infinite retries of route that fail with connection shutdown errors. The problem was that the logic that decided whether to reuse a route didn't track certain HTTP/2 errors. https://github.com/lysine-dev/okhttp/issues/5547","code":"@Test\n fun noRecoveryFromTwoRefusedStreams() {\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(\n MockResponse(body = \"abc\"),\n )\n val call = client.newCall(Request(server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.errorCode).isEqualTo(ErrorCode.REFUSED_STREAM)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1013,"symbol":"recoverFromOneInternalErrorRequiresNewConnection","kind":"function","lang":"kotlin","code":"@Test\n fun recoverFromOneInternalErrorRequiresNewConnection() {\n recoverFromOneHttp2ErrorRequiresNewConnection(ErrorCode.INTERNAL_ERROR)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1018,"symbol":"recoverFromOneCancelRequiresNewConnection","kind":"function","lang":"kotlin","code":"@Test\n fun recoverFromOneCancelRequiresNewConnection() {\n recoverFromOneHttp2ErrorRequiresNewConnection(ErrorCode.CANCEL)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1023,"symbol":"recoverFromOneHttp2ErrorRequiresNewConnection","kind":"function","lang":"kotlin","code":"private fun recoverFromOneHttp2ErrorRequiresNewConnection(errorCode: ErrorCode?) {\n server.enqueue(\n MockResponse.Builder().onRequestStart(CloseStream(errorCode!!.httpCode)).build(),\n )\n server.enqueue(MockResponse(body = \"abc\"))\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns())\n .build()\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"abc\")\n\n // New connection.\n val c0e0 = server.takeRequest()\n assertThat(c0e0.connectionIndex).isEqualTo(0)\n assertThat(c0e0.exchangeIndex).isEqualTo(0)\n // New connection.\n val c1e0 = server.takeRequest()\n assertThat(c1e0.connectionIndex).isEqualTo(1)\n assertThat(c1e0.exchangeIndex).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1047,"symbol":"recoverFromMultipleRefusedStreamsRequiresNewConnection","kind":"function","lang":"kotlin","code":"@Test\n fun recoverFromMultipleRefusedStreamsRequiresNewConnection() {\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseStream(ErrorCode.REFUSED_STREAM.httpCode))\n .build(),\n )\n server.enqueue(MockResponse(body = \"abc\"))\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns())\n .build()\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"abc\")\n\n // New connection.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n // Reused connection.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n // New connection.\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1079,"symbol":"recoverFromCancelReusesConnection","kind":"function","lang":"kotlin","code":"@Test\n fun recoverFromCancelReusesConnection() {\n val responseDequeuedLatches =\n listOf(\n // No synchronization for the last request, which is not canceled:\n CountDownLatch(1),\n CountDownLatch(0),\n )\n val requestCanceledLatches =\n listOf(\n CountDownLatch(1),\n CountDownLatch(0),\n )\n val dispatcher = RespondAfterCancelDispatcher(responseDequeuedLatches, requestCanceledLatches)\n dispatcher.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(10, TimeUnit.SECONDS)\n .body(\"abc\")\n .build(),\n )\n dispatcher.enqueue(\n MockResponse(body = \"def\"),\n )\n server.dispatcher = dispatcher\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns())\n .build()\n callAndCancel(0, responseDequeuedLatches[0], requestCanceledLatches[0])\n\n // Make a second request to ensure the connection is reused.\n val call = client.newCall(Request(server.url(\"/\")))\n val response = call.execute()\n assertThat(response.body.string()).isEqualTo(\"def\")\n assertThat(server.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1118,"symbol":"recoverFromMultipleCancelReusesConnection","kind":"function","lang":"kotlin","code":"@Test\n fun recoverFromMultipleCancelReusesConnection() {\n val responseDequeuedLatches =\n Arrays.asList(\n CountDownLatch(1),\n // No synchronization for the last request, which is not canceled:\n CountDownLatch(1),\n CountDownLatch(0),\n )\n val requestCanceledLatches =\n Arrays.asList(\n CountDownLatch(1),\n CountDownLatch(1),\n CountDownLatch(0),\n )\n val dispatcher = RespondAfterCancelDispatcher(responseDequeuedLatches, requestCanceledLatches)\n dispatcher.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(10, TimeUnit.SECONDS)\n .body(\"abc\")\n .build(),\n )\n dispatcher.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(10, TimeUnit.SECONDS)\n .body(\"def\")\n .build(),\n )\n dispatcher.enqueue(\n MockResponse(body = \"ghi\"),\n )\n server.dispatcher = dispatcher\n client =\n client\n .newBuilder()\n .dns(DoubleInetAddressDns())\n .build()\n callAndCancel(0, responseDequeuedLatches[0], requestCanceledLatches[0])\n callAndCancel(1, responseDequeuedLatches[1], requestCanceledLatches[1])\n\n // Make a third request to "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1167,"symbol":"RespondAfterCancelDispatcher","kind":"class","lang":"kotlin","code":"private class RespondAfterCancelDispatcher(\n private val responseDequeuedLatches: List,\n private val requestCanceledLatches: List,\n ) : QueueDispatcher() {\n private var responseIndex = 0\n\n @Synchronized\n override fun dispatch(request: RecordedRequest): MockResponse {\n // This guarantees a deterministic sequence when handling the canceled request:\n // 1. Server reads request and dequeues first response\n // 2. Client cancels request\n // 3. Server tries to send response on the canceled stream\n // Otherwise, there is no guarantee for the sequence. For example, the server may use the\n // first mocked response to respond to the second request.\n val response = super.dispatch(request)\n responseDequeuedLatches[responseIndex].countDown()\n requestCanceledLatches[responseIndex].await()\n responseIndex++\n return response\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1173,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"@Synchronized\n override fun dispatch(request: RecordedRequest): MockResponse {\n // This guarantees a deterministic sequence when handling the canceled request:\n // 1. Server reads request and dequeues first response\n // 2. Client cancels request\n // 3. Server tries to send response on the canceled stream\n // Otherwise, there is no guarantee for the sequence. For example, the server may use the\n // first mocked response to respond to the second request.\n val response = super.dispatch(request)\n responseDequeuedLatches[responseIndex].countDown()\n requestCanceledLatches[responseIndex].await()\n responseIndex++\n return response\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1190,"symbol":"callAndCancel","kind":"function","lang":"kotlin","doc":"Make a call and canceling it as soon as it's accepted by the server.","code":"private fun callAndCancel(\n expectedSequenceNumber: Int,\n responseDequeuedLatch: CountDownLatch?,\n requestCanceledLatch: CountDownLatch?,\n ) {\n val call = client.newCall(Request(server.url(\"/\")))\n val latch = CountDownLatch(1)\n call.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n latch.countDown()\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n fail(\"\")\n }\n },\n )\n assertThat(server.takeRequest().exchangeIndex)\n .isEqualTo(expectedSequenceNumber)\n responseDequeuedLatch!!.await()\n call.cancel()\n // Avoid flaky race conditions\n Thread.sleep(100)\n requestCanceledLatch!!.countDown()\n latch.await()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1199,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n latch.countDown()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1206,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n fail(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1224,"symbol":"noRecoveryFromRefusedStreamWithRetryDisabled","kind":"function","lang":"kotlin","code":"@Test\n fun noRecoveryFromRefusedStreamWithRetryDisabled() {\n noRecoveryFromErrorWithRetryDisabled(ErrorCode.REFUSED_STREAM)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1229,"symbol":"noRecoveryFromInternalErrorWithRetryDisabled","kind":"function","lang":"kotlin","code":"@Test\n fun noRecoveryFromInternalErrorWithRetryDisabled() {\n noRecoveryFromErrorWithRetryDisabled(ErrorCode.INTERNAL_ERROR)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1234,"symbol":"noRecoveryFromCancelWithRetryDisabled","kind":"function","lang":"kotlin","code":"@Test\n fun noRecoveryFromCancelWithRetryDisabled() {\n noRecoveryFromErrorWithRetryDisabled(ErrorCode.CANCEL)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HttpOverHttp2Test.kt","line":1239,"symbol":"noRecoveryFromErrorWithRetryDisabled","kind":"function","lang":"kotlin","code":"private fun noRecoveryFromErrorWithRetryDisabled(errorCode: ErrorCode?) {\n server.enqueue(\n MockResponse.Builder().onRequestStart(CloseStream(errorCode!!.httpCode)).build(),\n )\n server.enqueue(MockResponse(body = \"abc\"))\n client =\n client\n .newBuilder()\n .retryOnConnectionFailure(false)\n .build()\n val call = client.newCall(Request(server.url(\"/\")))\n assertFailsWith {\n call.execute()\n }.also { expected ->\n assertThat(expected.errorCode).isEqualTo(errorCode)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HuffmanTest.kt","line":32,"symbol":"HuffmanTest","kind":"class","lang":"kotlin","doc":"Original version of this class was lifted from `com.twitter.hpack.HuffmanTest`.","code":"class HuffmanTest {\n @Test\n fun roundTripForRequestAndResponse() {\n val s = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\n for (i in s.indices) {\n assertRoundTrip(s.substring(0, i).encodeUtf8())\n }\n val random = Random(123456789L)\n val buf = ByteArray(4096)\n random.nextBytes(buf)\n assertRoundTrip(buf.toByteString())\n }\n\n private fun assertRoundTrip(data: ByteString) {\n val encodeBuffer = Buffer()\n encode(data, encodeBuffer)\n assertThat(encodedLength(data).toLong()).isEqualTo(encodeBuffer.size)\n val decodeBuffer = Buffer()\n decode(encodeBuffer, encodeBuffer.size, decodeBuffer)\n assertEquals(data, decodeBuffer.readByteString())\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HuffmanTest.kt","line":33,"symbol":"roundTripForRequestAndResponse","kind":"function","lang":"kotlin","code":"@Test\n fun roundTripForRequestAndResponse() {\n val s = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\n for (i in s.indices) {\n assertRoundTrip(s.substring(0, i).encodeUtf8())\n }\n val random = Random(123456789L)\n val buf = ByteArray(4096)\n random.nextBytes(buf)\n assertRoundTrip(buf.toByteString())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/HuffmanTest.kt","line":45,"symbol":"assertRoundTrip","kind":"function","lang":"kotlin","code":"private fun assertRoundTrip(data: ByteString) {\n val encodeBuffer = Buffer()\n encode(data, encodeBuffer)\n assertThat(encodedLength(data).toLong()).isEqualTo(encodeBuffer.size)\n val decodeBuffer = Buffer()\n decode(encodeBuffer, encodeBuffer.size, decodeBuffer)\n assertEquals(data, decodeBuffer.readByteString())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":36,"symbol":"MockHttp2Peer","kind":"class","lang":"kotlin","doc":"Replays prerecorded outgoing frames and records incoming frames.","code":"class MockHttp2Peer : Closeable {\n private var frameCount = 0\n private var client = false\n private val bytesOut = Buffer()\n private var writer = Http2Writer(bytesOut, client)\n private val outFrames: MutableList = ArrayList()\n private val inFrames: BlockingQueue = LinkedBlockingQueue()\n private var port = 0\n private val executor = Executors.newSingleThreadExecutor(threadFactory(\"MockHttp2Peer\"))\n private var serverSocket: ServerSocket? = null\n private var socket: Socket? = null\n\n fun setClient(client: Boolean) {\n if (this.client == client) return\n this.client = client\n writer = Http2Writer(bytesOut, client)\n }\n\n fun acceptFrame() {\n frameCount++\n }\n\n /** Maximum length of an outbound data frame. */\n fun maxOutboundDataLength(): Int = writer.maxDataLength()\n\n /** Count of frames sent or received. */\n fun frameCount(): Int = frameCount\n\n fun sendFrame(): Http2Writer {\n outFrames.add(OutFrame(frameCount++, bytesOut.size, false))\n return writer\n }\n\n /**\n * Shortens the last frame from its original length to `length`. This will cause the peer to\n * close the socket as soon as this frame has been written; otherwise the peer s"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":48,"symbol":"setClient","kind":"function","lang":"kotlin","code":"fun setClient(client: Boolean) {\n if (this.client == client) return\n this.client = client\n writer = Http2Writer(bytesOut, client)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":54,"symbol":"acceptFrame","kind":"function","lang":"kotlin","code":"fun acceptFrame() {\n frameCount++\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":59,"symbol":"maxOutboundDataLength","kind":"function","lang":"kotlin","doc":"Maximum length of an outbound data frame.","code":"fun maxOutboundDataLength(): Int = writer.maxDataLength()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":62,"symbol":"frameCount","kind":"function","lang":"kotlin","doc":"Count of frames sent or received.","code":"fun frameCount(): Int = frameCount"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":64,"symbol":"sendFrame","kind":"function","lang":"kotlin","code":"fun sendFrame(): Http2Writer {\n outFrames.add(OutFrame(frameCount++, bytesOut.size, false))\n return writer\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":74,"symbol":"truncateLastFrame","kind":"function","lang":"kotlin","doc":"Shortens the last frame from its original length to `length`. This will cause the peer to close the socket as soon as this frame has been written; otherwise the peer stays open until explicitly closed.","code":"fun truncateLastFrame(length: Int): Http2Writer {\n val lastFrame = outFrames.removeAt(outFrames.size - 1)\n require(length < bytesOut.size - lastFrame.start)\n\n // Move everything from bytesOut into a new buffer.\n val fullBuffer = Buffer()\n bytesOut.read(fullBuffer, bytesOut.size)\n\n // Copy back all but what we're truncating.\n fullBuffer.read(bytesOut, lastFrame.start + length)\n outFrames.add(OutFrame(lastFrame.sequence, lastFrame.start, true))\n return writer\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":88,"symbol":"takeFrame","kind":"function","lang":"kotlin","code":"fun takeFrame(): InFrame = inFrames.take()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":90,"symbol":"play","kind":"function","lang":"kotlin","code":"fun play() {\n check(serverSocket == null)\n serverSocket = ServerSocket()\n serverSocket!!.reuseAddress = false\n serverSocket!!.bind(InetSocketAddress(\"localhost\", 0), 1)\n port = serverSocket!!.localPort\n executor.execute {\n try {\n readAndWriteFrames()\n } catch (e: IOException) {\n this@MockHttp2Peer.closeQuietly()\n logger.info(\"${this@MockHttp2Peer} done: ${e.message}\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":106,"symbol":"readAndWriteFrames","kind":"function","lang":"kotlin","code":"private fun readAndWriteFrames() {\n check(socket == null)\n val socket = serverSocket!!.accept()!!\n this.socket = socket\n\n // Bail out now if this instance was closed while waiting for the socket to accept.\n synchronized(this) {\n if (executor.isShutdown) {\n socket.close()\n return\n }\n }\n val outputStream = socket.getOutputStream()\n val inputStream = socket.getInputStream()\n val reader = Http2Reader(inputStream.source().buffer(), client)\n val outFramesIterator: Iterator = outFrames.iterator()\n val outBytes = bytesOut.readByteArray()\n var nextOutFrame: OutFrame? = null\n for (i in 0 until frameCount) {\n if (nextOutFrame == null && outFramesIterator.hasNext()) {\n nextOutFrame = outFramesIterator.next()\n }\n\n if (nextOutFrame != null && nextOutFrame.sequence == i) {\n val start = nextOutFrame.start\n var truncated: Boolean\n var end: Long\n if (outFramesIterator.hasNext()) {\n nextOutFrame = outFramesIterator.next()\n end = nextOutFrame.start\n truncated = false\n } else {\n end = outBytes.size.toLong()\n truncated = nextOutFra"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":159,"symbol":"openSocket","kind":"function","lang":"kotlin","code":"fun openSocket(): Socket = Socket(\"localhost\", port)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":161,"symbol":"close","kind":"function","lang":"kotlin","code":"@Synchronized override fun close() {\n executor.shutdown()\n socket?.closeQuietly()\n serverSocket?.closeQuietly()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":167,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"MockHttp2Peer[$port]\""} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":175,"symbol":"InFrame","kind":"class","lang":"kotlin","code":"class InFrame(\n val sequence: Int,\n val reader: Http2Reader,\n ) : Http2Reader.Handler {\n @JvmField var type = -1\n var clearPrevious = false\n\n @JvmField var outFinished = false\n\n @JvmField var inFinished = false\n\n @JvmField var streamId = 0\n\n @JvmField var associatedStreamId = 0\n\n @JvmField var errorCode: ErrorCode? = null\n\n @JvmField var windowSizeIncrement: Long = 0\n\n @JvmField var headerBlock: List
? = null\n\n @JvmField var data: ByteArray? = null\n\n @JvmField var settings: Settings? = null\n\n @JvmField var ack = false\n\n @JvmField var payload1 = 0\n\n @JvmField var payload2 = 0\n\n override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n check(type == -1)\n this.type = Http2.TYPE_SETTINGS\n this.clearPrevious = clearPrevious\n this.settings = settings\n }\n\n override fun ackSettings() {\n check(type == -1)\n this.type = Http2.TYPE_SETTINGS\n this.ack = true\n }\n\n override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n check(type == -1)\n this.type = Http2.TYPE_HEADER"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":206,"symbol":"settings","kind":"function","lang":"kotlin","code":"override fun settings(\n clearPrevious: Boolean,\n settings: Settings,\n ) {\n check(type == -1)\n this.type = Http2.TYPE_SETTINGS\n this.clearPrevious = clearPrevious\n this.settings = settings\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":216,"symbol":"ackSettings","kind":"function","lang":"kotlin","code":"override fun ackSettings() {\n check(type == -1)\n this.type = Http2.TYPE_SETTINGS\n this.ack = true\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":222,"symbol":"headers","kind":"function","lang":"kotlin","code":"override fun headers(\n inFinished: Boolean,\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n check(type == -1)\n this.type = Http2.TYPE_HEADERS\n this.inFinished = inFinished\n this.streamId = streamId\n this.associatedStreamId = associatedStreamId\n this.headerBlock = headerBlock\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":236,"symbol":"data","kind":"function","lang":"kotlin","code":"override fun data(\n inFinished: Boolean,\n streamId: Int,\n source: BufferedSource,\n length: Int,\n ) {\n check(type == -1)\n this.type = Http2.TYPE_DATA\n this.inFinished = inFinished\n this.streamId = streamId\n this.data = source.readByteString(length.toLong()).toByteArray()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":249,"symbol":"rstStream","kind":"function","lang":"kotlin","code":"override fun rstStream(\n streamId: Int,\n errorCode: ErrorCode,\n ) {\n check(type == -1)\n this.type = Http2.TYPE_RST_STREAM\n this.streamId = streamId\n this.errorCode = errorCode\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":259,"symbol":"ping","kind":"function","lang":"kotlin","code":"override fun ping(\n ack: Boolean,\n payload1: Int,\n payload2: Int,\n ) {\n check(type == -1)\n type = Http2.TYPE_PING\n this.ack = ack\n this.payload1 = payload1\n this.payload2 = payload2\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":271,"symbol":"goAway","kind":"function","lang":"kotlin","code":"override fun goAway(\n lastGoodStreamId: Int,\n errorCode: ErrorCode,\n debugData: ByteString,\n ) {\n check(type == -1)\n this.type = Http2.TYPE_GOAWAY\n this.streamId = lastGoodStreamId\n this.errorCode = errorCode\n this.data = debugData.toByteArray()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":283,"symbol":"windowUpdate","kind":"function","lang":"kotlin","code":"override fun windowUpdate(\n streamId: Int,\n windowSizeIncrement: Long,\n ) {\n check(type == -1)\n this.type = Http2.TYPE_WINDOW_UPDATE\n this.streamId = streamId\n this.windowSizeIncrement = windowSizeIncrement\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":293,"symbol":"priority","kind":"function","lang":"kotlin","code":"override fun priority(\n streamId: Int,\n streamDependency: Int,\n weight: Int,\n exclusive: Boolean,\n ): Unit = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":300,"symbol":"pushPromise","kind":"function","lang":"kotlin","code":"override fun pushPromise(\n streamId: Int,\n associatedStreamId: Int,\n headerBlock: List
,\n ) {\n this.type = Http2.TYPE_PUSH_PROMISE\n this.streamId = streamId\n this.associatedStreamId = associatedStreamId\n this.headerBlock = headerBlock\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/MockHttp2Peer.kt","line":311,"symbol":"alternateService","kind":"function","lang":"kotlin","code":"override fun alternateService(\n streamId: Int,\n origin: String,\n protocol: ByteString,\n host: String,\n port: Int,\n maxAge: Long,\n ): Unit = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/SettingsTest.kt","line":24,"symbol":"SettingsTest","kind":"class","lang":"kotlin","code":"class SettingsTest {\n @Test\n fun unsetField() {\n val settings = Settings()\n assertThat(settings.isSet(Settings.MAX_CONCURRENT_STREAMS)).isFalse()\n assertThat(settings.getMaxConcurrentStreams()).isEqualTo(Int.MAX_VALUE)\n }\n\n @Test\n fun setFields() {\n val settings = Settings()\n settings[Settings.HEADER_TABLE_SIZE] = 8096\n assertThat(settings.headerTableSize).isEqualTo(8096)\n assertThat(settings.getEnablePush(true)).isTrue()\n settings[Settings.ENABLE_PUSH] = 1\n assertThat(settings.getEnablePush(false)).isTrue()\n settings.clear()\n assertThat(settings.getMaxConcurrentStreams()).isEqualTo(Int.MAX_VALUE)\n settings[Settings.MAX_CONCURRENT_STREAMS] = 75\n assertThat(settings.getMaxConcurrentStreams()).isEqualTo(75)\n settings.clear()\n assertThat(settings.getMaxFrameSize(16384)).isEqualTo(16384)\n settings[Settings.MAX_FRAME_SIZE] = 16777215\n assertThat(settings.getMaxFrameSize(16384)).isEqualTo(16777215)\n assertThat(settings.getMaxHeaderListSize(-1)).isEqualTo(-1)\n settings[Settings.MAX_HEADER_LIST_SIZE] = 16777215\n assertThat(settings.getMaxHeaderListSize(-1)).isEqualTo(16777215)\n assertThat(settings.initialWindowSize).isEqua"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/SettingsTest.kt","line":25,"symbol":"unsetField","kind":"function","lang":"kotlin","code":"@Test\n fun unsetField() {\n val settings = Settings()\n assertThat(settings.isSet(Settings.MAX_CONCURRENT_STREAMS)).isFalse()\n assertThat(settings.getMaxConcurrentStreams()).isEqualTo(Int.MAX_VALUE)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/SettingsTest.kt","line":32,"symbol":"setFields","kind":"function","lang":"kotlin","code":"@Test\n fun setFields() {\n val settings = Settings()\n settings[Settings.HEADER_TABLE_SIZE] = 8096\n assertThat(settings.headerTableSize).isEqualTo(8096)\n assertThat(settings.getEnablePush(true)).isTrue()\n settings[Settings.ENABLE_PUSH] = 1\n assertThat(settings.getEnablePush(false)).isTrue()\n settings.clear()\n assertThat(settings.getMaxConcurrentStreams()).isEqualTo(Int.MAX_VALUE)\n settings[Settings.MAX_CONCURRENT_STREAMS] = 75\n assertThat(settings.getMaxConcurrentStreams()).isEqualTo(75)\n settings.clear()\n assertThat(settings.getMaxFrameSize(16384)).isEqualTo(16384)\n settings[Settings.MAX_FRAME_SIZE] = 16777215\n assertThat(settings.getMaxFrameSize(16384)).isEqualTo(16777215)\n assertThat(settings.getMaxHeaderListSize(-1)).isEqualTo(-1)\n settings[Settings.MAX_HEADER_LIST_SIZE] = 16777215\n assertThat(settings.getMaxHeaderListSize(-1)).isEqualTo(16777215)\n assertThat(settings.initialWindowSize).isEqualTo(\n Settings.DEFAULT_INITIAL_WINDOW_SIZE,\n )\n settings[Settings.INITIAL_WINDOW_SIZE] = 108\n assertThat(settings.initialWindowSize).isEqualTo(108)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/SettingsTest.kt","line":58,"symbol":"merge","kind":"function","lang":"kotlin","code":"@Test\n fun merge() {\n val a = Settings()\n a[Settings.HEADER_TABLE_SIZE] = 10000\n a[Settings.MAX_HEADER_LIST_SIZE] = 20000\n a[Settings.INITIAL_WINDOW_SIZE] = 30000\n val b = Settings()\n b[Settings.MAX_HEADER_LIST_SIZE] = 40000\n b[Settings.INITIAL_WINDOW_SIZE] = 50000\n b[Settings.MAX_CONCURRENT_STREAMS] = 60000\n a.merge(b)\n assertThat(a.headerTableSize).isEqualTo(10000)\n assertThat(a.getMaxHeaderListSize(-1)).isEqualTo(40000)\n assertThat(a.initialWindowSize).isEqualTo(50000)\n assertThat(a.getMaxConcurrentStreams()).isEqualTo(60000)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":31,"symbol":"IdnaMappingTableTest","kind":"class","lang":"kotlin","doc":"Confirm we get the expected table whether we build it from the .txt file or compact that.","code":"class IdnaMappingTableTest {\n private lateinit var table: SimpleIdnaMappingTable\n private lateinit var compactTable: IdnaMappingTable\n\n @BeforeEach\n fun setUp() {\n val path = \"/okhttp3/internal/idna/IdnaMappingTable.txt\".toPath()\n val plainTable =\n FileSystem.RESOURCES.read(path) {\n readPlainTextIdnaMappingTable()\n }\n table = plainTable\n val data = buildIdnaMappingTableData(plainTable)\n compactTable =\n IdnaMappingTable(\n sections = data.sections,\n ranges = data.ranges,\n mappings = data.mappings,\n )\n }\n\n @Test fun regularMappings() {\n assertThat(\"hello\".map()).isEqualTo(\"hello\")\n assertThat(\"hello-world\".map()).isEqualTo(\"hello-world\")\n assertThat(\"HELLO\".map()).isEqualTo(\"hello\")\n assertThat(\"Hello\".map()).isEqualTo(\"hello\")\n\n // These compound characters map their its components.\n assertThat(\"¼\".map()).isEqualTo(\"1⁄4\")\n assertThat(\"™\".map()).isEqualTo(\"tm\")\n }\n\n /** Confirm the compact table satisfies is documented invariants. */\n @Test fun validateCompactTableInvariants() {\n // Less than 16,834 bytes, because we binary search on a 14-bit index.\n assertThat(compactTable.sections.leng"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":35,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n val path = \"/okhttp3/internal/idna/IdnaMappingTable.txt\".toPath()\n val plainTable =\n FileSystem.RESOURCES.read(path) {\n readPlainTextIdnaMappingTable()\n }\n table = plainTable\n val data = buildIdnaMappingTableData(plainTable)\n compactTable =\n IdnaMappingTable(\n sections = data.sections,\n ranges = data.ranges,\n mappings = data.mappings,\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":52,"symbol":"regularMappings","kind":"function","lang":"kotlin","code":"@Test fun regularMappings() {\n assertThat(\"hello\".map()).isEqualTo(\"hello\")\n assertThat(\"hello-world\".map()).isEqualTo(\"hello-world\")\n assertThat(\"HELLO\".map()).isEqualTo(\"hello\")\n assertThat(\"Hello\".map()).isEqualTo(\"hello\")\n\n // These compound characters map their its components.\n assertThat(\"¼\".map()).isEqualTo(\"1⁄4\")\n assertThat(\"™\".map()).isEqualTo(\"tm\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":64,"symbol":"validateCompactTableInvariants","kind":"function","lang":"kotlin","doc":"Confirm the compact table satisfies is documented invariants.","code":"@Test fun validateCompactTableInvariants() {\n // Less than 16,834 bytes, because we binary search on a 14-bit index.\n assertThat(compactTable.sections.length).isLessThan(1 shl 14)\n\n // Less than 65,536 bytes, because we binary search on a 14-bit index with a stride of 4 bytes.\n assertThat(compactTable.ranges.length).isLessThan((1 shl 14) * 4)\n\n // Less than 16,384 chars, because we index on a 14-bit index in the ranges table.\n assertThat(compactTable.mappings.length).isLessThan(1 shl 14)\n\n // Confirm the data strings are ASCII.\n for (dataString in listOf(compactTable.sections, compactTable.ranges)) {\n for (codePoint in dataString.codePoints()) {\n assertThat(codePoint and 0x7f).isEqualTo(codePoint)\n }\n }\n\n // Confirm the sections are increasing.\n val rangesIndices = mutableListOf()\n val rangesOffsets = mutableListOf()\n for (i in 0 until compactTable.sections.length step 4) {\n rangesIndices += compactTable.sections.read14BitInt(i)\n rangesOffsets += compactTable.sections.read14BitInt(i + 2)\n }\n assertThat(rangesIndices).isEqualTo(rangesIndices.sorted())\n\n // Check the ranges.\n for (r in 0 u"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":111,"symbol":"deviations","kind":"function","lang":"kotlin","code":"@Test fun deviations() {\n assertThat(\"ß\".map()).isEqualTo(\"ß\")\n assertThat(\"ς\".map()).isEqualTo(\"ς\")\n assertThat(\"\\u200c\".map()).isEqualTo(\"\\u200c\")\n assertThat(\"\\u200d\".map()).isEqualTo(\"\\u200d\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":118,"symbol":"ignored","kind":"function","lang":"kotlin","code":"@Test fun ignored() {\n assertThat(\"\\u200b\".map()).isEqualTo(\"\")\n assertThat(\"\\ufeff\".map()).isEqualTo(\"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":123,"symbol":"disallowed","kind":"function","lang":"kotlin","code":"@Test fun disallowed() {\n assertThat(\"\\u0080\".mapExpectingErrors()).isEqualTo(\"\\u0080\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":127,"symbol":"disallowedStd3Valid","kind":"function","lang":"kotlin","code":"@Test fun disallowedStd3Valid() {\n assertThat(\"_\".map()).isEqualTo(\"_\")\n assertThat(\"/\".map()).isEqualTo(\"/\")\n assertThat(\"≠\".map()).isEqualTo(\"≠\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":133,"symbol":"disallowedStd3Mapped","kind":"function","lang":"kotlin","code":"@Test fun disallowedStd3Mapped() {\n assertThat(\"\\u00b8\".map()).isEqualTo(\"\\u0020\\u0327\")\n assertThat(\"⑴\".map()).isEqualTo(\"(1)\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":138,"symbol":"outOfBounds","kind":"function","lang":"kotlin","code":"@Test fun outOfBounds() {\n assertFailsWith {\n table.map(-1, Buffer())\n }\n table.map(0, Buffer()) // Lowest legal code point.\n table.map(0x10ffff, Buffer()) // Highest legal code point.\n assertFailsWith {\n table.map(0x110000, Buffer())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":149,"symbol":"binarySearchEvenSizedRange","kind":"function","lang":"kotlin","code":"@Test fun binarySearchEvenSizedRange() {\n val table = listOf(1, 3, 5, 7, 9, 11)\n\n // Search for matches.\n assertEquals(0, binarySearch(0, 6) { index -> 1.compareTo(table[index]) })\n assertEquals(1, binarySearch(0, 6) { index -> 3.compareTo(table[index]) })\n assertEquals(2, binarySearch(0, 6) { index -> 5.compareTo(table[index]) })\n assertEquals(3, binarySearch(0, 6) { index -> 7.compareTo(table[index]) })\n assertEquals(4, binarySearch(0, 6) { index -> 9.compareTo(table[index]) })\n assertEquals(5, binarySearch(0, 6) { index -> 11.compareTo(table[index]) })\n\n // Search for misses.\n assertEquals(-1, binarySearch(0, 6) { index -> 0.compareTo(table[index]) })\n assertEquals(-2, binarySearch(0, 6) { index -> 2.compareTo(table[index]) })\n assertEquals(-3, binarySearch(0, 6) { index -> 4.compareTo(table[index]) })\n assertEquals(-4, binarySearch(0, 6) { index -> 6.compareTo(table[index]) })\n assertEquals(-5, binarySearch(0, 6) { index -> 8.compareTo(table[index]) })\n assertEquals(-6, binarySearch(0, 6) { index -> 10.compareTo(table[index]) })\n assertEquals(-7, binarySearch(0, 6) { index -> 12.compareTo(table[index]) })\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":170,"symbol":"binarySearchOddSizedRange","kind":"function","lang":"kotlin","code":"@Test fun binarySearchOddSizedRange() {\n val table = listOf(1, 3, 5, 7, 9)\n\n // Search for matches.\n assertEquals(0, binarySearch(0, 5) { index -> 1.compareTo(table[index]) })\n assertEquals(1, binarySearch(0, 5) { index -> 3.compareTo(table[index]) })\n assertEquals(2, binarySearch(0, 5) { index -> 5.compareTo(table[index]) })\n assertEquals(3, binarySearch(0, 5) { index -> 7.compareTo(table[index]) })\n assertEquals(4, binarySearch(0, 5) { index -> 9.compareTo(table[index]) })\n\n // Search for misses.\n assertEquals(-1, binarySearch(0, 5) { index -> 0.compareTo(table[index]) })\n assertEquals(-2, binarySearch(0, 5) { index -> 2.compareTo(table[index]) })\n assertEquals(-3, binarySearch(0, 5) { index -> 4.compareTo(table[index]) })\n assertEquals(-4, binarySearch(0, 5) { index -> 6.compareTo(table[index]) })\n assertEquals(-5, binarySearch(0, 5) { index -> 8.compareTo(table[index]) })\n assertEquals(-6, binarySearch(0, 5) { index -> 10.compareTo(table[index]) })\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":189,"symbol":"binarySearchSingleElementRange","kind":"function","lang":"kotlin","code":"@Test fun binarySearchSingleElementRange() {\n val table = listOf(1)\n\n // Search for matches.\n assertEquals(0, binarySearch(0, 1) { index -> 1.compareTo(table[index]) })\n\n // Search for misses.\n assertEquals(-1, binarySearch(0, 1) { index -> 0.compareTo(table[index]) })\n assertEquals(-2, binarySearch(0, 1) { index -> 2.compareTo(table[index]) })\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":200,"symbol":"binarySearchEmptyRange","kind":"function","lang":"kotlin","code":"@Test fun binarySearchEmptyRange() {\n assertEquals(-1, binarySearch(0, 0) { error(\"unexpected call\") })\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":205,"symbol":"comparePlainAndCompactTables","kind":"function","lang":"kotlin","doc":"Confirm the compact table has the exact same behavior as the plain table.","code":"@Test fun comparePlainAndCompactTables() {\n val buffer = Buffer()\n for (codePoint in 0..0x10ffff) {\n val allowedByTable = table.map(codePoint, buffer)\n val tableMappedTo = buffer.readUtf8()\n\n val allowedByCompactTable = compactTable.map(codePoint, buffer)\n val compactTableMappedTo = buffer.readUtf8()\n\n assertThat(allowedByCompactTable).isEqualTo(allowedByTable)\n assertThat(compactTableMappedTo).isEqualTo(tableMappedTo)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":220,"symbol":"compareConstructedAndGeneratedCompactTables","kind":"function","lang":"kotlin","doc":"Confirm we didn't corrupt any data in code generation.","code":"@Test fun compareConstructedAndGeneratedCompactTables() {\n assertThat(IDNA_MAPPING_TABLE.sections).isEqualTo(compactTable.sections)\n assertThat(IDNA_MAPPING_TABLE.ranges).isEqualTo(compactTable.ranges)\n assertThat(IDNA_MAPPING_TABLE.mappings).isEqualTo(compactTable.mappings)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":226,"symbol":"map","kind":"function","lang":"kotlin","code":"private fun String.map(): String {\n val buffer = Buffer()\n for (codePoint in codePoints()) {\n require(table.map(codePoint, buffer))\n }\n return buffer.readUtf8()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/IdnaMappingTableTest.kt","line":234,"symbol":"mapExpectingErrors","kind":"function","lang":"kotlin","code":"private fun String.mapExpectingErrors(): String {\n val buffer = Buffer()\n var errorCount = 0\n for (codePoint in codePoints()) {\n if (!table.map(codePoint, buffer)) errorCount++\n }\n assertThat(errorCount).isGreaterThan(0)\n return buffer.readUtf8()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":22,"symbol":"PunycodeTest","kind":"class","lang":"kotlin","code":"class PunycodeTest {\n /** https://datatracker.ietf.org/doc/html/rfc3492#section-7.1 */\n @Test fun rfc3492Samples() {\n // (A) Arabic (Egyptian)\n testEncodeDecode(\n unicode = \"ليهمابتكلموشعربي؟\",\n punycode = \"xn--egbpdaj6bu4bxfgehfvwxn\",\n )\n\n // (B) Chinese (simplified)\n testEncodeDecode(\n unicode = \"他们为什么不说中文\",\n punycode = \"xn--ihqwcrb4cv8a8dqg056pqjye\",\n )\n\n // (C) Chinese (traditional)\n testEncodeDecode(\n unicode = \"他們爲什麽不說中文\",\n punycode = \"xn--ihqwctvzc91f659drss3x8bo0yb\",\n )\n\n // (D) Czech\n testEncodeDecode(\n unicode = \"Pročprostěnemluvíčesky\",\n punycode = \"xn--Proprostnemluvesky-uyb24dma41a\",\n )\n\n // (E) Hebrew:\n testEncodeDecode(\n unicode = \"למההםפשוטלאמדבריםעברית\",\n punycode = \"xn--4dbcagdahymbxekheh6e0a7fei0b\",\n )\n\n // (F) Hindi (Devanagari)\n testEncodeDecode(\n unicode = \"यहलोगहिन्दीक्योंनहींबोलसकतेहैं\",\n punycode = \"xn--i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd\",\n )\n\n // (G) Japanese (kanji and hiragana)\n testEncodeDecode(\n unicode = \"なぜみんな日本語を話してくれないのか\",\n punycode = \"xn--n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa\",\n )\n\n // (H) Korean (Han"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":24,"symbol":"rfc3492Samples","kind":"function","lang":"kotlin","doc":"https://datatracker.ietf.org/doc/html/rfc3492#section-7.1","code":"@Test fun rfc3492Samples() {\n // (A) Arabic (Egyptian)\n testEncodeDecode(\n unicode = \"ليهمابتكلموشعربي؟\",\n punycode = \"xn--egbpdaj6bu4bxfgehfvwxn\",\n )\n\n // (B) Chinese (simplified)\n testEncodeDecode(\n unicode = \"他们为什么不说中文\",\n punycode = \"xn--ihqwcrb4cv8a8dqg056pqjye\",\n )\n\n // (C) Chinese (traditional)\n testEncodeDecode(\n unicode = \"他們爲什麽不說中文\",\n punycode = \"xn--ihqwctvzc91f659drss3x8bo0yb\",\n )\n\n // (D) Czech\n testEncodeDecode(\n unicode = \"Pročprostěnemluvíčesky\",\n punycode = \"xn--Proprostnemluvesky-uyb24dma41a\",\n )\n\n // (E) Hebrew:\n testEncodeDecode(\n unicode = \"למההםפשוטלאמדבריםעברית\",\n punycode = \"xn--4dbcagdahymbxekheh6e0a7fei0b\",\n )\n\n // (F) Hindi (Devanagari)\n testEncodeDecode(\n unicode = \"यहलोगहिन्दीक्योंनहींबोलसकतेहैं\",\n punycode = \"xn--i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd\",\n )\n\n // (G) Japanese (kanji and hiragana)\n testEncodeDecode(\n unicode = \"なぜみんな日本語を話してくれないのか\",\n punycode = \"xn--n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa\",\n )\n\n // (H) Korean (Hangul syllables)\n testEncodeDecode(\n unicode = \"세계의모든사람들이한국어를이해한다면얼마나좋을까\",\n pun"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":92,"symbol":"multipleLabels","kind":"function","lang":"kotlin","code":"@Test fun multipleLabels() {\n testEncodeDecode(\n unicode = \"☃.net\",\n punycode = \"xn--n3h.net\",\n )\n testEncodeDecode(\n unicode = \"ålgård.no\",\n punycode = \"xn--lgrd-poac.no\",\n )\n testEncodeDecode(\n unicode = \"個人.香港\",\n punycode = \"xn--gmqw5a.xn--j6w193g\",\n )\n testEncodeDecode(\n unicode = \"упр.срб\",\n punycode = \"xn--o1ach.xn--90a3ac\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":111,"symbol":"nonBasicCodePointInPrefix","kind":"function","lang":"kotlin","code":"@Test fun nonBasicCodePointInPrefix() {\n assertNull(Punycode.decode(\"xn--cåt-n3h\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":115,"symbol":"nonBasicCodePointInInsertionCoding","kind":"function","lang":"kotlin","code":"@Test fun nonBasicCodePointInInsertionCoding() {\n assertNull(Punycode.decode(\"xn--cat-ñ3h\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":119,"symbol":"unterminatedCodePoint","kind":"function","lang":"kotlin","code":"@Test fun unterminatedCodePoint() {\n assertNull(Punycode.decode(\"xn--cat-n\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":123,"symbol":"overflowI","kind":"function","lang":"kotlin","code":"@Test fun overflowI() {\n assertNull(Punycode.decode(\"xn--99999999\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":127,"symbol":"overflowMaxCodePoint","kind":"function","lang":"kotlin","code":"@Test fun overflowMaxCodePoint() {\n assertNull(Punycode.decode(\"xn--a-b.net\"))\n assertNull(Punycode.decode(\"xn--a-9b.net\"))\n assertEquals(\"a՚.net\", Punycode.decode(\"xn--a-99b.net\"))\n assertEquals(\"a溠.net\", Punycode.decode(\"xn--a-999b.net\"))\n assertEquals(\"a\\uD8E2\\uDF5C.net\", Punycode.decode(\"xn--a-9999b.net\"))\n assertNull(Punycode.decode(\"xn--a-99999b.net\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":136,"symbol":"dashInPrefix","kind":"function","lang":"kotlin","code":"@Test fun dashInPrefix() {\n testEncodeDecode(\n unicode = \"klmnöpqrst-uvwxy\",\n punycode = \"xn--klmnpqrst-uvwxy-ctb\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":143,"symbol":"uppercasePunycode","kind":"function","lang":"kotlin","code":"@Test fun uppercasePunycode() {\n testDecodeOnly(\n unicode = \"ليهمابتكلموشعربي؟\",\n punycode = \"XN--EGBPDAJ6BU4BXFGEHFVWXN\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":150,"symbol":"mixedCasePunycode","kind":"function","lang":"kotlin","code":"@Test fun mixedCasePunycode() {\n testDecodeOnly(\n unicode = \"ليهمابتكلموشعربي؟\",\n punycode = \"Xn--EgBpDaJ6Bu4bXfGeHfVwXn\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":161,"symbol":"overflowEncodingOversizedLabel","kind":"function","lang":"kotlin","doc":"It's invalid to have a label longer than 63 characters. If that's requested, the encoder may overflow and return null.","code":"@Test fun overflowEncodingOversizedLabel() {\n val a1000 = \"a\".repeat(1000)\n val a1000MaxCodePoint = a1000 + \"\\udbff\\udfff\"\n testEncodeDecode(\n a1000MaxCodePoint,\n \"xn--$a1000-nc89312g\",\n )\n assertNull(\n Punycode.encode(a1000MaxCodePoint.repeat(2)),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":173,"symbol":"invalidPunycode","kind":"function","lang":"kotlin","code":"@Test fun invalidPunycode() {\n assertNull(Punycode.decode(\"xn--ls8h=\"))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":177,"symbol":"testEncodeDecode","kind":"function","lang":"kotlin","code":"private fun testEncodeDecode(\n unicode: String,\n punycode: String,\n ) {\n assertEquals(unicode, Punycode.decode(punycode))\n assertEquals(punycode, Punycode.encode(unicode))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/idn/PunycodeTest.kt","line":185,"symbol":"testDecodeOnly","kind":"function","lang":"kotlin","code":"private fun testDecodeOnly(\n unicode: String,\n punycode: String,\n ) {\n assertEquals(unicode, Punycode.decode(punycode))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":26,"symbol":"FaultyFileSystem","kind":"class","lang":"kotlin","code":"class FaultyFileSystem constructor(\n delegate: FileSystem?,\n) : ForwardingFileSystem(delegate!!) {\n private val writeFaults: MutableSet = LinkedHashSet()\n private val deleteFaults: MutableSet = LinkedHashSet()\n private val renameFaults: MutableSet = LinkedHashSet()\n\n fun setFaultyWrite(\n file: Path,\n faulty: Boolean,\n ) {\n if (faulty) {\n writeFaults.add(file)\n } else {\n writeFaults.remove(file)\n }\n }\n\n fun setFaultyDelete(\n file: Path,\n faulty: Boolean,\n ) {\n if (faulty) {\n deleteFaults.add(file)\n } else {\n deleteFaults.remove(file)\n }\n }\n\n fun setFaultyRename(\n file: Path,\n faulty: Boolean,\n ) {\n if (faulty) {\n renameFaults.add(file)\n } else {\n renameFaults.remove(file)\n }\n }\n\n @Throws(IOException::class)\n override fun atomicMove(\n source: Path,\n target: Path,\n ) {\n if (renameFaults.contains(source) || renameFaults.contains(target)) throw IOException(\"boom!\")\n super.atomicMove(source, target)\n }\n\n @Throws(IOException::class)\n override fun delete(\n path: Path,\n mustExist: Boolean,\n ) {\n if (deleteFaults.contains(path)) throw IOException(\"boom!\")\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":33,"symbol":"setFaultyWrite","kind":"function","lang":"kotlin","code":"fun setFaultyWrite(\n file: Path,\n faulty: Boolean,\n ) {\n if (faulty) {\n writeFaults.add(file)\n } else {\n writeFaults.remove(file)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":44,"symbol":"setFaultyDelete","kind":"function","lang":"kotlin","code":"fun setFaultyDelete(\n file: Path,\n faulty: Boolean,\n ) {\n if (faulty) {\n deleteFaults.add(file)\n } else {\n deleteFaults.remove(file)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":55,"symbol":"setFaultyRename","kind":"function","lang":"kotlin","code":"fun setFaultyRename(\n file: Path,\n faulty: Boolean,\n ) {\n if (faulty) {\n renameFaults.add(file)\n } else {\n renameFaults.remove(file)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":66,"symbol":"atomicMove","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun atomicMove(\n source: Path,\n target: Path,\n ) {\n if (renameFaults.contains(source) || renameFaults.contains(target)) throw IOException(\"boom!\")\n super.atomicMove(source, target)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":75,"symbol":"delete","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun delete(\n path: Path,\n mustExist: Boolean,\n ) {\n if (deleteFaults.contains(path)) throw IOException(\"boom!\")\n super.delete(path, mustExist)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":84,"symbol":"deleteRecursively","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun deleteRecursively(\n fileOrDirectory: Path,\n mustExist: Boolean,\n ) {\n if (deleteFaults.contains(fileOrDirectory)) throw IOException(\"boom!\")\n super.deleteRecursively(fileOrDirectory, mustExist)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":93,"symbol":"appendingSink","kind":"function","lang":"kotlin","code":"override fun appendingSink(\n file: Path,\n mustExist: Boolean,\n ): Sink = FaultySink(super.appendingSink(file, mustExist), file)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":98,"symbol":"sink","kind":"function","lang":"kotlin","code":"override fun sink(\n file: Path,\n mustCreate: Boolean,\n ): Sink = FaultySink(super.sink(file, mustCreate), file)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":103,"symbol":"FaultySink","kind":"class","lang":"kotlin","code":"inner class FaultySink(\n sink: Sink,\n private val file: Path,\n ) : ForwardingSink(sink) {\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n if (writeFaults.contains(file)) {\n throw IOException(\"boom!\")\n } else {\n super.write(source, byteCount)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/io/FaultyFileSystem.kt","line":107,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n if (writeFaults.contains(file)) {\n throw IOException(\"boom!\")\n } else {\n super.write(source, byteCount)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatformTest.kt","line":28,"symbol":"Jdk8WithJettyBootPlatformTest","kind":"class","lang":"kotlin","code":"class Jdk8WithJettyBootPlatformTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @Test\n fun testBuildsWithJettyBoot() {\n assumeTrue(System.getProperty(\"java.specification.version\") == \"1.8\")\n platform.assumeJettyBootEnabled()\n assertThat(buildIfSupported()).isNotNull()\n }\n\n @Test\n fun testNotBuildWithOther() {\n assumeFalse(System.getProperty(\"java.specification.version\") == \"1.8\")\n assertThat(buildIfSupported()).isNull()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatformTest.kt","line":32,"symbol":"testBuildsWithJettyBoot","kind":"function","lang":"kotlin","code":"@Test\n fun testBuildsWithJettyBoot() {\n assumeTrue(System.getProperty(\"java.specification.version\") == \"1.8\")\n platform.assumeJettyBootEnabled()\n assertThat(buildIfSupported()).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatformTest.kt","line":39,"symbol":"testNotBuildWithOther","kind":"function","lang":"kotlin","code":"@Test\n fun testNotBuildWithOther() {\n assumeFalse(System.getProperty(\"java.specification.version\") == \"1.8\")\n assertThat(buildIfSupported()).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk9PlatformTest.kt","line":29,"symbol":"Jdk9PlatformTest","kind":"class","lang":"kotlin","code":"class Jdk9PlatformTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @Test\n fun buildsWhenJdk9() {\n platform.assumeJdk9()\n assertThat(buildIfSupported()).isNotNull()\n }\n\n @Test\n fun buildsWhenJdk8() {\n platform.assumeJdk8()\n try {\n SSLSocket::class.java.getMethod(\"getApplicationProtocol\")\n // also present on JDK8 after build 252.\n assertThat(buildIfSupported()).isNotNull()\n } catch (nsme: NoSuchMethodException) {\n assertThat(buildIfSupported()).isNull()\n }\n }\n\n @Test\n fun testToStringIsClassname() {\n assertThat(Jdk9Platform().toString()).isEqualTo(\"Jdk9Platform\")\n }\n\n @Test\n fun selectedProtocolIsNullWhenSslSocketThrowsExceptionForApplicationProtocol() {\n platform.assumeJdk9()\n val applicationProtocolUnsupported =\n object : DelegatingSSLSocket(null) {\n override fun getApplicationProtocol(): String = throw UnsupportedOperationException(\"Mock exception\")\n }\n assertThat(Jdk9Platform().getSelectedProtocol(applicationProtocolUnsupported)).isNull()\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk9PlatformTest.kt","line":33,"symbol":"buildsWhenJdk9","kind":"function","lang":"kotlin","code":"@Test\n fun buildsWhenJdk9() {\n platform.assumeJdk9()\n assertThat(buildIfSupported()).isNotNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk9PlatformTest.kt","line":39,"symbol":"buildsWhenJdk8","kind":"function","lang":"kotlin","code":"@Test\n fun buildsWhenJdk8() {\n platform.assumeJdk8()\n try {\n SSLSocket::class.java.getMethod(\"getApplicationProtocol\")\n // also present on JDK8 after build 252.\n assertThat(buildIfSupported()).isNotNull()\n } catch (nsme: NoSuchMethodException) {\n assertThat(buildIfSupported()).isNull()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk9PlatformTest.kt","line":51,"symbol":"testToStringIsClassname","kind":"function","lang":"kotlin","code":"@Test\n fun testToStringIsClassname() {\n assertThat(Jdk9Platform().toString()).isEqualTo(\"Jdk9Platform\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk9PlatformTest.kt","line":56,"symbol":"selectedProtocolIsNullWhenSslSocketThrowsExceptionForApplicationProtocol","kind":"function","lang":"kotlin","code":"@Test\n fun selectedProtocolIsNullWhenSslSocketThrowsExceptionForApplicationProtocol() {\n platform.assumeJdk9()\n val applicationProtocolUnsupported =\n object : DelegatingSSLSocket(null) {\n override fun getApplicationProtocol(): String = throw UnsupportedOperationException(\"Mock exception\")\n }\n assertThat(Jdk9Platform().getSelectedProtocol(applicationProtocolUnsupported)).isNull()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/Jdk9PlatformTest.kt","line":61,"symbol":"getApplicationProtocol","kind":"function","lang":"kotlin","code":"override fun getApplicationProtocol(): String = throw UnsupportedOperationException(\"Mock exception\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt","line":25,"symbol":"PlatformTest","kind":"class","lang":"kotlin","code":"class PlatformTest {\n @RegisterExtension\n var platform = PlatformRule()\n\n @Test\n fun alwaysBuilds() {\n Platform()\n }\n\n /** Guard against the default value changing by accident. */\n @Test\n fun defaultPrefix() {\n assertThat(Platform().prefix).isEqualTo(\"OkHttp\")\n }\n\n @Test\n fun testToStringIsClassname() {\n assertThat(Platform().toString()).isEqualTo(\"Platform\")\n }\n\n @Test\n fun testNotAndroid() {\n platform.assumeNotAndroid()\n\n // This is tautological so just confirms that it runs.\n assertThat(isAndroid).isEqualTo(false)\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt","line":29,"symbol":"alwaysBuilds","kind":"function","lang":"kotlin","code":"@Test\n fun alwaysBuilds() {\n Platform()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt","line":35,"symbol":"defaultPrefix","kind":"function","lang":"kotlin","doc":"Guard against the default value changing by accident.","code":"@Test\n fun defaultPrefix() {\n assertThat(Platform().prefix).isEqualTo(\"OkHttp\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt","line":40,"symbol":"testToStringIsClassname","kind":"function","lang":"kotlin","code":"@Test\n fun testToStringIsClassname() {\n assertThat(Platform().toString()).isEqualTo(\"Platform\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/platform/PlatformTest.kt","line":45,"symbol":"testNotAndroid","kind":"function","lang":"kotlin","code":"@Test\n fun testNotAndroid() {\n platform.assumeNotAndroid()\n\n // This is tautological so just confirms that it runs.\n assertThat(isAndroid).isEqualTo(false)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":46,"symbol":"PublicSuffixListGenerator","kind":"class","lang":"kotlin","doc":"The intent is to use this class to update the list periodically by manually running the main method. This should be run from the top-level okhttp directory. The resulting file is used by [PublicSuffixDatabase].","code":"class PublicSuffixListGenerator(\n projectRoot: Path = \".\".toPath(),\n val fileSystem: FileSystem = FileSystem.SYSTEM,\n val client: OkHttpClient = OkHttpClient(),\n) {\n private val testResources = projectRoot / \"okhttp/src/jvmTest/resources\"\n private val publicSuffixListDotDat = testResources / \"okhttp3/internal/publicsuffix/public_suffix_list.dat\"\n private val outputFile = testResources / PUBLIC_SUFFIX_RESOURCE\n\n val request = Request(\"https://publicsuffix.org/list/public_suffix_list.dat\".toHttpUrl())\n\n suspend fun import() {\n check(fileSystem.metadata(testResources).isDirectory)\n\n updateLocalFile()\n\n val importResults = readImportResults()\n\n writeOutputFile(importResults)\n }\n\n private suspend fun updateLocalFile() =\n withContext(Dispatchers.IO) {\n client.newCall(request).executeAsync().use { response ->\n fileSystem.sink(publicSuffixListDotDat).buffer().use { sink ->\n sink.writeAll(response.body.source())\n }\n }\n }\n\n private suspend fun readImportResults(): ImportResults =\n withContext(Dispatchers.IO) {\n val sortedRules: SortedSet = TreeSet()\n val sortedExceptionRules: SortedSet = TreeSe"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":57,"symbol":"import","kind":"function","lang":"kotlin","code":"suspend fun import() {\n check(fileSystem.metadata(testResources).isDirectory)\n\n updateLocalFile()\n\n val importResults = readImportResults()\n\n writeOutputFile(importResults)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":67,"symbol":"updateLocalFile","kind":"function","lang":"kotlin","code":"private suspend fun updateLocalFile() =\n withContext(Dispatchers.IO) {\n client.newCall(request).executeAsync().use { response ->\n fileSystem.sink(publicSuffixListDotDat).buffer().use { sink ->\n sink.writeAll(response.body.source())\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":76,"symbol":"readImportResults","kind":"function","lang":"kotlin","code":"private suspend fun readImportResults(): ImportResults =\n withContext(Dispatchers.IO) {\n val sortedRules: SortedSet = TreeSet()\n val sortedExceptionRules: SortedSet = TreeSet()\n var totalRuleBytes = 0\n var totalExceptionRuleBytes = 0\n\n fileSystem.source(publicSuffixListDotDat).buffer().use { source ->\n while (!source.exhausted()) {\n var rule: ByteString = source.readUtf8LineStrict().toRule() ?: continue\n\n if (rule.startsWith(EXCEPTION_RULE_MARKER)) {\n rule = rule.substring(1)\n // We use '\\n' for end of value.\n totalExceptionRuleBytes += rule.size + 1\n sortedExceptionRules.add(rule)\n } else {\n totalRuleBytes += rule.size + 1 // We use '\\n' for end of value.\n sortedRules.add(rule)\n }\n }\n }\n\n ImportResults(sortedRules, sortedExceptionRules, totalRuleBytes, totalExceptionRuleBytes)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":102,"symbol":"toRule","kind":"function","lang":"kotlin","code":"private fun String.toRule(): ByteString? {\n if (trim { it <= ' ' }.isEmpty() || startsWith(\"//\")) return null\n if (contains(WILDCARD_CHAR)) {\n assertWildcardRule(this)\n }\n return encodeUtf8()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":110,"symbol":"ImportResults","kind":"class","lang":"kotlin","code":"data class ImportResults(\n val sortedRules: SortedSet,\n val sortedExceptionRules: SortedSet,\n val totalRuleBytes: Int,\n val totalExceptionRuleBytes: Int,\n ) {\n fun writeOut(sink: BufferedSink) {\n with(sink) {\n writeInt(totalRuleBytes)\n for (domain in sortedRules) {\n write(domain).writeByte(NEWLINE)\n }\n writeInt(totalExceptionRuleBytes)\n for (domain in sortedExceptionRules) {\n write(domain).writeByte(NEWLINE)\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":116,"symbol":"writeOut","kind":"function","lang":"kotlin","code":"fun writeOut(sink: BufferedSink) {\n with(sink) {\n writeInt(totalRuleBytes)\n for (domain in sortedRules) {\n write(domain).writeByte(NEWLINE)\n }\n writeInt(totalExceptionRuleBytes)\n for (domain in sortedExceptionRules) {\n write(domain).writeByte(NEWLINE)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":130,"symbol":"writeOutputFile","kind":"function","lang":"kotlin","code":"private suspend fun writeOutputFile(importResults: ImportResults) =\n withContext(Dispatchers.IO) {\n fileSystem.write(outputFile) {\n importResults.writeOut(this)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":144,"symbol":"assertWildcardRule","kind":"function","lang":"kotlin","doc":"These assertions ensure the [PublicSuffixDatabase] remains correct. The specification is very flexible regarding wildcard rules, but this flexibility is not something currently used in practice. To simplify the implementation, we've avoided implementing the flexible rules in favor of supporting what's actually used in practice. That means if these assertions ever fail, the implementation will need to be revisited to support a more flexible rule.","code":"private fun assertWildcardRule(rule: String) {\n check(rule.startsWith(WILDCARD_CHAR)) {\n \"\"\"Wildcard Assertion Failure: '$rule'\nA wildcard rule was added with a wildcard that is not in leftmost position! We'll need to change the ${PublicSuffixDatabase::class.java.name} to handle this.\"\"\"\n }\n check(rule.indexOf(WILDCARD_CHAR, 1) == -1) {\n \"\"\"Wildcard Assertion Failure: '$rule'\nA wildcard rule was added with multiple wildcards! We'll need to change ${PublicSuffixDatabase::class.java.name} to handle this.\"\"\"\n }\n check(rule.length != 1) {\n \"\"\"Wildcard Assertion Failure: '$rule'\nA wildcard rule was added that wildcards the first level! We'll need to change the ${PublicSuffixDatabase::class.java.name} to handle this.\"\"\"\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixListGenerator.kt","line":166,"symbol":"main","kind":"function","lang":"kotlin","code":"suspend fun main() {\n val publicSuffixListGenerator = PublicSuffixListGenerator()\n\n try {\n publicSuffixListGenerator.import()\n } finally {\n publicSuffixListGenerator.client.run {\n connectionPool.evictAll()\n dispatcher.executorService.shutdownNow()\n }\n }\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixTesting.jvm.kt","line":22,"symbol":"PublicSuffixTestRunner","kind":"class","lang":"kotlin","code":"actual class PublicSuffixTestRunner(\n klass: Class<*>,\n) : Runner() {\n private val delegate = JUnit4(klass)\n\n override fun getDescription() = delegate.description\n\n override fun run(notifier: RunNotifier?) = delegate.run(notifier)\n\n override fun testCount() = delegate.testCount()\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixTesting.jvm.kt","line":27,"symbol":"getDescription","kind":"function","lang":"kotlin","code":"override fun getDescription() = delegate.description"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixTesting.jvm.kt","line":29,"symbol":"run","kind":"function","lang":"kotlin","code":"override fun run(notifier: RunNotifier?) = delegate.run(notifier)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixTesting.jvm.kt","line":31,"symbol":"testCount","kind":"function","lang":"kotlin","code":"override fun testCount() = delegate.testCount()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/publicsuffix/PublicSuffixTesting.jvm.kt","line":34,"symbol":"beforePublicSuffixTest","kind":"function","lang":"kotlin","code":"actual fun beforePublicSuffixTest() {\n}"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":50,"symbol":"CertificatePinnerChainValidationTest","kind":"class","lang":"kotlin","code":"class CertificatePinnerChainValidationTest {\n @RegisterExtension\n var platform = PlatformRule()\n\n @RegisterExtension\n var clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach\n fun setup() {\n platform.assumeNotBouncyCastle()\n }\n\n /**\n * The pinner should pull the root certificate from the trust manager.\n */\n @Test\n fun pinRootNotPresentInChain() {\n // Fails on 11.0.1 https://github.com/lysine-dev/okhttp/issues/4703\n val rootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .commonName(\"root\")\n .build()\n val intermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(rootCa)\n .certificateAuthority(0)\n .serialNumber(2L)\n .commonName(\"intermediate_ca\")\n .build()\n val certificate =\n HeldCertificate\n .Builder()\n .signedBy(intermediateCa)\n .serialNumber(3L)\n .commonName(server.hostName)\n .build()\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(server.hostName, pin(rootCa.certificate))\n .build()\n val handshakeCe"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":60,"symbol":"setup","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setup() {\n platform.assumeNotBouncyCastle()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":68,"symbol":"pinRootNotPresentInChain","kind":"function","lang":"kotlin","doc":"The pinner should pull the root certificate from the trust manager.","code":"@Test\n fun pinRootNotPresentInChain() {\n // Fails on 11.0.1 https://github.com/lysine-dev/okhttp/issues/4703\n val rootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .commonName(\"root\")\n .build()\n val intermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(rootCa)\n .certificateAuthority(0)\n .serialNumber(2L)\n .commonName(\"intermediate_ca\")\n .build()\n val certificate =\n HeldCertificate\n .Builder()\n .signedBy(intermediateCa)\n .serialNumber(3L)\n .commonName(server.hostName)\n .build()\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(server.hostName, pin(rootCa.certificate))\n .build()\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(rootCa.certificate)\n .build()\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":140,"symbol":"pinIntermediatePresentInChain","kind":"function","lang":"kotlin","doc":"The pinner should accept an intermediate from the server's chain.","code":"@Test\n fun pinIntermediatePresentInChain() {\n // Fails on 11.0.1 https://github.com/lysine-dev/okhttp/issues/4703\n val rootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .commonName(\"root\")\n .build()\n val intermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(rootCa)\n .certificateAuthority(0)\n .serialNumber(2L)\n .commonName(\"intermediate_ca\")\n .build()\n val certificate =\n HeldCertificate\n .Builder()\n .signedBy(intermediateCa)\n .serialNumber(3L)\n .commonName(server.hostName)\n .build()\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(server.hostName, pin(intermediateCa.certificate))\n .build()\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(rootCa.certificate)\n .build()\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVer"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":233,"symbol":"unrelatedPinnedLeafCertificateInChain","kind":"function","lang":"kotlin","code":"@Test\n fun unrelatedPinnedLeafCertificateInChain() {\n // https://github.com/lysine-dev/okhttp/issues/4729\n platform.expectFailureOnConscryptPlatform()\n platform.expectFailureOnCorrettoPlatform()\n platform.expectFailureOnLoomPlatform()\n\n // Start with a trusted root CA certificate.\n val rootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .commonName(\"root\")\n .build()\n\n // Add a good intermediate CA, and have that issue a good certificate to localhost. Prepare an\n // SSL context for an HTTP client under attack. It includes the trusted CA and a pinned\n // certificate.\n val goodIntermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(rootCa)\n .certificateAuthority(0)\n .serialNumber(2L)\n .commonName(\"good_intermediate_ca\")\n .build()\n val goodCertificate =\n HeldCertificate\n .Builder()\n .signedBy(goodIntermediateCa)\n .serialNumber(3L)\n .commonName(server.hostName)\n .build()\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(server.hostName, pin(goodCertificate.certif"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":337,"symbol":"unrelatedPinnedIntermediateCertificateInChain","kind":"function","lang":"kotlin","code":"@Test\n fun unrelatedPinnedIntermediateCertificateInChain() {\n // https://github.com/lysine-dev/okhttp/issues/4729\n platform.expectFailureOnConscryptPlatform()\n platform.expectFailureOnCorrettoPlatform()\n platform.expectFailureOnLoomPlatform()\n\n // Start with two root CA certificates, one is good and the other is compromised.\n val rootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .commonName(\"root\")\n .build()\n val compromisedRootCa =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .certificateAuthority(1)\n .commonName(\"compromised_root\")\n .build()\n\n // Add a good intermediate CA, and have that issue a good certificate to localhost. Prepare an\n // SSL context for an HTTP client under attack. It includes the trusted CA and a pinned\n // certificate.\n val goodIntermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(rootCa)\n .certificateAuthority(0)\n .serialNumber(3L)\n .commonName(\"intermediate_ca\")\n .build()\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(ser"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":507,"symbol":"signersMustHaveCaBitSet","kind":"function","lang":"kotlin","doc":"Some implementations fail the TLS handshake when they see the long chain, and don't give CertificatePinner the opportunity to produce a different chain from their own. This includes the OpenJDK 11 TLS implementation, which itself fails the handshake when it encounters a non-CA certificate.","code":"@Test\n fun signersMustHaveCaBitSet() {\n val attackerCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(4)\n .commonName(\"attacker ca\")\n .build()\n val attackerIntermediate =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .certificateAuthority(3)\n .commonName(\"attacker\")\n .signedBy(attackerCa)\n .build()\n val pinnedRoot =\n HeldCertificate\n .Builder()\n .serialNumber(3L)\n .certificateAuthority(2)\n .commonName(\"pinned root\")\n .signedBy(attackerIntermediate)\n .build()\n val pinnedIntermediate =\n HeldCertificate\n .Builder()\n .serialNumber(4L)\n .certificateAuthority(1)\n .commonName(\"pinned intermediate\")\n .signedBy(pinnedRoot)\n .build()\n val attackerSwitch =\n HeldCertificate\n .Builder()\n .serialNumber(5L)\n .keyPair(attackerIntermediate.keyPair) // share keys between compromised CA and leaf!\n .commonName(\"attacker\")\n .addSubjectAlternativeName(\"attacker.com\")\n .signedBy(pinnedIntermediate)\n .build()\n val phonyVictim ="} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":641,"symbol":"intermediateMustNotHaveMoreIntermediatesThanSigner","kind":"function","lang":"kotlin","doc":"-> pinnedRoot (trusted by CertificatePinner) -> compromisedIntermediate (max intermediates: 0) -> attackerIntermediate (max intermediates: 0) -> phonyVictim ```","code":"@Test\n fun intermediateMustNotHaveMoreIntermediatesThanSigner() {\n val attackerCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(2)\n .commonName(\"attacker ca\")\n .build()\n val pinnedRoot =\n HeldCertificate\n .Builder()\n .serialNumber(2L)\n .certificateAuthority(1)\n .commonName(\"pinned root\")\n .signedBy(attackerCa)\n .build()\n val compromisedIntermediate =\n HeldCertificate\n .Builder()\n .serialNumber(3L)\n .certificateAuthority(0)\n .commonName(\"compromised intermediate\")\n .signedBy(pinnedRoot)\n .build()\n val attackerIntermediate =\n HeldCertificate\n .Builder()\n .keyPair(attackerCa.keyPair) // Share keys between compromised CA and intermediate!\n .serialNumber(4L)\n .certificateAuthority(0) // More intermediates than permitted by signer!\n .commonName(\"attacker intermediate\")\n .signedBy(compromisedIntermediate)\n .build()\n val phonyVictim =\n HeldCertificate\n .Builder()\n .serialNumber(5L)\n .signedBy(attackerIntermediate)\n .addSubjectAlte"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":727,"symbol":"lonePinnedCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun lonePinnedCertificate() {\n val onlyCertificate =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .commonName(\"root\")\n .build()\n val certificatePinner =\n CertificatePinner\n .Builder()\n .add(server.hostName, pin(onlyCertificate.certificate))\n .build()\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(onlyCertificate.certificate)\n .build()\n val client =\n clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .certificatePinner(certificatePinner)\n .build()\n val serverHandshakeCertificates =\n HandshakeCertificates\n .Builder()\n .heldCertificate(onlyCertificate)\n .build()\n server.useHttps(serverHandshakeCertificates.sslSocketFactory())\n\n // The request should complete successfully.\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call1 =\n client.newCall(\n "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/CertificatePinnerChainValidationTest.kt","line":779,"symbol":"newServerSocketFactory","kind":"function","lang":"kotlin","code":"private fun newServerSocketFactory(\n heldCertificate: HeldCertificate,\n vararg intermediates: X509Certificate,\n ): SSLSocketFactory {\n // Test setup fails on JDK9\n // java.security.KeyStoreException: Certificate chain is not valid\n // at sun.security.pkcs12.PKCS12KeyStore.setKeyEntry\n // http://openjdk.java.net/jeps/229\n // http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/2c1c21d11e58/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java#l596\n val keystoreType = if (platform.isJdk9()) \"JKS\" else null\n val x509KeyManager = newKeyManager(keystoreType, heldCertificate, *intermediates)\n val trustManager =\n newTrustManager(\n keystoreType,\n emptyList(),\n emptyList(),\n )\n val sslContext = get().newSSLContext()\n sslContext.init(\n arrayOf(x509KeyManager),\n arrayOf(trustManager),\n SecureRandom(),\n )\n return sslContext.socketFactory\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":66,"symbol":"ClientAuthTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass ClientAuthTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private lateinit var serverRootCa: HeldCertificate\n private lateinit var serverIntermediateCa: HeldCertificate\n private lateinit var serverCert: HeldCertificate\n private lateinit var clientRootCa: HeldCertificate\n private lateinit var clientIntermediateCa: HeldCertificate\n private lateinit var clientCert: HeldCertificate\n\n @BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n platform.assumeNotBouncyCastle()\n serverRootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .commonName(\"root\")\n .addSubjectAlternativeName(\"root_ca.com\")\n .build()\n serverIntermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(serverRootCa)\n .certificateAuthority(0)\n .serialNumber(2L)\n .commonName(\"intermediate_ca\")\n .addSubjectAlternativeName(\"intermediate_ca.com\")\n .build()\n serverCert =\n HeldCertificate\n .Builder()\n .s"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":84,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n platform.assumeNotBouncyCastle()\n serverRootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .commonName(\"root\")\n .addSubjectAlternativeName(\"root_ca.com\")\n .build()\n serverIntermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(serverRootCa)\n .certificateAuthority(0)\n .serialNumber(2L)\n .commonName(\"intermediate_ca\")\n .addSubjectAlternativeName(\"intermediate_ca.com\")\n .build()\n serverCert =\n HeldCertificate\n .Builder()\n .signedBy(serverIntermediateCa)\n .serialNumber(3L)\n .commonName(\"Local Host\")\n .addSubjectAlternativeName(server.hostName)\n .build()\n clientRootCa =\n HeldCertificate\n .Builder()\n .serialNumber(1L)\n .certificateAuthority(1)\n .commonName(\"root\")\n .addSubjectAlternativeName(\"root_ca.com\")\n .build()\n clientIntermediateCa =\n HeldCertificate\n .Builder()\n .signedBy(serverRootCa)\n .certificateAuthority(0)\n .serialNumber(2L)\n .common"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":140,"symbol":"clientAuthForWants","kind":"function","lang":"kotlin","code":"@Test\n fun clientAuthForWants() {\n val client = buildClient(clientCert, clientIntermediateCa.certificate)\n val socketFactory = buildServerSslSocketFactory()\n server.useHttps(socketFactory)\n server.requestClientAuth()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n val response = call.execute()\n assertThat(response.handshake!!.peerPrincipal)\n .isEqualTo(X500Principal(\"CN=Local Host\"))\n assertThat(response.handshake!!.localPrincipal)\n .isEqualTo(X500Principal(\"CN=Jethro Willis\"))\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":161,"symbol":"clientAuthForNeeds","kind":"function","lang":"kotlin","code":"@Test\n fun clientAuthForNeeds() {\n val client = buildClient(clientCert, clientIntermediateCa.certificate)\n val socketFactory = buildServerSslSocketFactory()\n server.useHttps(socketFactory)\n server.requireClientAuth()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n val response = call.execute()\n assertThat(response.handshake!!.peerPrincipal).isEqualTo(\n X500Principal(\"CN=Local Host\"),\n )\n assertThat(response.handshake!!.localPrincipal).isEqualTo(\n X500Principal(\"CN=Jethro Willis\"),\n )\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":184,"symbol":"clientAuthSkippedForNone","kind":"function","lang":"kotlin","code":"@Test\n fun clientAuthSkippedForNone() {\n val client = buildClient(clientCert, clientIntermediateCa.certificate)\n val socketFactory = buildServerSslSocketFactory()\n server.useHttps(socketFactory)\n server.noClientAuth()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n val response = call.execute()\n assertThat(response.handshake!!.peerPrincipal).isEqualTo(\n X500Principal(\"CN=Local Host\"),\n )\n assertThat(response.handshake!!.localPrincipal).isNull()\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":205,"symbol":"missingClientAuthSkippedForWantsOnly","kind":"function","lang":"kotlin","code":"@Test\n fun missingClientAuthSkippedForWantsOnly() {\n val client = buildClient(null, clientIntermediateCa.certificate)\n val socketFactory = buildServerSslSocketFactory()\n server.useHttps(socketFactory)\n server.requestClientAuth()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n val response = call.execute()\n assertThat(response.handshake!!.peerPrincipal).isEqualTo(\n X500Principal(\"CN=Local Host\"),\n )\n assertThat(response.handshake!!.localPrincipal).isNull()\n assertThat(response.body.string()).isEqualTo(\"abc\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":226,"symbol":"missingClientAuthFailsForNeeds","kind":"function","lang":"kotlin","code":"@Flaky\n @RetryingTest(5)\n fun missingClientAuthFailsForNeeds() {\n // Fails with 11.0.1 https://github.com/lysine-dev/okhttp/issues/4598\n // StreamReset stream was reset: PROT...\n val client = buildClient(null, clientIntermediateCa.certificate)\n val socketFactory = buildServerSslSocketFactory()\n server.useHttps(socketFactory)\n server.requireClientAuth()\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n assertFailsWith {\n call.execute()\n }.also { expected ->\n when (expected) {\n is SSLHandshakeException -> {\n // JDK 11+\n }\n\n is SSLException -> {\n // javax.net.ssl.SSLException: readRecord\n }\n\n is SocketException -> {\n // Conscrypt, JDK 8 (>= 292), JDK 9\n }\n\n else -> {\n assertThat(expected.message).isEqualTo(\"exhausted all routes\")\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":259,"symbol":"commonNameIsNotTrusted","kind":"function","lang":"kotlin","code":"@Test\n fun commonNameIsNotTrusted() {\n serverCert =\n HeldCertificate\n .Builder()\n .signedBy(serverIntermediateCa)\n .serialNumber(3L)\n .commonName(server.hostName)\n .addSubjectAlternativeName(\"different-host.com\")\n .build()\n val client = buildClient(clientCert, clientIntermediateCa.certificate)\n val socketFactory = buildServerSslSocketFactory()\n server.useHttps(socketFactory)\n server.requireClientAuth()\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n assertFailsWith {\n call.execute()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":279,"symbol":"invalidClientAuthFails","kind":"function","lang":"kotlin","code":"@Test\n fun invalidClientAuthFails() {\n // Fails with https://github.com/lysine-dev/okhttp/issues/4598\n // StreamReset stream was reset: PROT...\n val clientCert2 =\n HeldCertificate\n .Builder()\n .serialNumber(4L)\n .commonName(\"Jethro Willis\")\n .build()\n val client = buildClient(clientCert2)\n val socketFactory = buildServerSslSocketFactory()\n server.useHttps(socketFactory)\n server.requireClientAuth()\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n assertFailsWith {\n call.execute()\n }.also { expected ->\n when (expected) {\n is SSLHandshakeException -> {\n // JDK 11+\n }\n\n is SSLException -> {\n // javax.net.ssl.SSLException: readRecord\n }\n\n is SocketException -> {\n // Conscrypt, JDK 8 (>= 292), JDK 9\n }\n\n is ConnectionShutdownException -> {\n // It didn't fail until it reached the application layer.\n }\n\n else -> {\n assertThat(expected.message).isEqualTo(\"exhausted all routes\")\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":321,"symbol":"invalidClientAuthEvents","kind":"function","lang":"kotlin","code":"@Test\n fun invalidClientAuthEvents() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .build(),\n )\n clientCert =\n HeldCertificate\n .Builder()\n .signedBy(clientIntermediateCa)\n .serialNumber(4L)\n .commonName(\"Jethro Willis\")\n .addSubjectAlternativeName(\"jethrowillis.com\")\n .validityInterval(1, 2)\n .build()\n var client = buildClient(clientCert, clientIntermediateCa.certificate)\n val eventRecorder = EventRecorder()\n client =\n client\n .newBuilder()\n .eventListener(eventRecorder.eventListener)\n .build()\n val socketFactory = buildServerSslSocketFactory()\n server.useHttps(socketFactory)\n server.requireClientAuth()\n val call = client.newCall(Request.Builder().url(server.url(\"/\")).build())\n assertFailsWith {\n call.execute()\n }\n\n // Observed Events are variable\n // JDK 14\n // CallStart, ProxySelectStart, ProxySelectEnd, DnsStart, DnsEnd, ConnectStart, SecureConnectStart,\n // SecureConnectEnd, ConnectEnd, ConnectionAcquired, RequestHeadersStart, RequestHeadersEnd,\n // ResponseFailed, ConnectionReleased, CallF"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":377,"symbol":"buildClient","kind":"function","lang":"kotlin","code":"private fun buildClient(\n heldCertificate: HeldCertificate?,\n vararg intermediates: X509Certificate,\n ): OkHttpClient {\n val builder =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(serverRootCa.certificate)\n if (heldCertificate != null) {\n builder.heldCertificate(heldCertificate, *intermediates)\n }\n val handshakeCertificates = builder.build()\n return clientTestRule\n .newClientBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).build()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/ClientAuthTest.kt","line":397,"symbol":"buildServerSslSocketFactory","kind":"function","lang":"kotlin","code":"private fun buildServerSslSocketFactory(): SSLSocketFactory {\n // The test uses JDK default SSL Context instead of the Platform provided one\n // as Conscrypt seems to have some differences, we only want to test client side here.\n return try {\n val keyManager =\n newKeyManager(\n null,\n serverCert,\n serverIntermediateCa.certificate,\n )\n val trustManager =\n newTrustManager(\n null,\n Arrays.asList(serverRootCa.certificate, clientRootCa.certificate),\n emptyList(),\n )\n val sslContext = SSLContext.getInstance(\"TLS\")\n sslContext.init(\n arrayOf(keyManager),\n arrayOf(trustManager),\n SecureRandom(),\n )\n sslContext.socketFactory\n } catch (e: GeneralSecurityException) {\n throw AssertionError(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":43,"symbol":"HostnameVerifierTest","kind":"class","lang":"kotlin","doc":"Tests for our hostname verifier. Most of these tests are from AOSP, which itself includes tests from the Apache HTTP Client test suite.","code":"class HostnameVerifierTest {\n private val verifier = OkHostnameVerifier\n\n @RegisterExtension\n var platform = PlatformRule()\n\n @Test fun verify() {\n val session = FakeSSLSession()\n assertThat(verifier.verify(\"localhost\", session)).isFalse()\n }\n\n @Test fun verifyCn() {\n // CN=foo.com\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n zerA/ZtrlU"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":49,"symbol":"verify","kind":"function","lang":"kotlin","code":"@Test fun verify() {\n val session = FakeSSLSession()\n assertThat(verifier.verify(\"localhost\", session)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":54,"symbol":"verifyCn","kind":"function","lang":"kotlin","code":"@Test fun verifyCn() {\n // CN=foo.com\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0T"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":91,"symbol":"verifyNonAsciiCn","kind":"function","lang":"kotlin","code":"@Test fun verifyNonAsciiCn() {\n // CN=花子.co.jp\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB\n FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU\n g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc\n wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t\n 7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn\n AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD\n qUYxqJUlPGlMqrKb3fCFiT3eX"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":127,"symbol":"verifySubjectAlt","kind":"function","lang":"kotlin","code":"@Test fun verifySubjectAlt() {\n // CN=foo.com, subjectAlt=bar.com\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n JTxpTKqym93whYk93l3o"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":171,"symbol":"verifyNonAsciiSubjectAlt","kind":"function","lang":"kotlin","doc":"Ignored due to incompatibilities between Android and Java on how non-ASCII subject alt names are parsed. Android fails to parse these, which means we fall back to the CN. The RI does parse them, so the CN is unused.","code":"@Test fun verifyNonAsciiSubjectAlt() {\n // Expecting actual:\n // [\"bar.com\", \"花子.co.jp\"]\n // to contain exactly (and in same order):\n // [\"bar.com\", \"������.co.jp\"]\n platform.assumeNotBouncyCastle()\n\n // CN=foo.com, subjectAlt=bar.com, subjectAlt=花子.co.jp\n // (hanako.co.jp in kanji)\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAU"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":231,"symbol":"verifySubjectAltOnly","kind":"function","lang":"kotlin","code":"@Test fun verifySubjectAltOnly() {\n // subjectAlt=foo.com\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv\n bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA\n fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt\n xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe\n Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8\n ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz\n jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5\n 5c0CAwEAAaOBkDCBjTAJBgNVHRME"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":269,"symbol":"verifyMultipleCn","kind":"function","lang":"kotlin","code":"@Test fun verifyMultipleCn() {\n // CN=foo.com, CN=bar.com, CN=花子.co.jp\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x\n CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV\n MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv\n loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf\n bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV\n Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva\n h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB\n T"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":310,"symbol":"verifyWilcardCn","kind":"function","lang":"kotlin","code":"@Test fun verifyWilcardCn() {\n // CN=*.foo.com\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3s"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":348,"symbol":"verifyWilcardCnOnTld","kind":"function","lang":"kotlin","code":"@Test fun verifyWilcardCnOnTld() {\n // It's the CA's responsibility to not issue broad-matching certificates!\n // CN=*.co.jp\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs\n aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n 07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n BqnGd87xQU3FVZI4tbtkB+KzjD9zz8Q"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":390,"symbol":"testWilcardNonAsciiSubjectAlt","kind":"function","lang":"kotlin","doc":"Previously ignored due to incompatibilities between Android and Java on how non-ASCII subject alt names are parsed. Android fails to parse these, which means we fall back to the CN. The RI does parse them, so the CN is unused.","code":"@Test fun testWilcardNonAsciiSubjectAlt() {\n // Expecting actual:\n // [\"*.bar.com\", \"*.花子.co.jp\"]\n // to contain exactly (and in same order):\n // [\"*.bar.com\", \"*.������.co.jp\"]\n platform.assumeNotBouncyCastle()\n\n // CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.花子.co.jp\n // (*.hanako.co.jp in kanji)\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx\n CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBII"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":454,"symbol":"subjectAltUsesLocalDomainAndIp","kind":"function","lang":"kotlin","code":"@Test fun subjectAltUsesLocalDomainAndIp() {\n // cat cert.cnf\n // [req]\n // distinguished_name=distinguished_name\n // req_extensions=req_extensions\n // x509_extensions=x509_extensions\n // [distinguished_name]\n // [req_extensions]\n // [x509_extensions]\n // subjectAltName=DNS:localhost.localdomain,DNS:localhost,IP:127.0.0.1\n //\n // $ openssl req -x509 -nodes -days 36500 -subj '/CN=localhost' -config ./cert.cnf \\\n // -newkey rsa:512 -out cert.pem\n val certificate =\n certificate(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBWDCCAQKgAwIBAgIJANS1EtICX2AZMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNV\n BAMTCWxvY2FsaG9zdDAgFw0xMjAxMDIxOTA4NThaGA8yMTExMTIwOTE5MDg1OFow\n FDESMBAGA1UEAxMJbG9jYWxob3N0MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPpt\n atK8r4/hf4hSIs0os/BSlQLbRBaK9AfBReM4QdAklcQqe6CHsStKfI8pp0zs7Ptg\n PmMdpbttL0O7mUboBC8CAwEAAaM1MDMwMQYDVR0RBCowKIIVbG9jYWxob3N0Lmxv\n Y2FsZG9tYWlugglsb2NhbGhvc3SHBH8AAAEwDQYJKoZIhvcNAQEFBQADQQD0ntfL\n DCzOCv9Ma6Lv5o5jcYWVxvBSTsnt22hsJpWD1K7iY9lbkLwl0ivn73pG2evsAn9G\n X8YKH52fnHsCrhSD\n -----END CERTIFICATE-----\n \"\"\".trimIndent(),\n )\n assertThat(cert"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":493,"symbol":"wildcardsCannotMatchIpAddresses","kind":"function","lang":"kotlin","code":"@Test fun wildcardsCannotMatchIpAddresses() {\n // openssl req -x509 -nodes -days 36500 -subj '/CN=*.0.0.1' -newkey rsa:512 -out cert.pem\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBkjCCATygAwIBAgIJAMdemqOwd/BEMA0GCSqGSIb3DQEBBQUAMBIxEDAOBgNV\n BAMUByouMC4wLjEwIBcNMTAxMjIwMTY0NDI1WhgPMjExMDExMjYxNjQ0MjVaMBIx\n EDAOBgNVBAMUByouMC4wLjEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAqY8c9Qrt\n YPWCvb7lclI+aDHM6fgbJcHsS9Zg8nUOh5dWrS7AgeA25wyaokFl4plBbbHQe2j+\n cCjsRiJIcQo9HwIDAQABo3MwcTAdBgNVHQ4EFgQUJ436TZPJvwCBKklZZqIvt1Yt\n JjEwQgYDVR0jBDswOYAUJ436TZPJvwCBKklZZqIvt1YtJjGhFqQUMBIxEDAOBgNV\n BAMUByouMC4wLjGCCQDHXpqjsHfwRDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEB\n BQUAA0EAk9i88xdjWoewqvE+iMC9tD2obMchgFDaHH0ogxxiRaIKeEly3g0uGxIt\n fl2WRY8hb4x+zRrwsFaLEpdEvqcjOQ==\n -----END CERTIFICATE-----\n \"\"\".trimIndent(),\n )\n assertThat(verifier.verify(\"127.0.0.1\", session)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":519,"symbol":"wildcardsDoesNotNeedTwoDots","kind":"function","lang":"kotlin","doc":"Earlier implementations of Android's hostname verifier required that wildcard names wouldn't match \"*.com\" or similar. This was a nonstandard check that we've since dropped. It is the CA's responsibility to not hand out certificates that match so broadly.","code":"@Test fun wildcardsDoesNotNeedTwoDots() {\n // openssl req -x509 -nodes -days 36500 -subj '/CN=*.com' -newkey rsa:512 -out cert.pem\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBjDCCATagAwIBAgIJAOVulXCSu6HuMA0GCSqGSIb3DQEBBQUAMBAxDjAMBgNV\n BAMUBSouY29tMCAXDTEwMTIyMDE2NDkzOFoYDzIxMTAxMTI2MTY0OTM4WjAQMQ4w\n DAYDVQQDFAUqLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDJd8xqni+h7Iaz\n ypItivs9kPuiJUqVz+SuJ1C05SFc3PmlRCvwSIfhyD67fHcbMdl+A/LrIjhhKZJe\n 1joO0+pFAgMBAAGjcTBvMB0GA1UdDgQWBBS4Iuzf5w8JdCp+EtBfdFNudf6+YzBA\n BgNVHSMEOTA3gBS4Iuzf5w8JdCp+EtBfdFNudf6+Y6EUpBIwEDEOMAwGA1UEAxQF\n Ki5jb22CCQDlbpVwkruh7jAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA0EA\n U6LFxmZr31lFyis2/T68PpjAppc0DpNQuA2m/Y7oTHBDi55Fw6HVHCw3lucuWZ5d\n qUYo4ES548JdpQtcLrW2sA==\n -----END CERTIFICATE-----\n \"\"\".trimIndent(),\n )\n assertThat(verifier.verify(\"google.com\", session)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":540,"symbol":"subjectAltName","kind":"function","lang":"kotlin","code":"@Test fun subjectAltName() {\n // $ cat ./cert.cnf\n // [req]\n // distinguished_name=distinguished_name\n // req_extensions=req_extensions\n // x509_extensions=x509_extensions\n // [distinguished_name]\n // [req_extensions]\n // [x509_extensions]\n // subjectAltName=DNS:bar.com,DNS:baz.com\n //\n // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \\\n // -newkey rsa:512 -out cert.pem\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBPTCB6KADAgECAgkA7zoHaaqNGHQwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE\n AxMHZm9vLmNvbTAgFw0xMDEyMjAxODM5MzZaGA8yMTEwMTEyNjE4MzkzNlowEjEQ\n MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC+gmoSxF+8\n hbV+rgRQqHIJd50216OWQJbU3BvdlPbca779NYO4+UZWTFdBM8BdQqs3H4B5Agvp\n y7HeSff1F7XRAgMBAAGjHzAdMBsGA1UdEQQUMBKCB2Jhci5jb22CB2Jhei5jb20w\n DQYJKoZIhvcNAQEFBQADQQBXpZZPOY2Dy1lGG81JTr8L4or9jpKacD7n51eS8iqI\n oTznPNuXHU5bFN0AAGX2ij47f/EahqTpo5RdS95P4sVm\n -----END CERTIFICATE-----\n \"\"\".trimIndent(),\n )\n assertThat(verifier.verify(\"foo.com\", session)).isFalse()\n assertThat(verifier.verify(\"bar.com\", session)).i"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":574,"symbol":"subjectAltNameWithWildcard","kind":"function","lang":"kotlin","code":"@Test fun subjectAltNameWithWildcard() {\n // $ cat ./cert.cnf\n // [req]\n // distinguished_name=distinguished_name\n // req_extensions=req_extensions\n // x509_extensions=x509_extensions\n // [distinguished_name]\n // [req_extensions]\n // [x509_extensions]\n // subjectAltName=DNS:bar.com,DNS:*.baz.com\n //\n // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \\\n // -newkey rsa:512 -out cert.pem\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBPzCB6qADAgECAgkAnv/7Jv5r7pMwDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE\n AxMHZm9vLmNvbTAgFw0xMDEyMjAxODQ2MDFaGA8yMTEwMTEyNjE4NDYwMVowEjEQ\n MA4GA1UEAxMHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDAz2YXnyog\n YdYLSFr/OEgSumtwqtZKJTB4wqTW/eKbBCEzxnyUMxWZIqUGu353PzwfOuWp2re3\n nvVV+QDYQlh9AgMBAAGjITAfMB0GA1UdEQQWMBSCB2Jhci5jb22CCSouYmF6LmNv\n bTANBgkqhkiG9w0BAQUFAANBAB8yrSl8zqy07i0SNYx2B/FnvQY734pxioaqFWfO\n Bqo1ZZl/9aPHEWIwBrxYNVB0SGu/kkbt/vxqOjzzrkXukmI=\n -----END CERTIFICATE-----\n \"\"\".trimIndent(),\n )\n assertThat(verifier.verify(\"foo.com\", session)).isFalse()\n assertThat(verifier.verify(\"bar"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":610,"symbol":"subjectAltNameWithIPAddresses","kind":"function","lang":"kotlin","code":"@Test fun subjectAltNameWithIPAddresses() {\n // $ cat ./cert.cnf\n // [req]\n // distinguished_name=distinguished_name\n // req_extensions=req_extensions\n // x509_extensions=x509_extensions\n // [distinguished_name]\n // [req_extensions]\n // [x509_extensions]\n // subjectAltName=IP:0:0:0:0:0:0:0:1,IP:2a03:2880:f003:c07:face:b00c::2,IP:0::5,IP:192.168.1.1\n //\n // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \\\n // -newkey rsa:512 -out cert.pem\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBaDCCARKgAwIBAgIJALxN+AOBVGwQMA0GCSqGSIb3DQEBCwUAMBIxEDAOBgNV\n BAMMB2Zvby5jb20wIBcNMjAwMzIyMTEwNDI4WhgPMjEyMDAyMjcxMTA0MjhaMBIx\n EDAOBgNVBAMMB2Zvby5jb20wXDANBgkqhkiG9w0BAQEFAANLADBIAkEAlnVbVfQ9\n 4aYjrPCcFuxOpjXuvyOc9Hcha4K7TfXyfsrjhAvCjCBIT/TiLOUVF3sx4yoCAtX8\n wmt404tTbKD6UwIDAQABo0kwRzBFBgNVHREEPjA8hxAAAAAAAAAAAAAAAAAAAAAB\n hxAqAyiA8AMMB/rOsAwAAAAChxAAAAAAAAAAAAAAAAAAAAAFhwTAqAEBMA0GCSqG\n SIb3DQEBCwUAA0EAPSOYHJh7hB4ElBqTCAFW+T5Y7mXsv9nQjBJ7w0YIw83V2PEI\n 3KbBIyGTrqHD6lG8QGZy+yNkIcRlodG8OfQRUg==\n -----END CERTIFICATE-----\n \"\"\"."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":652,"symbol":"generatedCertificate","kind":"function","lang":"kotlin","code":"@Test fun generatedCertificate() {\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"Foo Corp\")\n .addSubjectAlternativeName(\"foo.com\")\n .build()\n val session = session(heldCertificate.certificatePem())\n assertThat(verifier.verify(\"foo.com\", session)).isTrue()\n assertThat(verifier.verify(\"bar.com\", session)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":664,"symbol":"specialKInHostname","kind":"function","lang":"kotlin","code":"@Test fun specialKInHostname() {\n // https://github.com/apache/httpcomponents-client/commit/303e435d7949652ea77a6c50df1c548682476b6e\n // https://www.gosecure.net/blog/2020/10/27/weakness-in-java-tls-host-verification/\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"Foo Corp\")\n .addSubjectAlternativeName(\"k.com\")\n .addSubjectAlternativeName(\"tel.com\")\n .build()\n val session = session(heldCertificate.certificatePem())\n assertThat(verifier.verify(\"foo.com\", session)).isFalse()\n assertThat(verifier.verify(\"bar.com\", session)).isFalse()\n assertThat(verifier.verify(\"k.com\", session)).isTrue()\n assertThat(verifier.verify(\"K.com\", session)).isTrue()\n assertThat(verifier.verify(\"\\u2121.com\", session)).isFalse()\n assertThat(verifier.verify(\"℡.com\", session)).isFalse()\n\n // These should ideally be false, but we know that hostname is usually already checked by us\n assertThat(verifier.verify(\"\\u212A.com\", session)).isFalse()\n // Kelvin character below\n assertThat(verifier.verify(\"K.com\", session)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":688,"symbol":"specialKInCert","kind":"function","lang":"kotlin","code":"@Test fun specialKInCert() {\n // https://github.com/apache/httpcomponents-client/commit/303e435d7949652ea77a6c50df1c548682476b6e\n // https://www.gosecure.net/blog/2020/10/27/weakness-in-java-tls-host-verification/\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"Foo Corp\")\n .addSubjectAlternativeName(\"\\u2121.com\")\n .addSubjectAlternativeName(\"\\u212A.com\")\n .build()\n val session = session(heldCertificate.certificatePem())\n assertThat(verifier.verify(\"foo.com\", session)).isFalse()\n assertThat(verifier.verify(\"bar.com\", session)).isFalse()\n assertThat(verifier.verify(\"k.com\", session)).isFalse()\n assertThat(verifier.verify(\"K.com\", session)).isFalse()\n assertThat(verifier.verify(\"tel.com\", session)).isFalse()\n assertThat(verifier.verify(\"k.com\", session)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":707,"symbol":"specialKInExternalCert","kind":"function","lang":"kotlin","code":"@Test fun specialKInExternalCert() {\n // OpenJDK related test.\n platform.assumeNotConscrypt()\n\n // Expecting actual:\n // [\"℡.com\", \"K.com\"]\n // to contain exactly (and in same order):\n // [\"���.com\", \"���.com\"]\n platform.assumeNotBouncyCastle()\n\n // $ cat ./cert.cnf\n // [req]\n // distinguished_name=distinguished_name\n // req_extensions=req_extensions\n // x509_extensions=x509_extensions\n // [distinguished_name]\n // [req_extensions]\n // [x509_extensions]\n // subjectAltName=DNS:℡.com,DNS:K.com\n //\n // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \\\n // -newkey rsa:512 -out cert.pem\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBSDCB86ADAgECAhRLR4TGgXBegg0np90FZ1KPeWpDtjANBgkqhkiG9w0BAQsF\n ADASMRAwDgYDVQQDDAdmb28uY29tMCAXDTIwMTAyOTA2NTkwNVoYDzIxMjAxMDA1\n MDY1OTA1WjASMRAwDgYDVQQDDAdmb28uY29tMFwwDQYJKoZIhvcNAQEBBQADSwAw\n SAJBALQcTVW9aW++ClIV9/9iSzijsPvQGEu/FQOjIycSrSIheZyZmR8bluSNBq0C\n 9fpalRKZb0S2tlCTi5WoX8d3K30CAwEAAaMfMB0wGwYDVR0RBBQwEoIH4oShLmNv\n bYIH4oSqLmNvbTANBgkqhkiG9w0BAQsFAANBAA1+/eDvSUGv78iEjNW+1w3OP"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":757,"symbol":"certificateSANs","kind":"function","lang":"kotlin","code":"private fun certificateSANs(peerCertificate: X509Certificate): List =\n when (val subjectAlternativeNames = peerCertificate.subjectAlternativeNames) {\n null -> listOf()\n else -> subjectAlternativeNames.map { c: List<*> -> c[1] as String }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":763,"symbol":"replacementCharacter","kind":"function","lang":"kotlin","code":"@Test fun replacementCharacter() {\n // $ cat ./cert.cnf\n // [req]\n // distinguished_name=distinguished_name\n // req_extensions=req_extensions\n // x509_extensions=x509_extensions\n // [distinguished_name]\n // [req_extensions]\n // [x509_extensions]\n // subjectAltName=DNS:℡.com,DNS:K.com\n //\n // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \\\n // -newkey rsa:512 -out cert.pem\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBSDCB86ADAgECAhRLR4TGgXBegg0np90FZ1KPeWpDtjANBgkqhkiG9w0BAQsF\n ADASMRAwDgYDVQQDDAdmb28uY29tMCAXDTIwMTAyOTA2NTkwNVoYDzIxMjAxMDA1\n MDY1OTA1WjASMRAwDgYDVQQDDAdmb28uY29tMFwwDQYJKoZIhvcNAQEBBQADSwAw\n SAJBALQcTVW9aW++ClIV9/9iSzijsPvQGEu/FQOjIycSrSIheZyZmR8bluSNBq0C\n 9fpalRKZb0S2tlCTi5WoX8d3K30CAwEAAaMfMB0wGwYDVR0RBBQwEoIH4oShLmNv\n bYIH4oSqLmNvbTANBgkqhkiG9w0BAQsFAANBAA1+/eDvSUGv78iEjNW+1w3OPAwt\n Ij1qLQ/YI8OogZPMk7YY46/ydWWp7UpD47zy/vKmm4pOc8Glc8MoDD6UADs=\n -----END CERTIFICATE-----\n \"\"\".trimIndent(),\n )\n\n // Replacement characters are deliberate, from certificate loading.\n assertThat(verifier."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":796,"symbol":"malformedIpAddressAndMalformedSubjectAltName","kind":"function","lang":"kotlin","code":"@Test fun malformedIpAddressAndMalformedSubjectAltName() {\n // $ cat ./cert.cnf\n // [req]\n // distinguished_name=distinguished_name\n // x509_extensions=x509_extensions\n // [distinguished_name]\n // [x509_extensions]\n // # An iPAddress holding an address and a netmask. Java reads it back as\n // # '1.2.3.4/255.255.255.0', which is not a host name.\n // subjectAltName=DER:30:0a:87:08:01:02:03:04:ff:ff:ff:00\n //\n // $ openssl req -x509 -nodes -days 36500 -subj '/CN=foo.com' -config ./cert.cnf \\\n // -newkey rsa:2048 -out cert.pem\n val session =\n session(\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIC6jCCAdKgAwIBAgIUOs0TfFZ8c478WBRA5JhYDmCY27kwDQYJKoZIhvcNAQEL\n BQAwEjEQMA4GA1UEAwwHZm9vLmNvbTAgFw0yNjA3MjkxNzQzMzZaGA8yMTI2MDcw\n NTE3NDMzNlowEjEQMA4GA1UEAwwHZm9vLmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD\n ggEPADCCAQoCggEBAKRuEQYMeSBJkGt4Xah86p1TthHyTrQDqp2n2UMUFAbx6zSq\n LXJ/VMRMevKectFkgu2i+blMDvQcgiy3Mu1CNvGdJtWqCiUThZgvZVxAfliU5YNi\n K7X7V9EK+FqF1SB2mpzxhY2+a+tPBFTUxMFqOHl8JMZ1ZVTtmbRn+N1l9DojjqM5\n R0DZcxC/p5Fu6+EmFRc5ORK7J2s1NBYsEm5Arr64Vy/h9XUiz38uX+umQb8tUWtf\n KjneRhiGWehqzpOpKzsk8KQ7TDFbT3+"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":838,"symbol":"thatCatchesErrorsWithBadSession","kind":"function","lang":"kotlin","code":"@Test fun thatCatchesErrorsWithBadSession() {\n val localVerifier = OkHttpClient().hostnameVerifier\n\n // Since this is public API, okhttp3.internal.tls.OkHostnameVerifier.verify is also\n assertThat(verifier).isInstanceOf()\n val handshakeCertificates = platform.localhostHandshakeCertificates()\n val session = handshakeCertificates.sslContext().createSSLEngine().session\n assertThat(localVerifier.verify(\"\\uD83D\\uDCA9.com\", session)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":848,"symbol":"verifyAsIpAddress","kind":"function","lang":"kotlin","code":"@Test fun verifyAsIpAddress() {\n // IPv4\n assertThat(\"127.0.0.1\".canParseAsIpAddress()).isTrue()\n assertThat(\"1.2.3.4\".canParseAsIpAddress()).isTrue()\n\n // IPv6\n assertThat(\"::1\".canParseAsIpAddress()).isTrue()\n assertThat(\"2001:db8::1\".canParseAsIpAddress()).isTrue()\n assertThat(\"::192.168.0.1\".canParseAsIpAddress()).isTrue()\n assertThat(\"::ffff:192.168.0.1\".canParseAsIpAddress()).isTrue()\n assertThat(\"FEDC:BA98:7654:3210:FEDC:BA98:7654:3210\".canParseAsIpAddress()).isTrue()\n assertThat(\"1080:0:0:0:8:800:200C:417A\".canParseAsIpAddress()).isTrue()\n assertThat(\"1080::8:800:200C:417A\".canParseAsIpAddress()).isTrue()\n assertThat(\"FF01::101\".canParseAsIpAddress()).isTrue()\n assertThat(\"0:0:0:0:0:0:13.1.68.3\".canParseAsIpAddress()).isTrue()\n assertThat(\"0:0:0:0:0:FFFF:129.144.52.38\".canParseAsIpAddress()).isTrue()\n assertThat(\"::13.1.68.3\".canParseAsIpAddress()).isTrue()\n assertThat(\"::FFFF:129.144.52.38\".canParseAsIpAddress()).isTrue()\n\n // Hostnames\n assertThat(\"go\".canParseAsIpAddress()).isFalse()\n assertThat(\"localhost\".canParseAsIpAddress()).isFalse()\n assertThat(\"squareup.com\".canParseAsIpAddress()).isFalse()\n assertTha"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":874,"symbol":"certificate","kind":"function","lang":"kotlin","code":"private fun certificate(certificate: String): X509Certificate =\n CertificateFactory\n .getInstance(\"X.509\")\n .generateCertificate(ByteArrayInputStream(certificate.toByteArray()))\n as X509Certificate"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/tls/HostnameVerifierTest.kt","line":880,"symbol":"session","kind":"function","lang":"kotlin","code":"private fun session(certificate: String): SSLSession = FakeSSLSession(certificate(certificate))"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":33,"symbol":"MessageDeflaterInflaterTest","kind":"class","lang":"kotlin","code":"internal class MessageDeflaterInflaterTest {\n @Test fun `inflate golden value`() {\n val inflater = MessageInflater(false)\n val message = \"f248cdc9c957c8cc4bcb492cc9cccf530400\".decodeHex()\n assertThat(inflater.inflate(message)).isEqualTo(\"Hello inflation!\".encodeUtf8())\n }\n\n /**\n * We had a bug where self-finishing inflater streams would infinite loop!\n * https://github.com/lysine-dev/okhttp/issues/8078\n */\n @Test fun `inflate returns finished before bytesRead reaches input length`() {\n val inflater = MessageInflater(false)\n val message = \"53621260020000\".decodeHex()\n assertThat(inflater.inflate(message)).isEqualTo(\"22021002\".decodeHex())\n }\n\n @Test fun `deflate golden value`() {\n val deflater = MessageDeflater(false)\n val deflated = deflater.deflate(\"Hello deflate!\".encodeUtf8())\n assertThat(deflated.hex()).isEqualTo(\"f248cdc9c95748494dcb492c49550400\")\n }\n\n @Test fun `inflate deflate`() {\n val deflater = MessageDeflater(false)\n val inflater = MessageInflater(false)\n\n val goldenValue = \"Hello deflate!\".repeat(100).encodeUtf8()\n\n val deflated = deflater.deflate(goldenValue)\n assertThat(deflated.size).isLessThan(goldenValue.size)"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":34,"symbol":"`inflate golden value`","kind":"function","lang":"kotlin","code":"@Test fun `inflate golden value`() {\n val inflater = MessageInflater(false)\n val message = \"f248cdc9c957c8cc4bcb492cc9cccf530400\".decodeHex()\n assertThat(inflater.inflate(message)).isEqualTo(\"Hello inflation!\".encodeUtf8())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":44,"symbol":"`inflate returns finished before bytesRead reaches input length`","kind":"function","lang":"kotlin","doc":"We had a bug where self-finishing inflater streams would infinite loop! https://github.com/lysine-dev/okhttp/issues/8078","code":"@Test fun `inflate returns finished before bytesRead reaches input length`() {\n val inflater = MessageInflater(false)\n val message = \"53621260020000\".decodeHex()\n assertThat(inflater.inflate(message)).isEqualTo(\"22021002\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":50,"symbol":"`deflate golden value`","kind":"function","lang":"kotlin","code":"@Test fun `deflate golden value`() {\n val deflater = MessageDeflater(false)\n val deflated = deflater.deflate(\"Hello deflate!\".encodeUtf8())\n assertThat(deflated.hex()).isEqualTo(\"f248cdc9c95748494dcb492c49550400\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":56,"symbol":"`inflate deflate`","kind":"function","lang":"kotlin","code":"@Test fun `inflate deflate`() {\n val deflater = MessageDeflater(false)\n val inflater = MessageInflater(false)\n\n val goldenValue = \"Hello deflate!\".repeat(100).encodeUtf8()\n\n val deflated = deflater.deflate(goldenValue)\n assertThat(deflated.size).isLessThan(goldenValue.size)\n val inflated = inflater.inflate(deflated)\n\n assertThat(inflated).isEqualTo(goldenValue)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":69,"symbol":"`inflate deflate empty message`","kind":"function","lang":"kotlin","code":"@Test fun `inflate deflate empty message`() {\n val deflater = MessageDeflater(false)\n val inflater = MessageInflater(false)\n\n val goldenValue = \"\".encodeUtf8()\n\n val deflated = deflater.deflate(goldenValue)\n assertThat(deflated).isEqualTo(\"00\".decodeHex())\n val inflated = inflater.inflate(deflated)\n\n assertThat(inflated).isEqualTo(goldenValue)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":82,"symbol":"`inflate deflate with context takeover`","kind":"function","lang":"kotlin","code":"@Test fun `inflate deflate with context takeover`() {\n val deflater = MessageDeflater(false)\n val inflater = MessageInflater(false)\n\n val goldenValue1 = \"Hello deflate!\".repeat(100).encodeUtf8()\n val deflatedValue1 = deflater.deflate(goldenValue1)\n assertThat(inflater.inflate(deflatedValue1)).isEqualTo(goldenValue1)\n\n val goldenValue2 = \"Hello deflate?\".repeat(100).encodeUtf8()\n val deflatedValue2 = deflater.deflate(goldenValue2)\n assertThat(inflater.inflate(deflatedValue2)).isEqualTo(goldenValue2)\n\n assertThat(deflatedValue2.size).isLessThan(deflatedValue1.size)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":97,"symbol":"`inflate deflate with no context takeover`","kind":"function","lang":"kotlin","code":"@Test fun `inflate deflate with no context takeover`() {\n val deflater = MessageDeflater(true)\n val inflater = MessageInflater(true)\n\n val goldenValue1 = \"Hello deflate!\".repeat(100).encodeUtf8()\n val deflatedValue1 = deflater.deflate(goldenValue1)\n assertThat(inflater.inflate(deflatedValue1)).isEqualTo(goldenValue1)\n\n val goldenValue2 = \"Hello deflate!\".repeat(100).encodeUtf8()\n val deflatedValue2 = deflater.deflate(goldenValue2)\n assertThat(inflater.inflate(deflatedValue2)).isEqualTo(goldenValue2)\n\n assertThat(deflatedValue2).isEqualTo(deflatedValue1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":112,"symbol":"`deflate after close`","kind":"function","lang":"kotlin","code":"@Test fun `deflate after close`() {\n val deflater = MessageDeflater(true)\n deflater.close()\n\n assertFailsWith {\n deflater.deflate(\"Hello deflate!\".encodeUtf8())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":121,"symbol":"`inflate after close`","kind":"function","lang":"kotlin","code":"@Test fun `inflate after close`() {\n val inflater = MessageInflater(false)\n\n inflater.close()\n\n assertFailsWith {\n inflater.inflate(\"f240e30300\".decodeHex())\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":135,"symbol":"`inflate golden value in buffer that has been fragmented`","kind":"function","lang":"kotlin","doc":"Test for an [EOFException] caused by mishandling of fragmented buffers in web socket compression. https://github.com/lysine-dev/okhttp/issues/5965","code":"@Test fun `inflate golden value in buffer that has been fragmented`() {\n val inflater = MessageInflater(false)\n val buffer = fragmentBuffer(Buffer().write(\"f248cdc9c957c8cc4bcb492cc9cccf530400\".decodeHex()))\n inflater.inflate(buffer)\n assertThat(buffer.readUtf8()).isEqualTo(\"Hello inflation!\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":152,"symbol":"`deflated data has too many bytes`","kind":"function","lang":"kotlin","doc":"In practice this could happen if the encoder doesn't strip the [0x00, 0x00, 0xff, 0xff] suffix and that ends up repeated. https://github.com/lysine-dev/okhttp/issues/8551","code":"@Test\n fun `deflated data has too many bytes`() {\n val inflater = MessageInflater(true)\n val buffer = Buffer()\n\n val message1 = \"hello\".encodeUtf8()\n val message2 = \"hello 2\".encodeUtf8()\n\n DeflaterSink(buffer, Deflater(Deflater.DEFAULT_COMPRESSION, true)).use { sink ->\n sink.write(Buffer().write(message1), message1.size.toLong())\n }\n buffer.writeByte(0x00)\n // Trailing data. We use the Okio segment size to make sure it's still in the input buffer.\n buffer.write(ByteArray(8192))\n inflater.inflate(buffer)\n assertThat(buffer.readByteString()).isEqualTo(message1)\n\n DeflaterSink(buffer, Deflater(Deflater.DEFAULT_COMPRESSION, true)).use { sink ->\n sink.write(Buffer().write(message2), message2.size.toLong())\n }\n buffer.writeByte(0x00)\n inflater.inflate(buffer)\n assertThat(buffer.readByteString()).isEqualTo(message2)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":177,"symbol":"deflate","kind":"function","lang":"kotlin","code":"private fun MessageDeflater.deflate(byteString: ByteString): ByteString {\n val buffer = Buffer()\n buffer.write(byteString)\n deflate(buffer)\n return buffer.readByteString()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt","line":184,"symbol":"inflate","kind":"function","lang":"kotlin","code":"private fun MessageInflater.inflate(byteString: ByteString): ByteString {\n val buffer = Buffer()\n buffer.write(byteString)\n inflate(buffer)\n return buffer.readByteString()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":54,"symbol":"RealWebSocketTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slow\")\nclass RealWebSocketTest {\n // NOTE: Fields are named 'client' and 'server' for cognitive simplicity. This differentiation has\n // zero effect on the behavior of the WebSocket API which is why tests are only written once\n // from the perspective of a single peer.\n private val random = Random(0)\n private val taskFaker = TaskFaker()\n private val sockets = inMemorySocketPair(8192L)\n private val client = TestStreams(taskFaker, sockets[0], client = true)\n private val server = TestStreams(taskFaker, sockets[1], client = false)\n\n @BeforeEach\n fun setUp() {\n client.initWebSocket(random)\n server.initWebSocket(random)\n }\n\n @AfterEach\n @Throws(Exception::class)\n fun tearDown() {\n client.listener.assertExhausted()\n server.listener.assertExhausted()\n server.source.close()\n client.source.close()\n taskFaker.runTasks()\n server.webSocket!!.tearDown()\n client.webSocket!!.tearDown()\n taskFaker.close()\n }\n\n @Test\n fun close() {\n client.webSocket!!.close(1000, \"Hello!\")\n // This will trigger a close response.\n assertThat(server.processNextFrame()).isFalse()\n server.listener.assertClosing(1000, \"Hello!\")\n server.webSocket!!.finish"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":65,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n client.initWebSocket(random)\n server.initWebSocket(random)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":71,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n @Throws(Exception::class)\n fun tearDown() {\n client.listener.assertExhausted()\n server.listener.assertExhausted()\n server.source.close()\n client.source.close()\n taskFaker.runTasks()\n server.webSocket!!.tearDown()\n client.webSocket!!.tearDown()\n taskFaker.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":84,"symbol":"close","kind":"function","lang":"kotlin","code":"@Test\n fun close() {\n client.webSocket!!.close(1000, \"Hello!\")\n // This will trigger a close response.\n assertThat(server.processNextFrame()).isFalse()\n server.listener.assertClosing(1000, \"Hello!\")\n server.webSocket!!.finishReader()\n server.webSocket!!.close(1000, \"Goodbye!\")\n assertThat(client.processNextFrame()).isFalse()\n client.listener.assertClosing(1000, \"Goodbye!\")\n client.webSocket!!.finishReader()\n server.listener.assertClosed(1000, \"Hello!\")\n client.listener.assertClosed(1000, \"Goodbye!\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":99,"symbol":"clientCloseThenMethodsReturnFalse","kind":"function","lang":"kotlin","code":"@Test\n fun clientCloseThenMethodsReturnFalse() {\n client.webSocket!!.close(1000, \"Hello!\")\n assertThat(client.webSocket!!.close(1000, \"Hello!\")).isFalse()\n assertThat(client.webSocket!!.send(\"Hello!\")).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":106,"symbol":"clientCloseWith0Fails","kind":"function","lang":"kotlin","code":"@Test\n fun clientCloseWith0Fails() {\n assertFailsWith {\n client.webSocket!!.close(0, null)\n }.also { expected ->\n assertThat(\"Code must be in range [1000,5000): 0\")\n .isEqualTo(expected.message)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":116,"symbol":"afterSocketClosedPingFailsWebSocket","kind":"function","lang":"kotlin","code":"@Test\n fun afterSocketClosedPingFailsWebSocket() {\n server.source.close()\n client.webSocket!!.pong(\"Ping!\".encodeUtf8())\n taskFaker.runTasks()\n client.listener.assertFailure(IOException::class.java, \"source is closed\")\n assertThat(client.webSocket!!.send(\"Hello!\")).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":125,"symbol":"socketClosedDuringMessageKillsWebSocket","kind":"function","lang":"kotlin","code":"@Test\n fun socketClosedDuringMessageKillsWebSocket() {\n server.source.close()\n assertThat(client.webSocket!!.send(\"Hello!\")).isTrue()\n taskFaker.runTasks()\n client.listener.assertFailure(IOException::class.java, \"source is closed\")\n\n // A failed write prevents further use of the WebSocket instance.\n assertThat(client.webSocket!!.send(\"Hello!\")).isFalse()\n assertThat(client.webSocket!!.pong(\"Ping!\".encodeUtf8())).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":137,"symbol":"serverCloseThenWritingPingSucceeds","kind":"function","lang":"kotlin","code":"@Test\n fun serverCloseThenWritingPingSucceeds() {\n server.webSocket!!.close(1000, \"Hello!\")\n client.processNextFrame()\n client.listener.assertClosing(1000, \"Hello!\")\n assertThat(client.webSocket!!.pong(\"Pong?\".encodeUtf8())).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":145,"symbol":"clientCanWriteMessagesAfterServerClose","kind":"function","lang":"kotlin","code":"@Test\n fun clientCanWriteMessagesAfterServerClose() {\n server.webSocket!!.close(1000, \"Hello!\")\n client.processNextFrame()\n client.listener.assertClosing(1000, \"Hello!\")\n assertThat(client.webSocket!!.send(\"Hi!\")).isTrue()\n server.processNextFrame()\n server.listener.assertTextMessage(\"Hi!\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":155,"symbol":"serverCloseThenClientClose","kind":"function","lang":"kotlin","code":"@Test\n fun serverCloseThenClientClose() {\n server.webSocket!!.close(1000, \"Hello!\")\n client.processNextFrame()\n client.listener.assertClosing(1000, \"Hello!\")\n assertThat(client.webSocket!!.close(1000, \"Bye!\")).isTrue()\n client.webSocket!!.finishReader()\n taskFaker.runTasks()\n client.listener.assertClosed(1000, \"Hello!\")\n server.processNextFrame()\n server.listener.assertClosing(1000, \"Bye!\")\n server.webSocket!!.finishReader()\n server.listener.assertClosed(1000, \"Bye!\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":170,"symbol":"emptyCloseInitiatesShutdown","kind":"function","lang":"kotlin","code":"@Test\n fun emptyCloseInitiatesShutdown() {\n server.sink.write(\"8800\".decodeHex()).emit() // Close without code.\n client.processNextFrame()\n client.listener.assertClosing(1005, \"\")\n client.webSocket!!.finishReader()\n assertThat(client.webSocket!!.close(1000, \"Bye!\")).isTrue()\n server.processNextFrame()\n server.listener.assertClosing(1000, \"Bye!\")\n server.webSocket!!.finishReader()\n client.listener.assertClosed(1005, \"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":183,"symbol":"clientCloseClosesConnection","kind":"function","lang":"kotlin","code":"@Test\n fun clientCloseClosesConnection() {\n client.webSocket!!.close(1000, \"Hello!\")\n taskFaker.runTasks()\n assertThat(client.closed).isFalse()\n server.processNextFrame() // Read client closing, send server close.\n server.listener.assertClosing(1000, \"Hello!\")\n server.webSocket!!.finishReader()\n server.webSocket!!.close(1000, \"Goodbye!\")\n client.processNextFrame() // Read server closing, close connection.\n taskFaker.runTasks()\n client.listener.assertClosing(1000, \"Goodbye!\")\n client.webSocket!!.finishReader()\n taskFaker.runTasks()\n assertThat(client.closed).isTrue()\n\n // Server and client both finished closing, connection is closed.\n server.listener.assertClosed(1000, \"Hello!\")\n client.listener.assertClosed(1000, \"Goodbye!\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":204,"symbol":"clientCloseCancelsConnectionAfterTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun clientCloseCancelsConnectionAfterTimeout() {\n client.webSocket!!.close(1000, \"Hello!\")\n taskFaker.runTasks()\n // Note: we don't process server frames so our client 'close' doesn't receive a server 'close'.\n assertThat(client.canceled).isFalse()\n\n taskFaker.advanceUntil(ns(RealWebSocket.CANCEL_AFTER_CLOSE_MILLIS - 1))\n assertThat(client.canceled).isFalse()\n\n taskFaker.advanceUntil(ns(RealWebSocket.CANCEL_AFTER_CLOSE_MILLIS))\n assertThat(client.canceled).isTrue()\n\n client.processNextFrame() // This won't get a frame, but it will get a closed pipe.\n client.listener.assertFailure(IOException::class.java, \"canceled\")\n taskFaker.runTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":222,"symbol":"clientCloseCancelsConnectionAfterCustomTimeout","kind":"function","lang":"kotlin","code":"@Test\n fun clientCloseCancelsConnectionAfterCustomTimeout() {\n client.initWebSocket(random, webSocketCloseTimeout = 5_000)\n client.webSocket!!.close(1000, \"Hello!\")\n taskFaker.runTasks()\n // Note: we don't process server frames so our client 'close' doesn't receive a server 'close'.\n assertThat(client.canceled).isFalse()\n\n taskFaker.advanceUntil(ns(4_999))\n assertThat(client.canceled).isFalse()\n\n taskFaker.advanceUntil(ns(5_000))\n assertThat(client.canceled).isTrue()\n\n client.processNextFrame() // This won't get a frame, but it will get a closed pipe.\n client.listener.assertFailure(IOException::class.java, \"canceled\")\n taskFaker.runTasks()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":241,"symbol":"serverCloseClosesConnection","kind":"function","lang":"kotlin","code":"@Test\n fun serverCloseClosesConnection() {\n server.webSocket!!.close(1000, \"Hello!\")\n client.processNextFrame() // Read server close, send client close, close connection.\n assertThat(client.closed).isFalse()\n client.listener.assertClosing(1000, \"Hello!\")\n client.webSocket!!.finishReader()\n client.webSocket!!.close(1000, \"Hello!\")\n server.processNextFrame()\n server.listener.assertClosing(1000, \"Hello!\")\n server.webSocket!!.finishReader()\n client.listener.assertClosed(1000, \"Hello!\")\n server.listener.assertClosed(1000, \"Hello!\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":256,"symbol":"clientAndServerCloseClosesConnection","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun clientAndServerCloseClosesConnection() {\n // Send close from both sides at the same time.\n server.webSocket!!.close(1000, \"Hello!\")\n client.processNextFrame() // Read close, close connection close.\n assertThat(client.closed).isFalse()\n client.webSocket!!.close(1000, \"Hi!\")\n server.processNextFrame()\n client.listener.assertClosing(1000, \"Hello!\")\n server.listener.assertClosing(1000, \"Hi!\")\n client.webSocket!!.finishReader()\n server.webSocket!!.finishReader()\n client.listener.assertClosed(1000, \"Hello!\")\n server.listener.assertClosed(1000, \"Hi!\")\n taskFaker.runTasks()\n assertThat(client.closed).isTrue()\n server.listener.assertExhausted() // Client should not have sent second close.\n client.listener.assertExhausted() // Server should not have sent second close.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":277,"symbol":"serverCloseBreaksReadMessageLoop","kind":"function","lang":"kotlin","code":"@Test\n fun serverCloseBreaksReadMessageLoop() {\n server.webSocket!!.send(\"Hello!\")\n server.webSocket!!.close(1000, \"Bye!\")\n assertThat(client.processNextFrame()).isTrue()\n client.listener.assertTextMessage(\"Hello!\")\n assertThat(client.processNextFrame()).isFalse()\n client.listener.assertClosing(1000, \"Bye!\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":287,"symbol":"protocolErrorBeforeCloseSendsFailure","kind":"function","lang":"kotlin","code":"@Test\n fun protocolErrorBeforeCloseSendsFailure() {\n server.sink.write(\"0a00\".decodeHex()).emit() // Invalid non-final ping frame.\n client.processNextFrame() // Detects error, send close, close connection.\n taskFaker.runTasks()\n client.webSocket!!.finishReader()\n assertThat(client.closed).isTrue()\n client.listener.assertFailure(\n ProtocolException::class.java,\n \"Control frames must be final.\",\n )\n server.processNextFrame()\n taskFaker.runTasks()\n server.listener.assertFailure()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":303,"symbol":"protocolErrorInCloseResponseClosesConnection","kind":"function","lang":"kotlin","code":"@Test\n fun protocolErrorInCloseResponseClosesConnection() {\n client.webSocket!!.close(1000, \"Hello\")\n server.processNextFrame()\n // Not closed until close reply is received.\n assertThat(client.closed).isFalse()\n\n // Manually write an invalid masked close frame.\n server.sink.write(\"888760b420bb635c68de0cd84f\".decodeHex()).emit()\n client.processNextFrame() // Detects error, disconnects immediately since close already sent.\n client.webSocket!!.finishReader()\n taskFaker.runTasks()\n assertThat(client.closed).isTrue()\n client.listener.assertFailure(\n ProtocolException::class.java,\n \"Server-sent frames must not be masked.\",\n )\n server.listener.assertClosing(1000, \"Hello\")\n server.listener.assertExhausted() // Client should not have sent second close.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":324,"symbol":"protocolErrorAfterCloseDoesNotSendClose","kind":"function","lang":"kotlin","code":"@Test\n fun protocolErrorAfterCloseDoesNotSendClose() {\n client.webSocket!!.close(1000, \"Hello!\")\n server.processNextFrame()\n\n // Not closed until close reply is received.\n assertThat(client.closed).isFalse()\n server.sink.write(\"0a00\".decodeHex()).emit() // Invalid non-final ping frame.\n client.processNextFrame() // Detects error, disconnects immediately since close already sent.\n client.webSocket!!.finishReader()\n taskFaker.runTasks()\n assertThat(client.closed).isTrue()\n client.listener.assertFailure(\n ProtocolException::class.java,\n \"Control frames must be final.\",\n )\n server.listener.assertClosing(1000, \"Hello!\")\n server.listener.assertExhausted() // Client should not have sent second close.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":344,"symbol":"networkErrorReportedAsFailure","kind":"function","lang":"kotlin","code":"@Test\n fun networkErrorReportedAsFailure() {\n server.sink.close()\n client.processNextFrame()\n taskFaker.runTasks()\n client.listener.assertFailure(EOFException::class.java)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":352,"symbol":"closeThrowingFailsConnection","kind":"function","lang":"kotlin","code":"@Test\n fun closeThrowingFailsConnection() {\n server.source.close()\n client.webSocket!!.close(1000, null)\n taskFaker.runTasks()\n client.listener.assertFailure(IOException::class.java, \"source is closed\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":360,"symbol":"closeMessageAndConnectionCloseThrowingDoesNotMaskOriginal","kind":"function","lang":"kotlin","code":"@Test\n fun closeMessageAndConnectionCloseThrowingDoesNotMaskOriginal() {\n // So when the client sends close it throws an IOException.\n server.source.close()\n client.webSocket!!.close(1000, \"Bye!\")\n taskFaker.runTasks()\n client.webSocket!!.finishReader()\n client.listener.assertFailure(IOException::class.java, \"source is closed\")\n assertThat(client.closed).isTrue()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":371,"symbol":"pingOnInterval","kind":"function","lang":"kotlin","code":"@Test\n fun pingOnInterval() {\n client.initWebSocket(random, pingIntervalMillis = 500)\n taskFaker.advanceUntil(ns(500L))\n server.processNextFrame() // Ping.\n client.processNextFrame() // Pong.\n taskFaker.advanceUntil(ns(1000L))\n server.processNextFrame() // Ping.\n client.processNextFrame() // Pong.\n taskFaker.advanceUntil(ns(1500L))\n server.processNextFrame() // Ping.\n client.processNextFrame() // Pong.\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":385,"symbol":"unacknowledgedPingFailsConnection","kind":"function","lang":"kotlin","code":"@Test\n fun unacknowledgedPingFailsConnection() {\n client.initWebSocket(random, pingIntervalMillis = 500)\n\n // Don't process the ping and pong frames!\n taskFaker.advanceUntil(ns(500L))\n taskFaker.advanceUntil(ns(1000L))\n client.listener.assertFailure(\n SocketTimeoutException::class.java,\n \"sent ping but didn't receive pong within 500ms (after 0 successful ping/pongs)\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":398,"symbol":"unexpectedPongsDoNotInterfereWithFailureDetection","kind":"function","lang":"kotlin","code":"@Test\n fun unexpectedPongsDoNotInterfereWithFailureDetection() {\n client.initWebSocket(random, pingIntervalMillis = 500)\n\n // At 0ms the server sends 3 unexpected pongs. The client accepts 'em and ignores em.\n server.webSocket!!.pong(\"pong 1\".encodeUtf8())\n client.processNextFrame()\n server.webSocket!!.pong(\"pong 2\".encodeUtf8())\n client.processNextFrame()\n taskFaker.runTasks()\n server.webSocket!!.pong(\"pong 3\".encodeUtf8())\n client.processNextFrame()\n\n // After 500ms the client automatically pings and the server pongs back.\n taskFaker.advanceUntil(ns(500L))\n server.processNextFrame() // Ping.\n client.processNextFrame() // Pong.\n\n // After 1000ms the client will attempt a ping 2, but we don't process it. That'll cause the\n // client to fail at 1500ms when it's time to send ping 3 because pong 2 hasn't been received.\n taskFaker.advanceUntil(ns(1000L))\n taskFaker.advanceUntil(ns(1500L))\n client.listener.assertFailure(\n SocketTimeoutException::class.java,\n \"sent ping but didn't receive pong within 500ms (after 1 successful ping/pongs)\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":426,"symbol":"messagesNotCompressedWhenNotConfigured","kind":"function","lang":"kotlin","code":"@Test\n fun messagesNotCompressedWhenNotConfigured() {\n val message = repeat('a', RealWebSocket.DEFAULT_MINIMUM_DEFLATE_SIZE.toInt())\n server.webSocket!!.send(message)\n taskFaker.runTasks()\n assertThat(client.clientSourceBufferSize())\n .isGreaterThan(message.length.toLong()) // Not compressed.\n assertThat(client.processNextFrame()).isTrue()\n client.listener.assertTextMessage(message)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":437,"symbol":"messagesCompressedWhenConfigured","kind":"function","lang":"kotlin","code":"@Test\n fun messagesCompressedWhenConfigured() {\n val headers = headersOf(\"Sec-WebSocket-Extensions\", \"permessage-deflate\")\n client.initWebSocket(random, responseHeaders = headers)\n server.initWebSocket(random, responseHeaders = headers)\n val message = repeat('a', RealWebSocket.DEFAULT_MINIMUM_DEFLATE_SIZE.toInt())\n server.webSocket!!.send(message)\n taskFaker.runTasks()\n assertThat(client.clientSourceBufferSize())\n .isLessThan(message.length.toLong()) // Compressed!\n assertThat(client.processNextFrame()).isTrue()\n client.listener.assertTextMessage(message)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":451,"symbol":"smallMessagesNotCompressed","kind":"function","lang":"kotlin","code":"@Test\n fun smallMessagesNotCompressed() {\n val headers = headersOf(\"Sec-WebSocket-Extensions\", \"permessage-deflate\")\n client.initWebSocket(random, responseHeaders = headers)\n server.initWebSocket(random, responseHeaders = headers)\n val message = repeat('a', RealWebSocket.DEFAULT_MINIMUM_DEFLATE_SIZE.toInt() - 1)\n server.webSocket!!.send(message)\n taskFaker.runTasks()\n assertThat(client.clientSourceBufferSize())\n .isGreaterThan(message.length.toLong()) // Not compressed.\n assertThat(client.processNextFrame()).isTrue()\n client.listener.assertTextMessage(message)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":466,"symbol":"TestStreams","kind":"class","lang":"kotlin","doc":"One peer's streams, listener, and web socket in the test.","code":"private class TestStreams(\n private val taskFaker: TaskFaker,\n private val delegate: Socket,\n private val client: Boolean,\n ) : BufferedSocket {\n private val name = if (client) \"client\" else \"server\"\n val listener = WebSocketRecorder(name)\n var webSocket: RealWebSocket? = null\n var sourceClosed = false\n var sinkClosed = false\n val closed: Boolean\n get() = sourceClosed && sinkClosed\n var canceled = false\n\n override val source: BufferedSource =\n object : ForwardingSource(delegate.source) {\n override fun close() {\n sourceClosed = true\n super.close()\n }\n }.buffer()\n\n override val sink: BufferedSink =\n object : ForwardingSink(delegate.sink) {\n override fun close() {\n sinkClosed = true\n super.close()\n }\n }.buffer()\n\n fun initWebSocket(\n random: Random?,\n pingIntervalMillis: Int = 0,\n responseHeaders: Headers? = headersOf(),\n webSocketCloseTimeout: Long = RealWebSocket.CANCEL_AFTER_CLOSE_MILLIS,\n ) {\n val url = \"http://example.com/websocket\"\n val response =\n Response\n .Builder()\n .code(101)\n .mes"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":482,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n sourceClosed = true\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":490,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n sinkClosed = true\n super.close()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":496,"symbol":"initWebSocket","kind":"function","lang":"kotlin","code":"fun initWebSocket(\n random: Random?,\n pingIntervalMillis: Int = 0,\n responseHeaders: Headers? = headersOf(),\n webSocketCloseTimeout: Long = RealWebSocket.CANCEL_AFTER_CLOSE_MILLIS,\n ) {\n val url = \"http://example.com/websocket\"\n val response =\n Response\n .Builder()\n .code(101)\n .message(\"OK\")\n .request(Request.Builder().url(url).build())\n .headers(responseHeaders!!)\n .protocol(Protocol.HTTP_1_1)\n .build()\n webSocket =\n RealWebSocket(\n taskFaker.taskRunner,\n response.request,\n listener,\n random!!,\n pingIntervalMillis.toLong(),\n parse(\n responseHeaders,\n ),\n RealWebSocket.DEFAULT_MINIMUM_DEFLATE_SIZE,\n webSocketCloseTimeout,\n ).apply {\n if (client) {\n call =\n object : FailingCall() {\n override fun cancel() {\n this@TestStreams.cancel()\n }\n }\n }\n }\n webSocket!!.initReaderAndWriter(name, this, client)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":528,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n this@TestStreams.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":541,"symbol":"clientSourceBufferSize","kind":"function","lang":"kotlin","doc":"Peeks the number of bytes available for the client to read immediately. This doesn't block so it requires that bytes have already been flushed by the server.","code":"fun clientSourceBufferSize(): Long {\n source.request(1L)\n return source.buffer.size\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":546,"symbol":"processNextFrame","kind":"function","lang":"kotlin","code":"fun processNextFrame(): Boolean {\n taskFaker.runTasks()\n return webSocket!!.processNextFrame()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":551,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n canceled = true\n delegate.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/RealWebSocketTest.kt","line":558,"symbol":"ns","kind":"function","lang":"kotlin","code":"private fun ns(millis: Long): Long = millis * 1000000L"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":23,"symbol":"WebSocketExtensionsTest","kind":"class","lang":"kotlin","code":"class WebSocketExtensionsTest {\n @Test\n fun emptyHeader() {\n assertThat(parse(\"\")).isEqualTo(WebSocketExtensions())\n }\n\n @Test\n fun noExtensionHeader() {\n assertThat(WebSocketExtensions.parse(headersOf()))\n .isEqualTo(WebSocketExtensions())\n }\n\n @Test\n fun emptyExtension() {\n assertThat(parse(\", permessage-deflate\"))\n .isEqualTo(WebSocketExtensions(perMessageDeflate = true, unknownValues = true))\n }\n\n @Test\n fun unknownExtension() {\n assertThat(parse(\"unknown-ext\"))\n .isEqualTo(WebSocketExtensions(unknownValues = true))\n }\n\n @Test\n fun perMessageDeflate() {\n assertThat(parse(\"permessage-deflate\"))\n .isEqualTo(WebSocketExtensions(perMessageDeflate = true))\n }\n\n @Test\n fun emptyParameters() {\n assertThat(parse(\"permessage-deflate;\"))\n .isEqualTo(WebSocketExtensions(perMessageDeflate = true))\n }\n\n @Test\n fun repeatedPerMessageDeflate() {\n assertThat(parse(\"permessage-deflate, permessage-deflate; server_no_context_takeover\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n serverNoContextTakeover = true,\n unknownValues = true,\n ),\n )\n }\n\n @Test\n fun mul"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":24,"symbol":"emptyHeader","kind":"function","lang":"kotlin","code":"@Test\n fun emptyHeader() {\n assertThat(parse(\"\")).isEqualTo(WebSocketExtensions())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":29,"symbol":"noExtensionHeader","kind":"function","lang":"kotlin","code":"@Test\n fun noExtensionHeader() {\n assertThat(WebSocketExtensions.parse(headersOf()))\n .isEqualTo(WebSocketExtensions())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":35,"symbol":"emptyExtension","kind":"function","lang":"kotlin","code":"@Test\n fun emptyExtension() {\n assertThat(parse(\", permessage-deflate\"))\n .isEqualTo(WebSocketExtensions(perMessageDeflate = true, unknownValues = true))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":41,"symbol":"unknownExtension","kind":"function","lang":"kotlin","code":"@Test\n fun unknownExtension() {\n assertThat(parse(\"unknown-ext\"))\n .isEqualTo(WebSocketExtensions(unknownValues = true))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":47,"symbol":"perMessageDeflate","kind":"function","lang":"kotlin","code":"@Test\n fun perMessageDeflate() {\n assertThat(parse(\"permessage-deflate\"))\n .isEqualTo(WebSocketExtensions(perMessageDeflate = true))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":53,"symbol":"emptyParameters","kind":"function","lang":"kotlin","code":"@Test\n fun emptyParameters() {\n assertThat(parse(\"permessage-deflate;\"))\n .isEqualTo(WebSocketExtensions(perMessageDeflate = true))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":59,"symbol":"repeatedPerMessageDeflate","kind":"function","lang":"kotlin","code":"@Test\n fun repeatedPerMessageDeflate() {\n assertThat(parse(\"permessage-deflate, permessage-deflate; server_no_context_takeover\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n serverNoContextTakeover = true,\n unknownValues = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":71,"symbol":"multiplePerMessageDeflateHeaders","kind":"function","lang":"kotlin","code":"@Test\n fun multiplePerMessageDeflateHeaders() {\n val extensions =\n WebSocketExtensions.parse(\n headersOf(\n \"Sec-WebSocket-Extensions\",\n \"\",\n \"Sec-WebSocket-Extensions\",\n \"permessage-deflate\",\n ),\n )\n assertThat(extensions)\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":90,"symbol":"noContextTakeoverServerAndClient","kind":"function","lang":"kotlin","code":"@Test\n fun noContextTakeoverServerAndClient() {\n assertThat(parse(\"permessage-deflate; server_no_context_takeover; client_no_context_takeover\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n clientNoContextTakeover = true,\n serverNoContextTakeover = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":102,"symbol":"everything","kind":"function","lang":"kotlin","code":"@Test\n fun everything() {\n assertThat(\n parse(\n \"permessage-deflate; client_max_window_bits=15; client_no_context_takeover; \" +\n \"server_max_window_bits=8; server_no_context_takeover\",\n ),\n ).isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n clientMaxWindowBits = 15,\n clientNoContextTakeover = true,\n serverMaxWindowBits = 8,\n serverNoContextTakeover = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":120,"symbol":"noWhitespace","kind":"function","lang":"kotlin","code":"@Test\n fun noWhitespace() {\n assertThat(parse(\"permessage-deflate;server_no_context_takeover;client_no_context_takeover\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n clientNoContextTakeover = true,\n serverNoContextTakeover = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":132,"symbol":"excessWhitespace","kind":"function","lang":"kotlin","code":"@Test\n fun excessWhitespace() {\n assertThat(\n parse(\n \" permessage-deflate\\t ; \\tserver_no_context_takeover\\t ; client_no_context_takeover \",\n ),\n ).isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n clientNoContextTakeover = true,\n serverNoContextTakeover = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":147,"symbol":"noContextTakeoverClientAndServer","kind":"function","lang":"kotlin","code":"@Test\n fun noContextTakeoverClientAndServer() {\n assertThat(parse(\"permessage-deflate; client_no_context_takeover; server_no_context_takeover\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n clientNoContextTakeover = true,\n serverNoContextTakeover = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":159,"symbol":"noContextTakeoverClient","kind":"function","lang":"kotlin","code":"@Test\n fun noContextTakeoverClient() {\n assertThat(parse(\"permessage-deflate; client_no_context_takeover\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n clientNoContextTakeover = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":170,"symbol":"noContextTakeoverServer","kind":"function","lang":"kotlin","code":"@Test\n fun noContextTakeoverServer() {\n assertThat(parse(\"permessage-deflate; server_no_context_takeover\")).isEqualTo(\n WebSocketExtensions(perMessageDeflate = true, serverNoContextTakeover = true),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":177,"symbol":"clientMaxWindowBits","kind":"function","lang":"kotlin","code":"@Test\n fun clientMaxWindowBits() {\n assertThat(parse(\"permessage-deflate; client_max_window_bits=8\")).isEqualTo(\n WebSocketExtensions(perMessageDeflate = true, clientMaxWindowBits = 8),\n )\n assertThat(parse(\"permessage-deflate; client_max_window_bits=\\\"8\\\"\")).isEqualTo(\n WebSocketExtensions(perMessageDeflate = true, clientMaxWindowBits = 8),\n )\n assertThat(parse(\"permessage-deflate; client_max_window_bits=15\")).isEqualTo(\n WebSocketExtensions(perMessageDeflate = true, clientMaxWindowBits = 15),\n )\n assertThat(parse(\"permessage-deflate; client_max_window_bits=\\\"15\\\"\")).isEqualTo(\n WebSocketExtensions(perMessageDeflate = true, clientMaxWindowBits = 15),\n )\n assertThat(parse(\"permessage-deflate; client_max_window_bits\\t =\\t 8\\t \")).isEqualTo(\n WebSocketExtensions(perMessageDeflate = true, clientMaxWindowBits = 8),\n )\n assertThat(parse(\"permessage-deflate; client_max_window_bits\\t =\\t \\\"8\\\"\\t \")).isEqualTo(\n WebSocketExtensions(perMessageDeflate = true, clientMaxWindowBits = 8),\n )\n }\n\n @Test\n fun serverMaxWindowBits() {\n assertThat(parse(\"permessage-deflate; server_max_window_bits=8\")).isEqualTo(\n WebSocketE"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":231,"symbol":"unexpectedValue","kind":"function","lang":"kotlin","code":"@Test\n fun unexpectedValue() {\n assertThat(parse(\"permessage-deflate; client_no_context_takeover=true\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n clientNoContextTakeover = true,\n unknownValues = true,\n ),\n )\n assertThat(parse(\"permessage-deflate; server_max_window_bits=true\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n unknownValues = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":250,"symbol":"absentValue","kind":"function","lang":"kotlin","code":"@Test\n fun absentValue() {\n assertThat(parse(\"permessage-deflate; server_max_window_bits\")).isEqualTo(\n WebSocketExtensions(perMessageDeflate = true, unknownValues = true),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":257,"symbol":"uppercase","kind":"function","lang":"kotlin","code":"@Test\n fun uppercase() {\n assertThat(parse(\"PERMESSAGE-DEFLATE; SERVER_NO_CONTEXT_TAKEOVER; CLIENT_NO_CONTEXT_TAKEOVER\"))\n .isEqualTo(\n WebSocketExtensions(\n perMessageDeflate = true,\n clientNoContextTakeover = true,\n serverNoContextTakeover = true,\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketExtensionsTest.kt","line":269,"symbol":"parse","kind":"function","lang":"kotlin","code":"private fun parse(extension: String) = WebSocketExtensions.parse(headersOf(\"Sec-WebSocket-Extensions\", extension))"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":78,"symbol":"WebSocketHttpTest","kind":"class","lang":"kotlin","code":"@Flaky\n@Tag(\"Slow\")\nclass WebSocketHttpTest {\n // Flaky https://github.com/lysine-dev/okhttp/issues/4515\n // Flaky https://github.com/lysine-dev/okhttp/issues/4953\n @RegisterExtension\n var clientTestRule = configureClientTestRule()\n\n @RegisterExtension\n var platform = PlatformRule()\n\n @RegisterExtension\n var testLogHandler = TestLogHandler(OkHttpClient::class.java)\n\n @StartStop\n private val webServer = MockWebServer()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private val clientListener = WebSocketRecorder(\"client\")\n private val serverListener = WebSocketRecorder(\"server\")\n private val random = Random(0)\n private var client =\n clientTestRule\n .newClientBuilder()\n .writeTimeout(Duration.ofMillis(500))\n .readTimeout(Duration.ofMillis(500))\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain ->\n val response = chain.proceed(chain.request())\n // Ensure application interceptors never see a null body.\n assertThat(response.body).isNotNull()\n response\n },\n ).build()\n\n private fun configureClientTestRule(): OkHttpClientTestRule {\n val clientTestRule = "} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":113,"symbol":"configureClientTestRule","kind":"function","lang":"kotlin","code":"private fun configureClientTestRule(): OkHttpClientTestRule {\n val clientTestRule = OkHttpClientTestRule()\n clientTestRule.recordTaskRunner = true\n return clientTestRule\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":119,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n platform.assumeNotOpenJSSE()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":124,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n @Throws(InterruptedException::class)\n fun tearDown() {\n clientListener.assertExhausted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":130,"symbol":"textMessage","kind":"function","lang":"kotlin","code":"@Test\n fun textMessage() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n webSocket.send(\"Hello, WebSockets!\")\n serverListener.assertTextMessage(\"Hello, WebSockets!\")\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":146,"symbol":"binaryMessage","kind":"function","lang":"kotlin","code":"@Test\n fun binaryMessage() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n webSocket.send(\"Hello!\".encodeUtf8())\n serverListener.assertBinaryMessage(\"Hello!\".encodeUtf8())\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":162,"symbol":"serverMessage","kind":"function","lang":"kotlin","code":"@Test\n fun serverMessage() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n server.send(\"Hello, WebSockets!\")\n clientListener.assertTextMessage(\"Hello, WebSockets!\")\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":178,"symbol":"throwingOnOpenFailsImmediately","kind":"function","lang":"kotlin","code":"@Test\n fun throwingOnOpenFailsImmediately() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val e = RuntimeException()\n clientListener.setNextEventDelegate(\n object : WebSocketListener() {\n override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ): Unit = throw e\n },\n )\n newWebSocket()\n serverListener.assertOpen()\n serverListener.assertFailure(EOFException::class.java)\n serverListener.assertExhausted()\n clientListener.assertFailure(e)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":189,"symbol":"onOpen","kind":"function","lang":"kotlin","code":"override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ): Unit = throw e"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":202,"symbol":"throwingOnFailLogs","kind":"function","lang":"kotlin","code":"@Disabled(\"AsyncCall currently lets runtime exceptions propagate.\")\n @Test\n @Throws(\n Exception::class,\n )\n fun throwingOnFailLogs() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(200)\n .body(\"Body\")\n .build(),\n )\n val e = RuntimeException(\"boom\")\n clientListener.setNextEventDelegate(\n object : WebSocketListener() {\n override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ): Unit = throw e\n },\n )\n newWebSocket()\n assertThat(testLogHandler.take()).isEqualTo(\"INFO: [WS client] onFailure\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":218,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ): Unit = throw e"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":229,"symbol":"throwingOnMessageClosesImmediatelyAndFails","kind":"function","lang":"kotlin","code":"@Test\n fun throwingOnMessageClosesImmediatelyAndFails() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n val e = RuntimeException()\n clientListener.setNextEventDelegate(\n object : WebSocketListener() {\n override fun onMessage(\n webSocket: WebSocket,\n text: String,\n ): Unit = throw e\n },\n )\n server.send(\"Hello, WebSockets!\")\n clientListener.assertFailure(e)\n serverListener.assertFailure(EOFException::class.java)\n serverListener.assertExhausted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":243,"symbol":"onMessage","kind":"function","lang":"kotlin","code":"override fun onMessage(\n webSocket: WebSocket,\n text: String,\n ): Unit = throw e"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":255,"symbol":"throwingOnClosingClosesImmediatelyAndFails","kind":"function","lang":"kotlin","code":"@Test\n fun throwingOnClosingClosesImmediatelyAndFails() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n val e = RuntimeException()\n clientListener.setNextEventDelegate(\n object : WebSocketListener() {\n override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ): Unit = throw e\n },\n )\n server.close(1000, \"bye\")\n clientListener.assertFailure(e)\n serverListener.assertFailure()\n serverListener.assertExhausted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":269,"symbol":"onClosing","kind":"function","lang":"kotlin","code":"override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ): Unit = throw e"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":282,"symbol":"unplannedCloseHandledByCloseWithoutFailure","kind":"function","lang":"kotlin","code":"@Test\n fun unplannedCloseHandledByCloseWithoutFailure() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n clientListener.setNextEventDelegate(\n object : WebSocketListener() {\n override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n webSocket.close(1000, null)\n }\n },\n )\n server.close(1001, \"bye\")\n clientListener.assertClosed(1001, \"bye\")\n clientListener.assertExhausted()\n serverListener.assertClosing(1000, \"\")\n serverListener.assertClosed(1000, \"\")\n serverListener.assertExhausted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":295,"symbol":"onClosing","kind":"function","lang":"kotlin","code":"override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n webSocket.close(1000, null)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":312,"symbol":"unplannedCloseHandledWithoutFailure","kind":"function","lang":"kotlin","code":"@Test\n fun unplannedCloseHandledWithoutFailure() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n newWebSocket()\n val webSocket = clientListener.assertOpen()\n val server = serverListener.assertOpen()\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":326,"symbol":"non101RetainsBody","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun non101RetainsBody() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(200)\n .body(\"Body\")\n .build(),\n )\n newWebSocket()\n clientListener.assertFailure(\n 200,\n \"Body\",\n ProtocolException::class.java,\n \"Expected HTTP 101 response but was '200 OK'\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":345,"symbol":"notFound","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun notFound() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .status(\"HTTP/1.1 404 Not Found\")\n .build(),\n )\n newWebSocket()\n clientListener.assertFailure(\n 404,\n null,\n ProtocolException::class.java,\n \"Expected HTTP 101 response but was '404 Not Found'\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":363,"symbol":"clientTimeoutClosesBody","kind":"function","lang":"kotlin","code":"@Test\n fun clientTimeoutClosesBody() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(408)\n .build(),\n )\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n webSocket.send(\"abc\")\n serverListener.assertTextMessage(\"abc\")\n server.send(\"def\")\n clientListener.assertTextMessage(\"def\")\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":387,"symbol":"missingConnectionHeader","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun missingConnectionHeader() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(101)\n .setHeader(\"Upgrade\", \"websocket\")\n .setHeader(\"Sec-WebSocket-Accept\", \"ujmZX4KXZqjwy6vi1aQFH5p4Ygk=\")\n .build(),\n )\n webServer.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseSocket())\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertFailure(\n 101,\n null,\n ProtocolException::class.java,\n \"Expected 'Connection' header value 'Upgrade' but was 'null'\",\n )\n webSocket.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":414,"symbol":"wrongConnectionHeader","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun wrongConnectionHeader() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(101)\n .setHeader(\"Upgrade\", \"websocket\")\n .setHeader(\"Connection\", \"Downgrade\")\n .setHeader(\"Sec-WebSocket-Accept\", \"ujmZX4KXZqjwy6vi1aQFH5p4Ygk=\")\n .build(),\n )\n webServer.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseSocket())\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertFailure(\n 101,\n null,\n ProtocolException::class.java,\n \"Expected 'Connection' header value 'Upgrade' but was 'Downgrade'\",\n )\n webSocket.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":442,"symbol":"missingUpgradeHeader","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun missingUpgradeHeader() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(101)\n .setHeader(\"Connection\", \"Upgrade\")\n .setHeader(\"Sec-WebSocket-Accept\", \"ujmZX4KXZqjwy6vi1aQFH5p4Ygk=\")\n .build(),\n )\n webServer.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseSocket())\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertFailure(\n 101,\n null,\n ProtocolException::class.java,\n \"Expected 'Upgrade' header value 'websocket' but was 'null'\",\n )\n webSocket.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":469,"symbol":"wrongUpgradeHeader","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun wrongUpgradeHeader() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(101)\n .setHeader(\"Connection\", \"Upgrade\")\n .setHeader(\"Upgrade\", \"Pepsi\")\n .setHeader(\"Sec-WebSocket-Accept\", \"ujmZX4KXZqjwy6vi1aQFH5p4Ygk=\")\n .build(),\n )\n webServer.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseSocket())\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertFailure(\n 101,\n null,\n ProtocolException::class.java,\n \"Expected 'Upgrade' header value 'websocket' but was 'Pepsi'\",\n )\n webSocket.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":497,"symbol":"missingMagicHeader","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun missingMagicHeader() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(101)\n .setHeader(\"Connection\", \"Upgrade\")\n .setHeader(\"Upgrade\", \"websocket\")\n .build(),\n )\n webServer.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseSocket())\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertFailure(\n 101,\n null,\n ProtocolException::class.java,\n \"Expected 'Sec-WebSocket-Accept' header value 'ujmZX4KXZqjwy6vi1aQFH5p4Ygk=' but was 'null'\",\n )\n webSocket.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":524,"symbol":"wrongMagicHeader","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun wrongMagicHeader() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(101)\n .setHeader(\"Connection\", \"Upgrade\")\n .setHeader(\"Upgrade\", \"websocket\")\n .setHeader(\"Sec-WebSocket-Accept\", \"magic\")\n .build(),\n )\n webServer.enqueue(\n MockResponse\n .Builder()\n .onRequestStart(CloseSocket())\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertFailure(\n 101,\n null,\n ProtocolException::class.java,\n \"Expected 'Sec-WebSocket-Accept' header value 'ujmZX4KXZqjwy6vi1aQFH5p4Ygk=' but was 'magic'\",\n )\n webSocket.cancel()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":552,"symbol":"clientIncludesForbiddenHeader","kind":"function","lang":"kotlin","code":"@Test\n @Throws(IOException::class)\n fun clientIncludesForbiddenHeader() {\n newWebSocket(\n Request\n .Builder()\n .url(webServer.url(\"/\"))\n .header(\"Sec-WebSocket-Extensions\", \"permessage-deflate\")\n .build(),\n )\n clientListener.assertFailure(\n ProtocolException::class.java,\n \"Request header not permitted: 'Sec-WebSocket-Extensions'\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":568,"symbol":"webSocketAndApplicationInterceptors","kind":"function","lang":"kotlin","code":"@Test\n fun webSocketAndApplicationInterceptors() {\n val interceptedCount = AtomicInteger()\n client =\n client\n .newBuilder()\n .addInterceptor(\n Interceptor { chain: Interceptor.Chain ->\n assertThat(chain.request().body).isNull()\n val response = chain.proceed(chain.request())\n assertThat(response.header(\"Connection\")).isEqualTo(\"Upgrade\")\n assertThat(response.body).isInstanceOf()\n interceptedCount.incrementAndGet()\n response\n },\n ).build()\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n assertThat(interceptedCount.get()).isEqualTo(1)\n closeWebSockets(webSocket, serverListener.assertOpen())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":596,"symbol":"webSocketAndNetworkInterceptors","kind":"function","lang":"kotlin","code":"@Test\n fun webSocketAndNetworkInterceptors() {\n client =\n client\n .newBuilder()\n .addNetworkInterceptor(\n Interceptor { chain: Interceptor.Chain? ->\n throw AssertionError() // Network interceptors don't execute.\n },\n ).build()\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":618,"symbol":"overflowOutgoingQueue","kind":"function","lang":"kotlin","code":"@Test\n fun overflowOutgoingQueue() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n\n // Send messages until the client's outgoing buffer overflows!\n val message: ByteString = ByteString.of(*ByteArray(1024 * 1024))\n var messageCount: Long = 0\n while (true) {\n val success = webSocket.send(message)\n if (!success) break\n messageCount++\n val queueSize = webSocket.queueSize()\n assertThat(queueSize).isBetween(0L, messageCount * message.size)\n // Expect to fail before enqueueing 32 MiB.\n assertThat(messageCount).isLessThan(32L)\n }\n\n // Confirm all sent messages were received, followed by a client-initiated close.\n val server = serverListener.assertOpen()\n for (i in 0 until messageCount) {\n serverListener.assertBinaryMessage(message)\n }\n serverListener.assertClosing(1001, \"\")\n\n // When the server acknowledges the close the connection shuts down gracefully.\n server.close(1000, null)\n clientListener.assertClosing(1000, \"\")\n clientListener.assertClosed(100"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":656,"symbol":"closeReasonMaximumLength","kind":"function","lang":"kotlin","code":"@Test\n fun closeReasonMaximumLength() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val clientReason = repeat('C', 123)\n val serverReason = repeat('S', 123)\n val webSocket: WebSocket = newWebSocket()\n val server = serverListener.assertOpen()\n clientListener.assertOpen()\n webSocket.close(1000, clientReason)\n serverListener.assertClosing(1000, clientReason)\n server.close(1000, serverReason)\n clientListener.assertClosing(1000, serverReason)\n clientListener.assertClosed(1000, serverReason)\n serverListener.assertClosed(1000, clientReason)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":677,"symbol":"closeReasonTooLong","kind":"function","lang":"kotlin","code":"@Test\n fun closeReasonTooLong() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n val server = serverListener.assertOpen()\n clientListener.assertOpen()\n val reason = repeat('X', 124)\n assertFailsWith {\n webSocket.close(1000, reason)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"reason.size() > 123: $reason\")\n }\n webSocket.close(1000, null)\n serverListener.assertClosing(1000, \"\")\n server.close(1000, null)\n clientListener.assertClosing(1000, \"\")\n clientListener.assertClosed(1000, \"\")\n serverListener.assertClosed(1000, \"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":702,"symbol":"wsScheme","kind":"function","lang":"kotlin","code":"@Test\n fun wsScheme() {\n assumeNotWindows()\n websocketScheme(\"ws\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":708,"symbol":"wsUppercaseScheme","kind":"function","lang":"kotlin","code":"@Test\n fun wsUppercaseScheme() {\n websocketScheme(\"WS\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":713,"symbol":"wssScheme","kind":"function","lang":"kotlin","code":"@Test\n fun wssScheme() {\n webServer.useHttps(handshakeCertificates.sslSocketFactory())\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n websocketScheme(\"wss\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":727,"symbol":"httpsScheme","kind":"function","lang":"kotlin","code":"@Test\n fun httpsScheme() {\n webServer.useHttps(handshakeCertificates.sslSocketFactory())\n client =\n client\n .newBuilder()\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(RecordingHostnameVerifier())\n .build()\n websocketScheme(\"https\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":741,"symbol":"readTimeoutAppliesToHttpRequest","kind":"function","lang":"kotlin","code":"@Test\n fun readTimeoutAppliesToHttpRequest() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .onResponseStart(Stall)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertFailure(\n SocketTimeoutException::class.java,\n \"timeout\",\n \"Read timed out\",\n )\n assertThat(webSocket.close(1000, null)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":763,"symbol":"readTimeoutAppliesWithinFrames","kind":"function","lang":"kotlin","doc":"There's no read timeout when reading the first byte of a new frame. But as soon as we start reading a frame we enable the read timeout. In this test we have the server returning the first byte of a frame but no more frames.","code":"@Test\n fun readTimeoutAppliesWithinFrames() {\n webServer.dispatcher =\n object : Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse =\n upgradeResponse(request)\n .body(Buffer().write(\"81\".decodeHex())) // Truncated frame.\n .removeHeader(\"Content-Length\")\n .build()\n }\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n clientListener.assertFailure(\n SocketTimeoutException::class.java,\n \"timeout\",\n \"Read timed out\",\n )\n assertThat(webSocket.close(1000, null)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":767,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"override fun dispatch(request: RecordedRequest): MockResponse =\n upgradeResponse(request)\n .body(Buffer().write(\"81\".decodeHex())) // Truncated frame.\n .removeHeader(\"Content-Length\")\n .build()"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":783,"symbol":"readTimeoutDoesNotApplyAcrossFrames","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun readTimeoutDoesNotApplyAcrossFrames() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n\n // Sleep longer than the HTTP client's read timeout.\n Thread.sleep((client.readTimeoutMillis + 500).toLong())\n server.send(\"abc\")\n clientListener.assertTextMessage(\"abc\")\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":803,"symbol":"clientPingsServerOnInterval","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun clientPingsServerOnInterval() {\n client =\n client\n .newBuilder()\n .pingInterval(Duration.ofMillis(500))\n .build()\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen() as RealWebSocket\n val startNanos = System.nanoTime()\n while (webSocket.receivedPongCount() < 3) {\n Thread.sleep(50)\n }\n val elapsedUntilPong3 = System.nanoTime() - startNanos\n assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedUntilPong3).toDouble())\n .isCloseTo(1500.0, 250.0)\n\n // The client pinged the server 3 times, and it has ponged back 3 times.\n assertThat(webSocket.sentPingCount()).isEqualTo(3)\n assertThat(server.receivedPingCount()).isEqualTo(3)\n assertThat(webSocket.receivedPongCount()).isEqualTo(3)\n\n // The server has never pinged the client.\n assertThat(server.receivedPongCount()).isEqualTo(0)\n assertThat(webSocket.receivedPingCount()).isEqualTo(0)\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":839,"symbol":"clientDoesNotPingServerByDefault","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun clientDoesNotPingServerByDefault() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen() as RealWebSocket\n Thread.sleep(1000)\n\n // No pings and no pongs.\n assertThat(webSocket.sentPingCount()).isEqualTo(0)\n assertThat(webSocket.receivedPingCount()).isEqualTo(0)\n assertThat(webSocket.receivedPongCount()).isEqualTo(0)\n assertThat(server.sentPingCount()).isEqualTo(0)\n assertThat(server.receivedPingCount()).isEqualTo(0)\n assertThat(server.receivedPongCount()).isEqualTo(0)\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":868,"symbol":"unacknowledgedPingFailsConnection","kind":"function","lang":"kotlin","doc":"Configure the websocket to send pings every 500 ms. Artificially prevent the server from responding to pings. The client should give up when attempting to send its 2nd ping, at about 1000 ms.","code":"@Test\n fun unacknowledgedPingFailsConnection() {\n assumeNotWindows()\n client =\n client\n .newBuilder()\n .pingInterval(Duration.ofMillis(500))\n .build()\n\n // Stall in onOpen to prevent pongs from being sent.\n val latch = CountDownLatch(1)\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(\n object : WebSocketListener() {\n override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n try {\n latch.await() // The server can't respond to pings!\n } catch (e: InterruptedException) {\n throw AssertionError(e)\n }\n }\n },\n ).build(),\n )\n val openAtNanos = System.nanoTime()\n newWebSocket()\n clientListener.assertOpen()\n clientListener.assertFailure(\n SocketTimeoutException::class.java,\n \"sent ping but didn't receive pong within 500ms (after 0 successful ping/pongs)\",\n )\n latch.countDown()\n val elapsedUntilFailure = System.nanoTime() - openAtNanos\n assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure).toDouble())\n ."} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":884,"symbol":"onOpen","kind":"function","lang":"kotlin","code":"override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n try {\n latch.await() // The server can't respond to pings!\n } catch (e: InterruptedException) {\n throw AssertionError(e)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":911,"symbol":"clientCancelsIfCloseIsNotAcknowledged","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/2788","code":"@Test\n fun clientCancelsIfCloseIsNotAcknowledged() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n\n // Initiate a close on the client, which will schedule a hard cancel in 500 ms.\n val closeAtNanos = System.nanoTime()\n webSocket.close(1000, \"goodbye\", 500L)\n serverListener.assertClosing(1000, \"goodbye\")\n\n // Confirm that the hard cancel occurred after 500 ms.\n clientListener.assertFailure()\n val elapsedUntilFailure = System.nanoTime() - closeAtNanos\n assertThat(TimeUnit.NANOSECONDS.toMillis(elapsedUntilFailure).toDouble())\n .isCloseTo(500.0, 250.0)\n\n // Close the server and confirm it saw what we expected.\n server.close(1000, null)\n serverListener.assertClosed(1000, \"goodbye\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":939,"symbol":"webSocketsDontTriggerEventListener","kind":"function","lang":"kotlin","code":"@Test\n fun webSocketsDontTriggerEventListener() {\n val eventRecorder = EventRecorder()\n client =\n client\n .newBuilder()\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n webSocket.send(\"Web Sockets and Events?!\")\n serverListener.assertTextMessage(\"Web Sockets and Events?!\")\n webSocket.close(1000, \"\")\n serverListener.assertClosing(1000, \"\")\n server.close(1000, \"\")\n clientListener.assertClosing(1000, \"\")\n clientListener.assertClosed(1000, \"\")\n serverListener.assertClosed(1000, \"\")\n assertThat(eventRecorder.recordedEventTypes()).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":967,"symbol":"callTimeoutAppliesToSetup","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun callTimeoutAppliesToSetup() {\n webServer.enqueue(\n MockResponse\n .Builder()\n .headersDelay(500, TimeUnit.MILLISECONDS)\n .build(),\n )\n client =\n client\n .newBuilder()\n .readTimeout(Duration.ZERO)\n .writeTimeout(Duration.ZERO)\n .callTimeout(Duration.ofMillis(100))\n .build()\n newWebSocket()\n clientListener.assertFailure(InterruptedIOException::class.java, \"timeout\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":987,"symbol":"callTimeoutDoesNotApplyOnceConnected","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun callTimeoutDoesNotApplyOnceConnected() {\n client =\n client\n .newBuilder()\n .callTimeout(Duration.ofMillis(100))\n .build()\n webServer.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val webSocket: WebSocket = newWebSocket()\n clientListener.assertOpen()\n val server = serverListener.assertOpen()\n Thread.sleep(500)\n server.send(\"Hello, WebSockets!\")\n clientListener.assertTextMessage(\"Hello, WebSockets!\")\n closeWebSockets(webSocket, server)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1015,"symbol":"webSocketConnectionIsReleased","kind":"function","lang":"kotlin","doc":"We had a bug where web socket connections were leaked if the HTTP connection upgrade was not successful. This test confirms that connections are released back to the connection pool! https://github.com/lysine-dev/okhttp/issues/4258","code":"@Test\n @Throws(Exception::class)\n fun webSocketConnectionIsReleased() {\n // This test assumes HTTP/1.1 pooling semantics.\n client =\n client\n .newBuilder()\n .protocols(Arrays.asList(Protocol.HTTP_1_1))\n .build()\n webServer.enqueue(\n MockResponse\n .Builder()\n .code(HttpURLConnection.HTTP_NOT_FOUND)\n .body(\"not found!\")\n .build(),\n )\n webServer.enqueue(MockResponse())\n newWebSocket()\n clientListener.assertFailure()\n val regularRequest =\n Request\n .Builder()\n .url(webServer.url(\"/\"))\n .build()\n val response = client.newCall(regularRequest).execute()\n response.close()\n assertThat(webServer.takeRequest().exchangeIndex).isEqualTo(0)\n assertThat(webServer.takeRequest().exchangeIndex).isEqualTo(1)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1046,"symbol":"closeWithoutSuccessfulConnect","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/5705","code":"@Test\n fun closeWithoutSuccessfulConnect() {\n val request =\n Request\n .Builder()\n .url(webServer.url(\"/\"))\n .build()\n val webSocket = client.newWebSocket(request, clientListener)\n webSocket.send(\"hello\")\n webSocket.close(1000, null)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1059,"symbol":"reconnectingToNonWebSocket","kind":"function","lang":"kotlin","doc":"https://github.com/lysine-dev/okhttp/issues/7768","code":"@Test\n @Throws(InterruptedException::class)\n fun reconnectingToNonWebSocket() {\n for (i in 0..29) {\n webServer.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(100, TimeUnit.MILLISECONDS)\n .body(\"Wrong endpoint\")\n .code(401)\n .build(),\n )\n }\n val request =\n Request\n .Builder()\n .url(webServer.url(\"/\"))\n .build()\n val attempts = CountDownLatch(20)\n val webSockets = Collections.synchronizedList(ArrayList())\n val reconnectOnFailure: WebSocketListener =\n object : WebSocketListener() {\n override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n if (attempts.count > 0) {\n clientListener.setNextEventDelegate(this)\n webSockets.add(client.newWebSocket(request, clientListener))\n attempts.countDown()\n }\n }\n }\n clientListener.setNextEventDelegate(reconnectOnFailure)\n webSockets.add(client.newWebSocket(request, clientListener))\n attempts.await()\n synchronized(webSockets) {\n for (webSocket in webSockets) {\n webSocket.ca"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1081,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n if (attempts.count > 0) {\n clientListener.setNextEventDelegate(this)\n webSockets.add(client.newWebSocket(request, clientListener))\n attempts.countDown()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1103,"symbol":"compressedMessages","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun compressedMessages() {\n successfulExtensions(\"permessage-deflate\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1109,"symbol":"compressedMessagesNoClientContextTakeover","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun compressedMessagesNoClientContextTakeover() {\n successfulExtensions(\"permessage-deflate; client_no_context_takeover\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1115,"symbol":"compressedMessagesNoServerContextTakeover","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun compressedMessagesNoServerContextTakeover() {\n successfulExtensions(\"permessage-deflate; server_no_context_takeover\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1121,"symbol":"unexpectedExtensionParameter","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun unexpectedExtensionParameter() {\n extensionNegotiationFailure(\"permessage-deflate; unknown_parameter=15\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1127,"symbol":"clientMaxWindowBitsIncluded","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun clientMaxWindowBitsIncluded() {\n extensionNegotiationFailure(\"permessage-deflate; client_max_window_bits=15\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1133,"symbol":"serverMaxWindowBitsTooLow","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun serverMaxWindowBitsTooLow() {\n extensionNegotiationFailure(\"permessage-deflate; server_max_window_bits=7\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketHttpTest.kt","line":1139,"symbol":"serverMaxWindowBitsTooHigh","kind":"function","lang":"kotlin","code":"@Test\n @Throws(Exception::class)\n fun serverMaxWindowBitsTooHigh() {\n extensionNegotiationFailure(\"permessage-deflate; server_max_window_bits=16\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":37,"symbol":"WebSocketReaderTest","kind":"class","lang":"kotlin","code":"class WebSocketReaderTest {\n private val data = Buffer()\n private val callback = WebSocketRecorder(\"client\")\n private val random = Random(0)\n\n // Mutually exclusive. Use the one corresponding to the peer whose behavior you wish to test.\n private val serverReader =\n WebSocketReader(\n isClient = false,\n source = data,\n frameCallback = callback.asFrameCallback(),\n perMessageDeflate = false,\n noContextTakeover = false,\n )\n private val serverReaderWithCompression =\n WebSocketReader(\n isClient = false,\n source = data,\n frameCallback = callback.asFrameCallback(),\n perMessageDeflate = true,\n noContextTakeover = false,\n )\n private val clientReader =\n WebSocketReader(\n isClient = true,\n source = data,\n frameCallback = callback.asFrameCallback(),\n perMessageDeflate = false,\n noContextTakeover = false,\n )\n private val clientReaderWithCompression =\n WebSocketReader(\n isClient = true,\n source = data,\n frameCallback = callback.asFrameCallback(),\n perMessageDeflate = true,\n noContextTakeover = false,\n )\n\n @AfterEach fun tearDown() {\n callback.assertExhausted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":76,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n callback.assertExhausted()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":80,"symbol":"controlFramesMustBeFinal","kind":"function","lang":"kotlin","code":"@Test fun controlFramesMustBeFinal() {\n data.write(\"0a00\".decodeHex()) // Empty pong.\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Control frames must be final.\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":90,"symbol":"reservedFlag1IsUnsupportedWithNoCompression","kind":"function","lang":"kotlin","code":"@Test fun reservedFlag1IsUnsupportedWithNoCompression() {\n data.write(\"ca00\".decodeHex()) // Empty pong, flag 1 set.\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Unexpected rsv1 flag\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":99,"symbol":"reservedFlag1IsUnsupportedForControlFrames","kind":"function","lang":"kotlin","code":"@Test fun reservedFlag1IsUnsupportedForControlFrames() {\n data.write(\"ca00\".decodeHex()) // Empty pong, flag 1 set.\n assertFailsWith {\n clientReaderWithCompression.processNextFrame()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Unexpected rsv1 flag\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":108,"symbol":"reservedFlag1IsUnsupportedForContinuationFrames","kind":"function","lang":"kotlin","code":"@Test fun reservedFlag1IsUnsupportedForContinuationFrames() {\n data.write(\"c000\".decodeHex()) // Empty continuation, flag 1 set.\n assertFailsWith {\n clientReaderWithCompression.processNextFrame()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Unexpected rsv1 flag\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":117,"symbol":"reservedFlags2and3AreUnsupported","kind":"function","lang":"kotlin","code":"@Test fun reservedFlags2and3AreUnsupported() {\n data.write(\"aa00\".decodeHex()) // Empty pong, flag 2 set.\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Unexpected rsv2 flag\")\n }\n data.clear()\n data.write(\"9a00\".decodeHex()) // Empty pong, flag 3 set.\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Unexpected rsv3 flag\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":133,"symbol":"clientSentFramesMustBeMasked","kind":"function","lang":"kotlin","code":"@Test fun clientSentFramesMustBeMasked() {\n data.write(\"8100\".decodeHex())\n assertFailsWith {\n serverReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Client-sent frames must be masked.\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":143,"symbol":"serverSentFramesMustNotBeMasked","kind":"function","lang":"kotlin","code":"@Test fun serverSentFramesMustNotBeMasked() {\n data.write(\"8180\".decodeHex())\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Server-sent frames must not be masked.\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":153,"symbol":"controlFramePayloadMax","kind":"function","lang":"kotlin","code":"@Test fun controlFramePayloadMax() {\n data.write(\"8a7e007e\".decodeHex())\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Control frame must be less than 125B.\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":163,"symbol":"clientSimpleHello","kind":"function","lang":"kotlin","code":"@Test fun clientSimpleHello() {\n data.write(\"810548656c6c6f\".decodeHex()) // Hello\n clientReader.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":169,"symbol":"clientWithCompressionSimpleUncompressedHello","kind":"function","lang":"kotlin","code":"@Test fun clientWithCompressionSimpleUncompressedHello() {\n data.write(\"810548656c6c6f\".decodeHex()) // Hello\n clientReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":175,"symbol":"clientWithCompressionSimpleCompressedHello","kind":"function","lang":"kotlin","code":"@Test fun clientWithCompressionSimpleCompressedHello() {\n data.write(\"c107f248cdc9c90700\".decodeHex()) // Hello\n clientReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":181,"symbol":"serverSimpleHello","kind":"function","lang":"kotlin","code":"@Test fun serverSimpleHello() {\n data.write(\"818537fa213d7f9f4d5158\".decodeHex()) // Hello\n serverReader.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":187,"symbol":"serverWithCompressionSimpleUncompressedHello","kind":"function","lang":"kotlin","code":"@Test fun serverWithCompressionSimpleUncompressedHello() {\n data.write(\"818537fa213d7f9f4d5158\".decodeHex()) // Hello\n serverReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":193,"symbol":"serverWithCompressionSimpleCompressedHello","kind":"function","lang":"kotlin","code":"@Test fun serverWithCompressionSimpleCompressedHello() {\n data.write(\"c18760b420bb92fced72a9b320\".decodeHex()) // Hello\n serverReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":199,"symbol":"clientFramePayloadShort","kind":"function","lang":"kotlin","code":"@Test fun clientFramePayloadShort() {\n data.write(\"817E000548656c6c6f\".decodeHex()) // Hello\n clientReader.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":205,"symbol":"clientFramePayloadLong","kind":"function","lang":"kotlin","code":"@Test fun clientFramePayloadLong() {\n data.write(\"817f000000000000000548656c6c6f\".decodeHex()) // Hello\n clientReader.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":211,"symbol":"clientFramePayloadTooLongThrows","kind":"function","lang":"kotlin","code":"@Test fun clientFramePayloadTooLongThrows() {\n data.write(\"817f8000000000000000\".decodeHex())\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"Frame length 0x8000000000000000 > 0x7FFFFFFFFFFFFFFF\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":222,"symbol":"serverHelloTwoChunks","kind":"function","lang":"kotlin","code":"@Test fun serverHelloTwoChunks() {\n data.write(\"818537fa213d7f9f4d\".decodeHex()) // Hel\n data.write(\"5158\".decodeHex()) // lo\n serverReader.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":229,"symbol":"serverWithCompressionHelloTwoChunks","kind":"function","lang":"kotlin","code":"@Test fun serverWithCompressionHelloTwoChunks() {\n data.write(\"818537fa213d7f9f4d\".decodeHex()) // Hel\n data.write(\"5158\".decodeHex()) // lo\n serverReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":236,"symbol":"serverWithCompressionCompressedHelloTwoChunks","kind":"function","lang":"kotlin","code":"@Test fun serverWithCompressionCompressedHelloTwoChunks() {\n data.write(\"418460b420bb92fced72\".decodeHex()) // first 4 bytes of compressed 'Hello'\n data.write(\"80833851d9d4f156d9\".decodeHex()) // last 3 bytes of compressed 'Hello'\n serverReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":243,"symbol":"clientTwoFrameHello","kind":"function","lang":"kotlin","code":"@Test fun clientTwoFrameHello() {\n data.write(\"010348656c\".decodeHex()) // Hel\n data.write(\"80026c6f\".decodeHex()) // lo\n clientReader.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":250,"symbol":"clientWithCompressionTwoFrameHello","kind":"function","lang":"kotlin","code":"@Test fun clientWithCompressionTwoFrameHello() {\n data.write(\"010348656c\".decodeHex()) // Hel\n data.write(\"80026c6f\".decodeHex()) // lo\n clientReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":257,"symbol":"clientWithCompressionTwoFrameCompressedHello","kind":"function","lang":"kotlin","code":"@Test fun clientWithCompressionTwoFrameCompressedHello() {\n data.write(\"4104f248cdc9\".decodeHex()) // first 4 bytes of compressed 'Hello'\n data.write(\"8003c90700\".decodeHex()) // last 3 bytes of compressed 'Hello'\n clientReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":264,"symbol":"clientTwoFrameHelloWithPongs","kind":"function","lang":"kotlin","code":"@Test fun clientTwoFrameHelloWithPongs() {\n data.write(\"010348656c\".decodeHex()) // Hel\n data.write(\"8a00\".decodeHex()) // Pong\n data.write(\"8a00\".decodeHex()) // Pong\n data.write(\"8a00\".decodeHex()) // Pong\n data.write(\"8a00\".decodeHex()) // Pong\n data.write(\"80026c6f\".decodeHex()) // lo\n clientReader.processNextFrame()\n callback.assertPong(EMPTY)\n callback.assertPong(EMPTY)\n callback.assertPong(EMPTY)\n callback.assertPong(EMPTY)\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":279,"symbol":"clientTwoFrameCompressedHelloWithPongs","kind":"function","lang":"kotlin","code":"@Test fun clientTwoFrameCompressedHelloWithPongs() {\n data.write(\"4104f248cdc9\".decodeHex()) // first 4 bytes of compressed 'Hello'\n data.write(\"8a00\".decodeHex()) // Pong\n data.write(\"8a00\".decodeHex()) // Pong\n data.write(\"8a00\".decodeHex()) // Pong\n data.write(\"8a00\".decodeHex()) // Pong\n data.write(\"8003c90700\".decodeHex()) // last 3 bytes of compressed 'Hello'\n clientReaderWithCompression.processNextFrame()\n callback.assertPong(EMPTY)\n callback.assertPong(EMPTY)\n callback.assertPong(EMPTY)\n callback.assertPong(EMPTY)\n callback.assertTextMessage(\"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":294,"symbol":"clientIncompleteMessageBodyThrows","kind":"function","lang":"kotlin","code":"@Test fun clientIncompleteMessageBodyThrows() {\n data.write(\"810548656c\".decodeHex()) // Length = 5, \"Hel\"\n assertFailsWith {\n clientReader.processNextFrame()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":301,"symbol":"clientUncompressedMessageWithCompressedFlagThrows","kind":"function","lang":"kotlin","code":"@Test fun clientUncompressedMessageWithCompressedFlagThrows() {\n data.write(\"c10548656c6c6f\".decodeHex()) // Uncompressed 'Hello', flag 1 set\n assertFailsWith {\n clientReaderWithCompression.processNextFrame()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":308,"symbol":"clientIncompleteControlFrameBodyThrows","kind":"function","lang":"kotlin","code":"@Test fun clientIncompleteControlFrameBodyThrows() {\n data.write(\"8a0548656c\".decodeHex()) // Length = 5, \"Hel\"\n assertFailsWith {\n clientReader.processNextFrame()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":315,"symbol":"serverIncompleteMessageBodyThrows","kind":"function","lang":"kotlin","code":"@Test fun serverIncompleteMessageBodyThrows() {\n data.write(\"818537fa213d7f9f4d\".decodeHex()) // Length = 5, \"Hel\"\n assertFailsWith {\n serverReader.processNextFrame()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":322,"symbol":"serverIncompleteControlFrameBodyThrows","kind":"function","lang":"kotlin","code":"@Test fun serverIncompleteControlFrameBodyThrows() {\n data.write(\"8a8537fa213d7f9f4d\".decodeHex()) // Length = 5, \"Hel\"\n assertFailsWith {\n serverReader.processNextFrame()\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":329,"symbol":"clientSimpleBinary","kind":"function","lang":"kotlin","code":"@Test fun clientSimpleBinary() {\n val bytes = binaryData(256)\n data.write(\"827E0100\".decodeHex()).write(bytes)\n clientReader.processNextFrame()\n callback.assertBinaryMessage(bytes)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":336,"symbol":"clientTwoFrameBinary","kind":"function","lang":"kotlin","code":"@Test fun clientTwoFrameBinary() {\n val bytes = binaryData(200)\n data.write(\"0264\".decodeHex()).write(bytes, 0, 100)\n data.write(\"8064\".decodeHex()).write(bytes, 100, 100)\n clientReader.processNextFrame()\n callback.assertBinaryMessage(bytes)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":344,"symbol":"twoFrameNotContinuation","kind":"function","lang":"kotlin","code":"@Test fun twoFrameNotContinuation() {\n val bytes = binaryData(200)\n data.write(\"0264\".decodeHex()).write(bytes, 0, 100)\n data.write(\"8264\".decodeHex()).write(bytes, 100, 100)\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Expected continuation opcode. Got: 2\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":356,"symbol":"emptyPingCallsCallback","kind":"function","lang":"kotlin","code":"@Test fun emptyPingCallsCallback() {\n data.write(\"8900\".decodeHex()) // Empty ping\n clientReader.processNextFrame()\n callback.assertPing(EMPTY)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":362,"symbol":"pingCallsCallback","kind":"function","lang":"kotlin","code":"@Test fun pingCallsCallback() {\n data.write(\"890548656c6c6f\".decodeHex()) // Ping with \"Hello\"\n clientReader.processNextFrame()\n callback.assertPing(\"Hello\".encodeUtf8())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":368,"symbol":"emptyCloseCallsCallback","kind":"function","lang":"kotlin","code":"@Test fun emptyCloseCallsCallback() {\n data.write(\"8800\".decodeHex()) // Empty close\n clientReader.processNextFrame()\n callback.assertClosing(1005, \"\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":374,"symbol":"closeLengthOfOneThrows","kind":"function","lang":"kotlin","code":"@Test fun closeLengthOfOneThrows() {\n data.write(\"880100\".decodeHex()) // Close with invalid 1-byte payload\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Malformed close payload length of 1.\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":384,"symbol":"closeCallsCallback","kind":"function","lang":"kotlin","code":"@Test fun closeCallsCallback() {\n data.write(\"880703e848656c6c6f\".decodeHex()) // Close with code and reason\n clientReader.processNextFrame()\n callback.assertClosing(1000, \"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":390,"symbol":"closeIncompleteCallsCallback","kind":"function","lang":"kotlin","code":"@Test fun closeIncompleteCallsCallback() {\n data.write(\"880703e948656c6c6f\".decodeHex()) // Close with code and reason\n data.close()\n clientReader.processNextFrame()\n callback.assertClosing(1001, \"Hello\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":397,"symbol":"closeOutOfRangeThrows","kind":"function","lang":"kotlin","code":"@Test fun closeOutOfRangeThrows() {\n data.write(\"88020001\".decodeHex()) // Close with code 1\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Code must be in range [1000,5000): 1\")\n }\n data.write(\"88021388\".decodeHex()) // Close with code 5000\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"Code must be in range [1000,5000): 5000\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":414,"symbol":"closeReservedSetThrows","kind":"function","lang":"kotlin","code":"@Test fun closeReservedSetThrows() {\n data.write(\"880203ec\".decodeHex()) // Close with code 1004\n data.write(\"880203ed\".decodeHex()) // Close with code 1005\n data.write(\"880203ee\".decodeHex()) // Close with code 1006\n for (i in 1015..2999) {\n data.write((\"8802\" + format(\"%04X\", i)).decodeHex()) // Close with code 'i'\n }\n var count = 0\n while (!data.exhausted()) {\n assertFailsWith {\n clientReader.processNextFrame()\n }.also { expected ->\n assertThat(expected.message!!)\n .matches(Regex(\"Code \\\\d+ is reserved and may not be used.\"))\n }\n count++\n }\n assertThat(count).isEqualTo(1988)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":434,"symbol":"clientWithCompressionCannotBeUsedAfterClose","kind":"function","lang":"kotlin","code":"@Test fun clientWithCompressionCannotBeUsedAfterClose() {\n data.write(\"c107f248cdc9c90700\".decodeHex()) // Hello\n clientReaderWithCompression.processNextFrame()\n callback.assertTextMessage(\"Hello\")\n data.write(\"c107f248cdc9c90700\".decodeHex()) // Hello\n clientReaderWithCompression.close()\n assertFailsWith {\n clientReaderWithCompression.processNextFrame()\n }.also { expected ->\n assertThat(expected.message!!).contains(\"closed\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketReaderTest.kt","line":447,"symbol":"binaryData","kind":"function","lang":"kotlin","code":"private fun binaryData(length: Int): ByteString {\n val junk = ByteArray(length)\n random.nextBytes(junk)\n return junk.toByteString()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":33,"symbol":"WebSocketRecorder","kind":"class","lang":"kotlin","code":"class WebSocketRecorder(\n private val name: String,\n) : WebSocketListener() {\n private val events = LinkedBlockingQueue()\n private var delegate: WebSocketListener? = null\n\n /** Sets a delegate for handling the next callback to this listener. Cleared after invoked. */\n fun setNextEventDelegate(delegate: WebSocketListener?) {\n this.delegate = delegate\n }\n\n override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n Platform.get().log(\"[WS $name] onOpen\", Platform.INFO, null)\n val delegate = delegate\n if (delegate != null) {\n this.delegate = null\n delegate.onOpen(webSocket, response)\n } else {\n events.add(Open(webSocket, response))\n }\n }\n\n override fun onMessage(\n webSocket: WebSocket,\n bytes: ByteString,\n ) {\n Platform.get().log(\"[WS $name] onMessage\", Platform.INFO, null)\n val delegate = delegate\n if (delegate != null) {\n this.delegate = null\n delegate.onMessage(webSocket, bytes)\n } else {\n events.add(Message(bytes = bytes))\n }\n }\n\n override fun onMessage(\n webSocket: WebSocket,\n text: String,\n ) {\n Platform.get().log(\"[WS $name] onMessage\", Platform.INFO, null)\n val"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":40,"symbol":"setNextEventDelegate","kind":"function","lang":"kotlin","doc":"Sets a delegate for handling the next callback to this listener. Cleared after invoked.","code":"fun setNextEventDelegate(delegate: WebSocketListener?) {\n this.delegate = delegate\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":44,"symbol":"onOpen","kind":"function","lang":"kotlin","code":"override fun onOpen(\n webSocket: WebSocket,\n response: Response,\n ) {\n Platform.get().log(\"[WS $name] onOpen\", Platform.INFO, null)\n val delegate = delegate\n if (delegate != null) {\n this.delegate = null\n delegate.onOpen(webSocket, response)\n } else {\n events.add(Open(webSocket, response))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":58,"symbol":"onMessage","kind":"function","lang":"kotlin","code":"override fun onMessage(\n webSocket: WebSocket,\n bytes: ByteString,\n ) {\n Platform.get().log(\"[WS $name] onMessage\", Platform.INFO, null)\n val delegate = delegate\n if (delegate != null) {\n this.delegate = null\n delegate.onMessage(webSocket, bytes)\n } else {\n events.add(Message(bytes = bytes))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":72,"symbol":"onMessage","kind":"function","lang":"kotlin","code":"override fun onMessage(\n webSocket: WebSocket,\n text: String,\n ) {\n Platform.get().log(\"[WS $name] onMessage\", Platform.INFO, null)\n val delegate = delegate\n if (delegate != null) {\n this.delegate = null\n delegate.onMessage(webSocket, text)\n } else {\n events.add(Message(string = text))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":86,"symbol":"onClosing","kind":"function","lang":"kotlin","code":"override fun onClosing(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n Platform.get().log(\"[WS $name] onClosing $code\", Platform.INFO, null)\n val delegate = delegate\n if (delegate != null) {\n this.delegate = null\n delegate.onClosing(webSocket, code, reason)\n } else {\n events.add(Closing(code, reason))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":101,"symbol":"onClosed","kind":"function","lang":"kotlin","code":"override fun onClosed(\n webSocket: WebSocket,\n code: Int,\n reason: String,\n ) {\n Platform.get().log(\"[WS $name] onClosed $code\", Platform.INFO, null)\n val delegate = delegate\n if (delegate != null) {\n this.delegate = null\n delegate.onClosed(webSocket, code, reason)\n } else {\n events.add(Closed(code, reason))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":116,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n webSocket: WebSocket,\n t: Throwable,\n response: Response?,\n ) {\n Platform.get().log(\"[WS $name] onFailure\", Platform.INFO, t)\n val delegate = delegate\n if (delegate != null) {\n this.delegate = null\n delegate.onFailure(webSocket, t, response)\n } else {\n events.add(Failure(t, response))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":131,"symbol":"nextEvent","kind":"function","lang":"kotlin","code":"private fun nextEvent(): Any =\n events.poll(10, TimeUnit.SECONDS)\n ?: throw AssertionError(\"Timed out waiting for event.\")"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":135,"symbol":"assertTextMessage","kind":"function","lang":"kotlin","code":"fun assertTextMessage(payload: String?) {\n assertThat(nextEvent()).isEqualTo(Message(string = payload))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":139,"symbol":"assertBinaryMessage","kind":"function","lang":"kotlin","code":"fun assertBinaryMessage(payload: ByteString?) {\n assertThat(nextEvent()).isEqualTo(Message(payload))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":143,"symbol":"assertPing","kind":"function","lang":"kotlin","code":"fun assertPing(payload: ByteString) {\n assertThat(nextEvent()).isEqualTo(Ping(payload))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":147,"symbol":"assertPong","kind":"function","lang":"kotlin","code":"fun assertPong(payload: ByteString) {\n assertThat(nextEvent()).isEqualTo(Pong(payload))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":151,"symbol":"assertClosing","kind":"function","lang":"kotlin","code":"fun assertClosing(\n code: Int,\n reason: String,\n ) {\n assertThat(nextEvent()).isEqualTo(Closing(code, reason))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":158,"symbol":"assertClosed","kind":"function","lang":"kotlin","code":"fun assertClosed(\n code: Int,\n reason: String,\n ) {\n assertThat(nextEvent()).isEqualTo(Closed(code, reason))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":165,"symbol":"assertExhausted","kind":"function","lang":"kotlin","code":"fun assertExhausted() {\n assertThat(events).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":169,"symbol":"assertOpen","kind":"function","lang":"kotlin","code":"fun assertOpen(): WebSocket {\n val event = nextEvent() as Open\n return event.webSocket\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":174,"symbol":"assertFailure","kind":"function","lang":"kotlin","code":"fun assertFailure(t: Throwable?) {\n val event = nextEvent() as Failure\n assertThat(event.response).isNull()\n assertThat(event.t).isSameInstanceAs(t)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":180,"symbol":"assertFailure","kind":"function","lang":"kotlin","code":"fun assertFailure(\n cls: Class?,\n vararg messages: String,\n ) {\n val event = nextEvent() as Failure\n assertThat(event.response).isNull()\n assertThat(event.t.javaClass).isEqualTo(cls)\n if (messages.isNotEmpty()) {\n assertThat(messages).contains(event.t.message)\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":192,"symbol":"assertFailure","kind":"function","lang":"kotlin","code":"fun assertFailure() {\n nextEvent() as Failure\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":196,"symbol":"assertFailure","kind":"function","lang":"kotlin","code":"fun assertFailure(\n code: Int,\n body: String?,\n cls: Class?,\n message: String?,\n ) {\n val event = nextEvent() as Failure\n assertThat(event.response!!.code).isEqualTo(code)\n if (body != null) {\n assertThat(event.responseBody).isEqualTo(body)\n }\n assertThat(event.t.javaClass).isEqualTo(cls)\n assertThat(event.t.message).isEqualTo(message)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":212,"symbol":"asFrameCallback","kind":"function","lang":"kotlin","doc":"Expose this recorder as a frame callback and shim in \"ping\" events.","code":"fun asFrameCallback() =\n object : WebSocketReader.FrameCallback {\n override fun onReadMessage(text: String) {\n events.add(Message(string = text))\n }\n\n override fun onReadMessage(bytes: ByteString) {\n events.add(Message(bytes = bytes))\n }\n\n override fun onReadPing(payload: ByteString) {\n events.add(Ping(payload))\n }\n\n override fun onReadPong(payload: ByteString) {\n events.add(Pong(payload))\n }\n\n override fun onReadClose(\n code: Int,\n reason: String,\n ) {\n events.add(Closing(code, reason))\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":214,"symbol":"onReadMessage","kind":"function","lang":"kotlin","code":"override fun onReadMessage(text: String) {\n events.add(Message(string = text))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":218,"symbol":"onReadMessage","kind":"function","lang":"kotlin","code":"override fun onReadMessage(bytes: ByteString) {\n events.add(Message(bytes = bytes))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":222,"symbol":"onReadPing","kind":"function","lang":"kotlin","code":"override fun onReadPing(payload: ByteString) {\n events.add(Ping(payload))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":226,"symbol":"onReadPong","kind":"function","lang":"kotlin","code":"override fun onReadPong(payload: ByteString) {\n events.add(Pong(payload))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":230,"symbol":"onReadClose","kind":"function","lang":"kotlin","code":"override fun onReadClose(\n code: Int,\n reason: String,\n ) {\n events.add(Closing(code, reason))\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":243,"symbol":"Failure","kind":"class","lang":"kotlin","code":"internal class Failure(\n val t: Throwable,\n val response: Response?,\n ) {\n val responseBody: String? =\n when {\n response != null && response.code != 101 -> response.body.string()\n else -> null\n }\n\n override fun toString(): String =\n when (response) {\n null -> \"Failure[$t]\"\n else -> \"Failure[$response]\"\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketRecorder.kt","line":253,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n when (response) {\n null -> \"Failure[$t]\"\n else -> \"Failure[$response]\"\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":39,"symbol":"WebSocketWriterTest","kind":"class","lang":"kotlin","code":"class WebSocketWriterTest {\n private val data = Buffer()\n private val random = Random(0)\n\n /**\n * Check all data as verified inside of the test. We do this in an AfterEachCallback so that\n * exceptions thrown from the test do not cause this check to fail.\n */\n @RegisterExtension\n val noDataLeftBehind =\n AfterEachCallback { context: ExtensionContext ->\n if (context.executionException.isPresent) return@AfterEachCallback\n assertThat(data.readByteString().hex(), \"Data not empty\")\n .isEqualTo(\"\")\n }\n\n // Mutually exclusive. Use the one corresponding to the peer whose behavior you wish to test.\n private val serverWriter =\n WebSocketWriter(\n isClient = false,\n sink = data,\n random = random,\n perMessageDeflate = false,\n noContextTakeover = false,\n minimumDeflateSize = 0L,\n )\n private val clientWriter =\n WebSocketWriter(\n isClient = true,\n sink = data,\n random = random,\n perMessageDeflate = false,\n noContextTakeover = false,\n minimumDeflateSize = 0L,\n )\n\n @Test fun serverTextMessage() {\n serverWriter.writeMessageFrame(OPCODE_TEXT, \"Hello\".encodeUtf8())\n assertData(\"810548656c6"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":75,"symbol":"serverTextMessage","kind":"function","lang":"kotlin","code":"@Test fun serverTextMessage() {\n serverWriter.writeMessageFrame(OPCODE_TEXT, \"Hello\".encodeUtf8())\n assertData(\"810548656c6c6f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":80,"symbol":"serverCompressedTextMessage","kind":"function","lang":"kotlin","code":"@Test fun serverCompressedTextMessage() {\n val serverWriter =\n WebSocketWriter(\n false,\n data,\n random,\n true,\n false,\n 0L,\n )\n serverWriter.writeMessageFrame(OPCODE_TEXT, \"Hello\".encodeUtf8())\n assertData(\"c107f248cdc9c90700\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":94,"symbol":"serverSmallBufferedPayloadWrittenAsOneFrame","kind":"function","lang":"kotlin","code":"@Test fun serverSmallBufferedPayloadWrittenAsOneFrame() {\n val length = 5\n val payload: ByteString = (binaryData(length))\n serverWriter.writeMessageFrame(OPCODE_TEXT, payload)\n assertData(\"8105\")\n assertData(payload)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":102,"symbol":"serverLargeBufferedPayloadWrittenAsOneFrame","kind":"function","lang":"kotlin","code":"@Test fun serverLargeBufferedPayloadWrittenAsOneFrame() {\n val length = 12345\n val payload: ByteString = (binaryData(length))\n serverWriter.writeMessageFrame(OPCODE_TEXT, payload)\n assertData(\"817e\")\n assertData(format(\"%04x\", length))\n assertData(payload)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":111,"symbol":"clientTextMessage","kind":"function","lang":"kotlin","code":"@Test fun clientTextMessage() {\n clientWriter.writeMessageFrame(OPCODE_TEXT, \"Hello\".encodeUtf8())\n assertData(\"818560b420bb28d14cd70f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":116,"symbol":"clientCompressedTextMessage","kind":"function","lang":"kotlin","code":"@Test fun clientCompressedTextMessage() {\n val clientWriter =\n WebSocketWriter(\n false,\n data,\n random,\n true,\n false,\n 0L,\n )\n clientWriter.writeMessageFrame(OPCODE_TEXT, \"Hello\".encodeUtf8())\n assertData(\"c107f248cdc9c90700\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":130,"symbol":"serverBinaryMessage","kind":"function","lang":"kotlin","code":"@Test fun serverBinaryMessage() {\n val payload =\n \"\"\"\n 60b420bb3851d9d47acb933dbe70399bf6c92da33af01d4fb770e98c0325f41d3ebaf8986da712c82bcd4d554bf0b5\n 4023c2\n \"\"\".decodeHex(ignoreWhitespace = true)\n serverWriter.writeMessageFrame(OPCODE_BINARY, payload)\n assertData(\"8232\")\n assertData(payload)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":141,"symbol":"serverMessageLengthShort","kind":"function","lang":"kotlin","code":"@Test fun serverMessageLengthShort() {\n // Create a payload which will overflow the normal payload byte size.\n val payload = Buffer()\n while (payload.completeSegmentByteCount() <= PAYLOAD_BYTE_MAX) {\n payload.writeByte('0'.code)\n }\n serverWriter.writeMessageFrame(OPCODE_BINARY, payload.snapshot())\n\n // Write directly to the unbuffered sink. This ensures it will become single frame.\n assertData(\"827e\") // 'e' == 4-byte follow-up length.\n assertData(format(\"%04X\", payload.completeSegmentByteCount()))\n assertData(payload.readByteString())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":155,"symbol":"serverMessageLengthLong","kind":"function","lang":"kotlin","code":"@Test fun serverMessageLengthLong() {\n // Create a payload which will overflow the normal and short payload byte size.\n val payload = Buffer()\n while (payload.completeSegmentByteCount() <= PAYLOAD_SHORT_MAX) {\n payload.writeByte('0'.code)\n }\n serverWriter.writeMessageFrame(OPCODE_BINARY, payload.snapshot())\n\n // Write directly to the unbuffered sink. This ensures it will become single frame.\n assertData(\"827f\") // 'f' == 16-byte follow-up length.\n assertData(format(\"%016X\", payload.size))\n assertData(payload.readByteString())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":169,"symbol":"clientBinary","kind":"function","lang":"kotlin","code":"@Test fun clientBinary() {\n val payload =\n \"\"\"\n 60b420bb3851d9d47acb933dbe70399bf6c92da33af01d4fb770e98c0325f41d3ebaf8986da712c82bcd4d554bf0b5\n 4023c2\n \"\"\".decodeHex(ignoreWhitespace = true)\n clientWriter.writeMessageFrame(OPCODE_BINARY, payload)\n assertData(\"82b2\")\n assertData(\"60b420bb\")\n assertData(\n \"0000000058e5f96f1a7fb386dec41920967d0d185a443df4d7c4c9376391d4a65e0ed8230d1332734b796dee2\" +\n \"b4495fb4376\",\n )\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":184,"symbol":"serverEmptyClose","kind":"function","lang":"kotlin","code":"@Test fun serverEmptyClose() {\n serverWriter.writeClose(0, null)\n assertData(\"8800\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":189,"symbol":"serverCloseWithCode","kind":"function","lang":"kotlin","code":"@Test fun serverCloseWithCode() {\n serverWriter.writeClose(1001, null)\n assertData(\"880203e9\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":194,"symbol":"serverCloseWithCodeAndReason","kind":"function","lang":"kotlin","code":"@Test fun serverCloseWithCodeAndReason() {\n serverWriter.writeClose(1001, \"Hello\".encodeUtf8())\n assertData(\"880703e948656c6c6f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":199,"symbol":"clientEmptyClose","kind":"function","lang":"kotlin","code":"@Test fun clientEmptyClose() {\n clientWriter.writeClose(0, null)\n assertData(\"888060b420bb\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":204,"symbol":"clientCloseWithCode","kind":"function","lang":"kotlin","code":"@Test fun clientCloseWithCode() {\n clientWriter.writeClose(1001, null)\n assertData(\"888260b420bb635d\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":209,"symbol":"clientCloseWithCodeAndReason","kind":"function","lang":"kotlin","code":"@Test fun clientCloseWithCodeAndReason() {\n clientWriter.writeClose(1001, \"Hello\".encodeUtf8())\n assertData(\"888760b420bb635d68de0cd84f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":214,"symbol":"closeWithOnlyReasonThrows","kind":"function","lang":"kotlin","code":"@Test fun closeWithOnlyReasonThrows() {\n clientWriter.writeClose(0, \"Hello\".encodeUtf8())\n assertData(\"888760b420bb60b468de0cd84f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":219,"symbol":"closeCodeOutOfRangeThrows","kind":"function","lang":"kotlin","code":"@Test fun closeCodeOutOfRangeThrows() {\n assertFailsWith {\n clientWriter.writeClose(98724976, \"Hello\".encodeUtf8())\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Code must be in range [1000,5000): 98724976\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":227,"symbol":"closeReservedThrows","kind":"function","lang":"kotlin","code":"@Test fun closeReservedThrows() {\n assertFailsWith {\n clientWriter.writeClose(1005, \"Hello\".encodeUtf8())\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"Code 1005 is reserved and may not be used.\")\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":235,"symbol":"serverEmptyPing","kind":"function","lang":"kotlin","code":"@Test fun serverEmptyPing() {\n serverWriter.writePing(EMPTY)\n assertData(\"8900\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":240,"symbol":"clientEmptyPing","kind":"function","lang":"kotlin","code":"@Test fun clientEmptyPing() {\n clientWriter.writePing(EMPTY)\n assertData(\"898060b420bb\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":245,"symbol":"serverPingWithPayload","kind":"function","lang":"kotlin","code":"@Test fun serverPingWithPayload() {\n serverWriter.writePing(\"Hello\".encodeUtf8())\n assertData(\"890548656c6c6f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":250,"symbol":"clientPingWithPayload","kind":"function","lang":"kotlin","code":"@Test fun clientPingWithPayload() {\n clientWriter.writePing(\"Hello\".encodeUtf8())\n assertData(\"898560b420bb28d14cd70f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":255,"symbol":"serverEmptyPong","kind":"function","lang":"kotlin","code":"@Test fun serverEmptyPong() {\n serverWriter.writePong(EMPTY)\n assertData(\"8a00\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":260,"symbol":"clientEmptyPong","kind":"function","lang":"kotlin","code":"@Test fun clientEmptyPong() {\n clientWriter.writePong(EMPTY)\n assertData(\"8a8060b420bb\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":265,"symbol":"serverPongWithPayload","kind":"function","lang":"kotlin","code":"@Test fun serverPongWithPayload() {\n serverWriter.writePong(\"Hello\".encodeUtf8())\n assertData(\"8a0548656c6c6f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":270,"symbol":"clientPongWithPayload","kind":"function","lang":"kotlin","code":"@Test fun clientPongWithPayload() {\n clientWriter.writePong(\"Hello\".encodeUtf8())\n assertData(\"8a8560b420bb28d14cd70f\")\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":275,"symbol":"pingTooLongThrows","kind":"function","lang":"kotlin","code":"@Test fun pingTooLongThrows() {\n assertFailsWith {\n serverWriter.writePing(binaryData(1000))\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"Payload size must be less than or equal to 125\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":285,"symbol":"pongTooLongThrows","kind":"function","lang":"kotlin","code":"@Test fun pongTooLongThrows() {\n assertFailsWith {\n serverWriter.writePong((binaryData(1000)))\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"Payload size must be less than or equal to 125\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":295,"symbol":"closeTooLongThrows","kind":"function","lang":"kotlin","code":"@Test fun closeTooLongThrows() {\n assertFailsWith {\n val longReason: ByteString = repeat('X', 124).encodeUtf8()\n serverWriter.writeClose(1000, longReason)\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\n \"Payload size must be less than or equal to 125\",\n )\n }\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":306,"symbol":"assertData","kind":"function","lang":"kotlin","code":"private fun assertData(hex: String) {\n assertData(hex.decodeHex())\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":310,"symbol":"assertData","kind":"function","lang":"kotlin","code":"private fun assertData(expected: ByteString) {\n val actual = data.readByteString(Math.min(expected.size.toLong(), data.size))\n assertThat(actual).isEqualTo(expected)\n }"} {"repo":"okhttp","file":"okhttp/src/jvmTest/kotlin/okhttp3/internal/ws/WebSocketWriterTest.kt","line":316,"symbol":"binaryData","kind":"function","lang":"kotlin","code":"private fun binaryData(length: Int): ByteString {\n val junk = ByteArray(length)\n Random(0).nextBytes(junk)\n return junk.toByteString()\n }"} {"repo":"okhttp","file":"okhttp/src/main/resources/META-INF/native-image/okhttp/okhttp/native-image.properties","line":1,"symbol":"Args","kind":"field","lang":"properties","code":"Args = -H:+AddAllCharsets --enable-http --enable-https --features=okhttp3.internal.graal.OkHttpFeature"} {"repo":"okhttp","file":"okhttp-brotli/src/main/kotlin/okhttp3/brotli/Brotli.kt","line":24,"symbol":"Brotli","kind":"object","lang":"kotlin","code":"object Brotli : CompressionInterceptor.DecompressionAlgorithm {\n override val encoding: String get() = \"br\"\n\n override fun decompress(compressedSource: BufferedSource): Source = BrotliInputStream(compressedSource.inputStream()).source()\n}"} {"repo":"okhttp","file":"okhttp-brotli/src/main/kotlin/okhttp3/brotli/Brotli.kt","line":27,"symbol":"decompress","kind":"function","lang":"kotlin","code":"override fun decompress(compressedSource: BufferedSource): Source = BrotliInputStream(compressedSource.inputStream()).source()"} {"repo":"okhttp","file":"okhttp-brotli/src/main/kotlin/okhttp3/brotli/BrotliInterceptor.kt","line":27,"symbol":"BrotliInterceptor","kind":"object","lang":"kotlin","doc":"Transparent Brotli response support. Adds Accept-Encoding: br to request and checks (and strips) for Content-Encoding: br in responses. n.b. this replaces the transparent gzip compression in BridgeInterceptor.","code":"object BrotliInterceptor : CompressionInterceptor(Brotli, Gzip)"} {"repo":"okhttp","file":"okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt","line":42,"symbol":"BrotliInterceptorTest","kind":"class","lang":"kotlin","code":"class BrotliInterceptorTest {\n val brotliInterceptor = CompressionInterceptor(Brotli, Gzip)\n\n @Test\n fun testUncompressBrotli() {\n val s =\n \"1bce00009c05ceb9f028d14e416230f718960a537b0922d2f7b6adef56532c08dff44551516690131494db\" +\n \"6021c7e3616c82c1bc2416abb919aaa06e8d30d82cc2981c2f5c900bfb8ee29d5c03deb1c0dacff80e\" +\n \"abe82ba64ed250a497162006824684db917963ecebe041b352a3e62d629cc97b95cac24265b175171e\" +\n \"5cb384cd0912aeb5b5dd9555f2dd1a9b20688201\"\n\n val response =\n response(\"https://httpbin.org/brotli\", s.decodeHex()) {\n header(\"Content-Encoding\", \"br\")\n }\n\n val uncompressed = brotliInterceptor.decompress(response)\n\n val responseString = uncompressed.body.string()\n assertThat(responseString).contains(\"\\\"brotli\\\": true,\")\n assertThat(responseString).contains(\"\\\"Accept-Encoding\\\": \\\"br\\\"\")\n }\n\n @Test\n fun testUncompressGzip() {\n val s =\n \"1f8b0800968f215d02ff558ec10e82301044ef7c45b3e75269d0c478e340e4a426e007086c4a636c9bb65e\" +\n \"24fcbb5b484c3cec61deccecee9c3106eaa39dc3114e2cfa377296d8848f117d20369324500d03ba98\" +\n \"d766b0a3368a0ce83d4f55581b14696c88894f31ba5e1b61bdfa79f7803eaf149a35619f29b3db0b29\""} {"repo":"okhttp","file":"okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt","line":45,"symbol":"testUncompressBrotli","kind":"function","lang":"kotlin","code":"@Test\n fun testUncompressBrotli() {\n val s =\n \"1bce00009c05ceb9f028d14e416230f718960a537b0922d2f7b6adef56532c08dff44551516690131494db\" +\n \"6021c7e3616c82c1bc2416abb919aaa06e8d30d82cc2981c2f5c900bfb8ee29d5c03deb1c0dacff80e\" +\n \"abe82ba64ed250a497162006824684db917963ecebe041b352a3e62d629cc97b95cac24265b175171e\" +\n \"5cb384cd0912aeb5b5dd9555f2dd1a9b20688201\"\n\n val response =\n response(\"https://httpbin.org/brotli\", s.decodeHex()) {\n header(\"Content-Encoding\", \"br\")\n }\n\n val uncompressed = brotliInterceptor.decompress(response)\n\n val responseString = uncompressed.body.string()\n assertThat(responseString).contains(\"\\\"brotli\\\": true,\")\n assertThat(responseString).contains(\"\\\"Accept-Encoding\\\": \\\"br\\\"\")\n }\n\n @Test\n fun testUncompressGzip() {\n val s =\n \"1f8b0800968f215d02ff558ec10e82301044ef7c45b3e75269d0c478e340e4a426e007086c4a636c9bb65e\" +\n \"24fcbb5b484c3cec61deccecee9c3106eaa39dc3114e2cfa377296d8848f117d20369324500d03ba98\" +\n \"d766b0a3368a0ce83d4f55581b14696c88894f31ba5e1b61bdfa79f7803eaf149a35619f29b3db0b29\" +\n \"8abcbd54b7b6b97640c965bbfec238d9f4109ceb6edb01d66ba54d6247296441531e445970f627215b\" "} {"repo":"okhttp","file":"okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt","line":96,"symbol":"testFailsUncompress","kind":"function","lang":"kotlin","code":"@Test\n fun testFailsUncompress() {\n val response =\n response(\"https://httpbin.org/brotli\", \"bb919aaa06e8\".decodeHex()) {\n header(\"Content-Encoding\", \"br\")\n }\n\n assertFailsWith {\n val failingResponse = brotliInterceptor.decompress(response)\n failingResponse.body.string()\n }.also { ioe ->\n assertThat(ioe).hasMessage(\"Brotli stream decoding failed\")\n assertThat(ioe.cause?.javaClass?.simpleName).isEqualTo(\"BrotliRuntimeException\")\n }\n }"} {"repo":"okhttp","file":"okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt","line":112,"symbol":"testSkipUncompressNoContentResponse","kind":"function","lang":"kotlin","code":"@Test\n fun testSkipUncompressNoContentResponse() {\n val response =\n response(\"https://httpbin.org/brotli\", EMPTY) {\n header(\"Content-Encoding\", \"br\")\n code(204)\n message(\"NO CONTENT\")\n }\n\n val same = brotliInterceptor.decompress(response)\n\n val responseString = same.body.string()\n assertThat(responseString).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp-brotli/src/test/java/okhttp3/brotli/BrotliInterceptorTest.kt","line":127,"symbol":"response","kind":"function","lang":"kotlin","code":"private fun response(\n url: String,\n bodyHex: ByteString,\n fn: Response.Builder.() -> Unit = {},\n ): Response =\n Response\n .Builder()\n .body(bodyHex.toResponseBody(\"text/plain\".toMediaType()))\n .code(200)\n .message(\"OK\")\n .request(Request.Builder().url(url).build())\n .protocol(Protocol.HTTP_2)\n .apply(fn)\n .build()"} {"repo":"okhttp","file":"okhttp-brotli/src/test/java/okhttp3/brotli/BrotliTestMain.kt","line":21,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n val client =\n OkHttpClient\n .Builder()\n .addInterceptor(BrotliInterceptor)\n .build()\n\n sendRequest(\"https://httpbin.org/brotli\", client)\n sendRequest(\"https://httpbin.org/gzip\", client)\n}"} {"repo":"okhttp","file":"okhttp-brotli/src/test/java/okhttp3/brotli/BrotliTestMain.kt","line":32,"symbol":"sendRequest","kind":"function","lang":"kotlin","code":"private fun sendRequest(\n url: String,\n client: OkHttpClient,\n) {\n val req = Request.Builder().url(url).build()\n\n client.newCall(req).execute().use {\n println(it.body.string())\n }\n}"} {"repo":"okhttp","file":"okhttp-coroutines/src/main/kotlin/okhttp3/coroutines/ExecuteAsync.kt","line":28,"symbol":"executeAsync","kind":"function","lang":"kotlin","code":"suspend fun Call.executeAsync(): Response =\n suspendCancellableCoroutine { continuation ->\n continuation.invokeOnCancellation {\n this.cancel()\n }\n this.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n continuation.resumeWithException(e)\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n continuation.resume(response) { _, value, _ ->\n value.closeQuietly()\n }\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/main/kotlin/okhttp3/coroutines/ExecuteAsync.kt","line":35,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n continuation.resumeWithException(e)\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/main/kotlin/okhttp3/coroutines/ExecuteAsync.kt","line":42,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n continuation.resume(response) { _, value, _ ->\n value.closeQuietly()\n }\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":54,"symbol":"ExecuteAsyncTest","kind":"class","lang":"kotlin","code":"class ExecuteAsyncTest {\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private var client = clientTestRule.newClientBuilder().build()\n\n @StartStop\n private val server = MockWebServer()\n\n val request by lazy { Request(server.url(\"/\")) }\n\n @Test\n fun suspendCall() {\n runTest {\n server.enqueue(MockResponse(body = \"abc\"))\n\n val call = client.newCall(request)\n\n call.executeAsync().use {\n withContext(Dispatchers.IO) {\n assertThat(it.body.string()).isEqualTo(\"abc\")\n }\n }\n }\n }\n\n @Test\n fun timeoutCall() {\n runTest {\n server.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(5, TimeUnit.SECONDS)\n .body(\"abc\")\n .build(),\n )\n\n val call = client.newCall(request)\n\n assertFailsWith {\n withTimeout(1.seconds) {\n call.executeAsync().use {\n withContext(Dispatchers.IO) {\n it.body.string()\n }\n fail(\"No expected to get response\")\n }\n }\n }\n\n assertThat(call.isCanceled()).isTrue()\n }\n }\n\n @Test\n fun cancelledCall() {\n runTest {\n serv"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":65,"symbol":"suspendCall","kind":"function","lang":"kotlin","code":"@Test\n fun suspendCall() {\n runTest {\n server.enqueue(MockResponse(body = \"abc\"))\n\n val call = client.newCall(request)\n\n call.executeAsync().use {\n withContext(Dispatchers.IO) {\n assertThat(it.body.string()).isEqualTo(\"abc\")\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":80,"symbol":"timeoutCall","kind":"function","lang":"kotlin","code":"@Test\n fun timeoutCall() {\n runTest {\n server.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(5, TimeUnit.SECONDS)\n .body(\"abc\")\n .build(),\n )\n\n val call = client.newCall(request)\n\n assertFailsWith {\n withTimeout(1.seconds) {\n call.executeAsync().use {\n withContext(Dispatchers.IO) {\n it.body.string()\n }\n fail(\"No expected to get response\")\n }\n }\n }\n\n assertThat(call.isCanceled()).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":108,"symbol":"cancelledCall","kind":"function","lang":"kotlin","code":"@Test\n fun cancelledCall() {\n runTest {\n server.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(5, TimeUnit.SECONDS)\n .body(\"abc\")\n .build(),\n )\n\n val call = client.newCall(request)\n\n assertFailsWith {\n call.executeAsync().use {\n call.cancel()\n withContext(Dispatchers.IO) {\n it.body.string()\n }\n }\n }\n\n assertThat(call.isCanceled()).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":134,"symbol":"failedCall","kind":"function","lang":"kotlin","code":"@Test\n fun failedCall() {\n runTest {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"abc\")\n .onResponseStart(SocketEffect.ShutdownConnection)\n .build(),\n )\n\n val call = client.newCall(request)\n\n assertFailsWith {\n call.executeAsync().use {\n withContext(Dispatchers.IO) {\n it.body.string()\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":157,"symbol":"responseClosedIfCoroutineCanceled","kind":"function","lang":"kotlin","code":"@Test\n fun responseClosedIfCoroutineCanceled() {\n runTest {\n val call = ClosableCall()\n\n supervisorScope {\n assertFailsWith {\n coroutineScope {\n call.afterCallbackOnResponse = {\n coroutineContext.job.cancel()\n }\n call.executeAsync()\n }\n }\n }\n\n assertThat(call.canceled).isTrue()\n assertThat(call.responseClosed).isTrue()\n }\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":179,"symbol":"ClosableCall","kind":"class","lang":"kotlin","doc":"A call that keeps track of whether its response body is closed.","code":"private class ClosableCall : FailingCall() {\n private val response =\n Response\n .Builder()\n .request(Request(\"https://example.com/\".toHttpUrl()))\n .protocol(Protocol.HTTP_1_1)\n .message(\"OK\")\n .code(200)\n .body(\n object : ResponseBody() {\n override fun contentType() = null\n\n override fun contentLength() = -1L\n\n override fun source() =\n object : ForwardingSource(Buffer()) {\n override fun close() {\n responseClosed = true\n }\n }.buffer()\n },\n ).build()\n\n var responseClosed = false\n var canceled = false\n var afterCallbackOnResponse: () -> Unit = {}\n\n override fun cancel() {\n canceled = true\n }\n\n override fun enqueue(responseCallback: Callback) {\n responseCallback.onResponse(this, response)\n afterCallbackOnResponse()\n }\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":189,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = null"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":191,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength() = -1L"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":193,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source() =\n object : ForwardingSource(Buffer()) {\n override fun close() {\n responseClosed = true\n }\n }.buffer()"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":195,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n responseClosed = true\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":206,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n canceled = true\n }"} {"repo":"okhttp","file":"okhttp-coroutines/src/test/kotlin/okhttp3/coroutines/ExecuteAsyncTest.kt","line":210,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(responseCallback: Callback) {\n responseCallback.onResponse(this, response)\n afterCallbackOnResponse()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/BootstrapDns.kt","line":27,"symbol":"BootstrapDns","kind":"class","lang":"kotlin","doc":"Internal Bootstrap DNS implementation for handling initial connection to DNS over HTTPS server. Returns hardcoded results for the known host.","code":"internal class BootstrapDns(\n private val dnsHostname: String,\n private val dnsServers: List,\n) : Dns {\n @Throws(UnknownHostException::class)\n override fun lookup(hostname: String): List {\n if (this.dnsHostname != hostname) {\n throw UnknownHostException(\n \"BootstrapDns called for $hostname instead of $dnsHostname\",\n )\n }\n\n return dnsServers\n }\n}"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/BootstrapDns.kt","line":31,"symbol":"lookup","kind":"function","lang":"kotlin","code":"@Throws(UnknownHostException::class)\n override fun lookup(hostname: String): List {\n if (this.dnsHostname != hostname) {\n throw UnknownHostException(\n \"BootstrapDns called for $hostname instead of $dnsHostname\",\n )\n }\n\n return dnsServers\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":42,"symbol":"DnsOverHttps","kind":"class","lang":"kotlin","doc":"> using either the HTTP GET or POST method and the other requirements > of this section. The DNS API server defines the URI used by the > request through the use of a URI Template. [doh_spec]: https://tools.ietf.org/html/draft-ietf-doh-dns-over-https-13","code":"class DnsOverHttps internal constructor(\n private val taskRunner: TaskRunner,\n @get:JvmName(\"client\") val client: OkHttpClient,\n @get:JvmName(\"url\") val url: HttpUrl,\n @get:JvmName(\"cache\") val cache: DnsCache,\n @get:JvmName(\"includeIPv6\") val includeIPv6: Boolean,\n @get:JvmName(\"includeServiceMetadata\") val includeServiceMetadata: Boolean,\n @get:JvmName(\"post\") val post: Boolean,\n @get:JvmName(\"resolvePrivateAddresses\") val resolvePrivateAddresses: Boolean,\n @get:JvmName(\"resolvePublicAddresses\") val resolvePublicAddresses: Boolean,\n) : Dns {\n private val queryFactory =\n cache.`-delegate`.wrap(\n DnsOverHttpsQuery.Factory(\n taskRunner = taskRunner,\n resolvePrivateAddresses = resolvePrivateAddresses,\n resolvePublicAddresses = resolvePublicAddresses,\n client = client,\n dnsUrl = url,\n post = post,\n ),\n )\n\n override fun newCall(request: Dns.Request): Dns.Call =\n StateMachineDnsCall(\n taskRunner = taskRunner,\n request = request,\n queryFactory = queryFactory,\n includeIPv6 = includeIPv6,\n includeServiceMetadata = includeServiceMetadata,\n )\n\n @Throws(UnknownHostException::class)\n override "} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":65,"symbol":"newCall","kind":"function","lang":"kotlin","code":"override fun newCall(request: Dns.Request): Dns.Call =\n StateMachineDnsCall(\n taskRunner = taskRunner,\n request = request,\n queryFactory = queryFactory,\n includeIPv6 = includeIPv6,\n includeServiceMetadata = includeServiceMetadata,\n )"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":74,"symbol":"lookup","kind":"function","lang":"kotlin","code":"@Throws(UnknownHostException::class)\n override fun lookup(hostname: String): List {\n val withoutServiceMetadata =\n DnsOverHttps(\n taskRunner = taskRunner,\n client = client,\n url = url,\n cache = cache,\n includeIPv6 = includeIPv6,\n includeServiceMetadata = false,\n post = post,\n resolvePrivateAddresses = resolvePrivateAddresses,\n resolvePublicAddresses = resolvePublicAddresses,\n )\n val call = withoutServiceMetadata.newCall(Dns.Request(hostname))\n val records = call.execute()\n return records\n .filterIsInstance()\n .map { it.address }\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":95,"symbol":"Builder","kind":"class","lang":"kotlin","code":"class Builder {\n internal val taskRunner = TaskRunner.INSTANCE\n internal var client: OkHttpClient? = null\n internal var url: HttpUrl? = null\n internal var cache: DnsCache = DnsCache()\n internal var includeIPv6 = true\n internal var includeServiceMetadata = true\n internal var post = false\n internal var systemDns = Dns.SYSTEM\n internal var bootstrapDnsHosts: List? = null\n internal var resolvePrivateAddresses = false\n internal var resolvePublicAddresses = true\n\n fun build(): DnsOverHttps {\n val client = this.client ?: throw NullPointerException(\"client not set\")\n return DnsOverHttps(\n taskRunner = taskRunner,\n client = client.newBuilder().dns(buildBootstrapClient(this)).build(),\n url = checkNotNull(url) { \"url not set\" },\n cache = cache,\n includeIPv6 = includeIPv6,\n includeServiceMetadata = includeServiceMetadata,\n post = post,\n resolvePrivateAddresses = resolvePrivateAddresses,\n resolvePublicAddresses = resolvePublicAddresses,\n )\n }\n\n fun client(client: OkHttpClient) =\n apply {\n this.client = client\n }\n\n fun url(url: HttpUrl) =\n "} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":108,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): DnsOverHttps {\n val client = this.client ?: throw NullPointerException(\"client not set\")\n return DnsOverHttps(\n taskRunner = taskRunner,\n client = client.newBuilder().dns(buildBootstrapClient(this)).build(),\n url = checkNotNull(url) { \"url not set\" },\n cache = cache,\n includeIPv6 = includeIPv6,\n includeServiceMetadata = includeServiceMetadata,\n post = post,\n resolvePrivateAddresses = resolvePrivateAddresses,\n resolvePublicAddresses = resolvePublicAddresses,\n )\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":123,"symbol":"client","kind":"function","lang":"kotlin","code":"fun client(client: OkHttpClient) =\n apply {\n this.client = client\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":128,"symbol":"url","kind":"function","lang":"kotlin","code":"fun url(url: HttpUrl) =\n apply {\n this.url = url\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":133,"symbol":"cache","kind":"function","lang":"kotlin","code":"fun cache(cache: DnsCache) =\n apply {\n this.cache = cache\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":142,"symbol":"includeServiceMetadata","kind":"function","lang":"kotlin","doc":"True to request [`HTTPS` DNS records](https://datatracker.ietf.org/doc/rfc9460/), which are necessary for [Encrypted Client Hello (ECH)](https://datatracker.ietf.org/doc/rfc9849/).","code":"fun includeServiceMetadata(includeServiceMetadata: Boolean) =\n apply {\n this.includeServiceMetadata = includeServiceMetadata\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":147,"symbol":"includeIPv6","kind":"function","lang":"kotlin","code":"fun includeIPv6(includeIPv6: Boolean) =\n apply {\n this.includeIPv6 = includeIPv6\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":152,"symbol":"post","kind":"function","lang":"kotlin","code":"fun post(post: Boolean) =\n apply {\n this.post = post\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":157,"symbol":"resolvePrivateAddresses","kind":"function","lang":"kotlin","code":"fun resolvePrivateAddresses(resolvePrivateAddresses: Boolean) =\n apply {\n this.resolvePrivateAddresses = resolvePrivateAddresses\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":162,"symbol":"resolvePublicAddresses","kind":"function","lang":"kotlin","code":"fun resolvePublicAddresses(resolvePublicAddresses: Boolean) =\n apply {\n this.resolvePublicAddresses = resolvePublicAddresses\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":167,"symbol":"bootstrapDnsHosts","kind":"function","lang":"kotlin","code":"fun bootstrapDnsHosts(bootstrapDnsHosts: List?) =\n apply {\n this.bootstrapDnsHosts = bootstrapDnsHosts\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":172,"symbol":"bootstrapDnsHosts","kind":"function","lang":"kotlin","code":"fun bootstrapDnsHosts(vararg bootstrapDnsHosts: InetAddress): Builder = bootstrapDnsHosts(bootstrapDnsHosts.toList())"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":174,"symbol":"systemDns","kind":"function","lang":"kotlin","code":"fun systemDns(systemDns: Dns) =\n apply {\n this.systemDns = systemDns\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":184,"symbol":"buildBootstrapClient","kind":"function","lang":"kotlin","code":"private fun buildBootstrapClient(builder: Builder): Dns {\n val hosts = builder.bootstrapDnsHosts\n\n return if (hosts != null) {\n BootstrapDns(builder.url!!.host, hosts)\n } else {\n builder.systemDns\n }\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/DnsOverHttps.kt","line":194,"symbol":"isPrivateHost","kind":"function","lang":"kotlin","code":"internal fun isPrivateHost(host: String): Boolean = PublicSuffixDatabase.get().getEffectiveTldPlusOne(host) == null"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":45,"symbol":"DnsOverHttpsQuery","kind":"class","lang":"kotlin","code":"@OkHttpInternalApi\ninternal class DnsOverHttpsQuery(\n private val call: Call,\n) : DnsQuery {\n override fun enqueue(callback: DnsQuery.Callback) {\n call.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n callback.onFailure(e)\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val dnsMessage =\n try {\n decodeResponse(response)\n } catch (e: IOException) {\n return callback.onFailure(e)\n }\n\n callback.onResponse(dnsMessage)\n }\n },\n )\n }\n\n override fun cancel() {\n call.cancel()\n }\n\n class Factory(\n private val taskRunner: TaskRunner,\n private val resolvePrivateAddresses: Boolean,\n private val resolvePublicAddresses: Boolean,\n private val client: OkHttpClient,\n private val dnsUrl: HttpUrl,\n private val post: Boolean,\n ) : DnsQuery.Factory {\n override fun newQuery(question: Question): DnsQuery {\n val overrideQuery = overrideQuery(question)\n if (overrideQuery != null) {\n return overrideQuery\n }\n\n val "} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":49,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(callback: DnsQuery.Callback) {\n call.enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n callback.onFailure(e)\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val dnsMessage =\n try {\n decodeResponse(response)\n } catch (e: IOException) {\n return callback.onFailure(e)\n }\n\n callback.onResponse(dnsMessage)\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":52,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n callback.onFailure(e)\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":59,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n val dnsMessage =\n try {\n decodeResponse(response)\n } catch (e: IOException) {\n return callback.onFailure(e)\n }\n\n callback.onResponse(dnsMessage)\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":76,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n call.cancel()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":80,"symbol":"Factory","kind":"class","lang":"kotlin","code":"class Factory(\n private val taskRunner: TaskRunner,\n private val resolvePrivateAddresses: Boolean,\n private val resolvePublicAddresses: Boolean,\n private val client: OkHttpClient,\n private val dnsUrl: HttpUrl,\n private val post: Boolean,\n ) : DnsQuery.Factory {\n override fun newQuery(question: Question): DnsQuery {\n val overrideQuery = overrideQuery(question)\n if (overrideQuery != null) {\n return overrideQuery\n }\n\n val dnsMessage = DnsMessage.query(question)\n return DnsOverHttpsQuery(\n call =\n client.newCall(\n request =\n Request\n .Builder()\n .header(\"Accept\", DNS_MESSAGE.toString())\n .apply {\n if (post) {\n url(dnsUrl)\n cacheUrlOverride(\n dnsUrl\n .newBuilder()\n .addQueryParameter(\"hostname\", question.name)\n .addQueryParameter(\"type\", question.type.toString())\n .build(),\n )\n post(dnsMessage.toRequestBody())\n } else {\n "} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":88,"symbol":"newQuery","kind":"function","lang":"kotlin","code":"override fun newQuery(question: Question): DnsQuery {\n val overrideQuery = overrideQuery(question)\n if (overrideQuery != null) {\n return overrideQuery\n }\n\n val dnsMessage = DnsMessage.query(question)\n return DnsOverHttpsQuery(\n call =\n client.newCall(\n request =\n Request\n .Builder()\n .header(\"Accept\", DNS_MESSAGE.toString())\n .apply {\n if (post) {\n url(dnsUrl)\n cacheUrlOverride(\n dnsUrl\n .newBuilder()\n .addQueryParameter(\"hostname\", question.name)\n .addQueryParameter(\"type\", question.type.toString())\n .build(),\n )\n post(dnsMessage.toRequestBody())\n } else {\n val requestUrl =\n dnsUrl\n .newBuilder()\n .addQueryParameter(\"dns\", dnsMessage.asQueryParameter())\n .build()\n url(requestUrl)\n }\n }.buil"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":127,"symbol":"overrideQuery","kind":"function","lang":"kotlin","doc":"Returns an alternate query for [question] if the [DnsOverHttpsQuery] should not be used.","code":"private fun overrideQuery(question: Question): DnsQuery? {\n // Don't load the public suffix list unless necessary.\n if (resolvePrivateAddresses && resolvePublicAddresses) return null\n\n val privateHost = isPrivateHost(question.name)\n\n val resolveUnsupportedMessage =\n when {\n privateHost && !resolvePrivateAddresses -> \"private hosts not resolved\"\n !privateHost && !resolvePublicAddresses -> \"public hosts not resolved\"\n else -> return null\n }\n\n return ResolveUnsupportedQuery(\n hostname = question.name,\n message = resolveUnsupportedMessage,\n )\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":146,"symbol":"ResolveUnsupportedQuery","kind":"class","lang":"kotlin","code":"private inner class ResolveUnsupportedQuery(\n private val hostname: String,\n private val message: String,\n ) : DnsQuery {\n override fun enqueue(callback: DnsQuery.Callback) {\n taskRunner.newQueue().execute(\"$hostname dns\") {\n callback.onFailure(UnknownHostException(message))\n }\n }\n\n override fun cancel() {\n }\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":150,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(callback: DnsQuery.Callback) {\n taskRunner.newQueue().execute(\"$hostname dns\") {\n callback.onFailure(UnknownHostException(message))\n }\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":156,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":162,"symbol":"asQueryParameter","kind":"function","lang":"kotlin","code":"internal fun DnsMessage.asQueryParameter(): String {\n val buffer = Buffer()\n DnsMessageWriter(buffer).write(this@asQueryParameter)\n return buffer.readByteString().base64Url(includePadding = false)\n}"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":169,"symbol":"toRequestBody","kind":"function","lang":"kotlin","doc":"Cloudflare doesn't support chunked encoding.","code":"internal fun DnsMessage.toRequestBody(): RequestBody =\n Buffer().also { DnsMessageWriter(it).write(this) }.readByteString().toRequestBody(DNS_MESSAGE)"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/main/kotlin/okhttp3/dnsoverhttps/internal/-DnsOverHttpsQuery.kt","line":172,"symbol":"decodeResponse","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\ninternal fun decodeResponse(response: Response): DnsMessage {\n if (\n response.cacheResponse == null &&\n response.protocol !== Protocol.HTTP_2 &&\n response.protocol !== Protocol.QUIC\n ) {\n Platform.get().log(\"Unexpected protocol: ${response.protocol}\", Platform.WARN)\n }\n\n response.use {\n if (!response.isSuccessful) {\n throw IOException(\"response: ${response.code} ${response.message}\")\n }\n\n val body = response.body\n if (body.contentLength() > MAX_RESPONSE_SIZE) {\n throw ProtocolException(\n \"response size exceeds limit ($MAX_RESPONSE_SIZE bytes): ${body.contentLength()} bytes\",\n )\n }\n\n return DnsMessageReader(body.source()).read()\n }\n}"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":89,"symbol":"DnsOverHttpsTest","kind":"class","lang":"kotlin","doc":"This test takes advantage of the fact that the new DNS API always requests records in this order: * [TYPE_HTTPS] * [TYPE_AAAA] * [TYPE_A]","code":"@Burst\nclass DnsOverHttpsTest(\n private val entryPoint: EntryPoint = EntryPoint.NewCall,\n) {\n @RegisterExtension\n val platform = PlatformRule()\n\n private val server = FakeDns()\n\n @StartStop\n private val mockWebServer =\n MockWebServer()\n .apply {\n dispatcher = server.dispatcher\n }\n\n private val completedRunnables = LinkedBlockingDeque()\n private val executorService =\n object : ThreadPoolExecutor(\n 0,\n Int.MAX_VALUE,\n 1,\n TimeUnit.SECONDS,\n SynchronousQueue(),\n ) {\n override fun afterExecute(\n r: Runnable,\n t: Throwable?,\n ) {\n completedRunnables.add(r)\n }\n }\n\n private lateinit var dns: DnsOverHttps\n private val dispatcher =\n Dispatcher(executorService)\n .apply {\n // Force calls to run sequentially for determinism.\n this.maxRequestsPerHost = 1\n }\n private val cacheFs = FakeFileSystem()\n private val eventRecorder = EventRecorder()\n private val bootstrapClient =\n OkHttpClient\n .Builder()\n .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))\n .dispatcher(dispatcher)\n .eventListener(eventRecorder.eventListener)\n .addInte"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":114,"symbol":"afterExecute","kind":"function","lang":"kotlin","code":"override fun afterExecute(\n r: Runnable,\n t: Throwable?,\n ) {\n completedRunnables.add(r)\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":145,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n mockWebServer.protocols = bootstrapClient.protocols\n dns = buildLocalhost(bootstrapClient)\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":151,"symbol":"getOne","kind":"function","lang":"kotlin","code":"@Test\n fun getOne() {\n server[\"lysine.dev\"] = listOf(InetAddress.getByName(\"10.20.30.40\"))\n val result = dns.invoke(entryPoint, \"lysine.dev\")\n assertThat(result).isEqualTo(listOf(address(\"10.20.30.40\")))\n val (dnsRequest, httpsRequest) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest!!.method).isEqualTo(\"GET\")\n assertThat(dnsRequest)\n .isEqualTo(queryRequest(\"lysine.dev\", TYPE_A))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":162,"symbol":"getWithCache","kind":"function","lang":"kotlin","code":"@Test\n fun getWithCache() {\n val dnsCache = DnsCache()\n dns = buildLocalhost(bootstrapClient, dnsCache = dnsCache)\n\n // Put a sample record in for the first query.\n server[\"lysine.dev\"] = listOf(InetAddress.getByName(\"10.20.30.40\"))\n val result0 = dns.invoke(entryPoint, \"lysine.dev\")\n assertThat(result0).isEqualTo(listOf(address(\"10.20.30.40\")))\n val (dnsRequest, httpsRequest) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest!!.method).isEqualTo(\"GET\")\n assertThat(dnsRequest)\n .isEqualTo(queryRequest(\"lysine.dev\", TYPE_A))\n\n // Put a different record in for the second query. We'll get the first record because that's\n // what is in the cache.\n server[\"lysine.dev\"] = listOf(InetAddress.getByName(\"55.66.77.88\"))\n val result1 = dns.invoke(entryPoint, \"lysine.dev\")\n assertThat(result1).isEqualTo(listOf(address(\"10.20.30.40\"))) // Stale! Cache worked!\n assertThat(server.pollRequest()).isNull() // No request.\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":184,"symbol":"getIpv6","kind":"function","lang":"kotlin","code":"@Test\n fun getIpv6() {\n server[\"lysine.dev\"] =\n listOf(\n InetAddress.getByName(\"10.20.30.40\"),\n InetAddress.getByName(\"1:2::3:4\"),\n )\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true)\n val result = dns(entryPoint, \"lysine.dev\")\n assertThat(result).containsExactly(\n address(\"1:2::3:4\"),\n address(\"10.20.30.40\"),\n )\n\n val (dnsRequest1, httpsRequest1) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest1!!.method).isEqualTo(\"GET\")\n assertThat(dnsRequest1).isEqualTo(queryRequest(\"lysine.dev\", TYPE_AAAA))\n\n val (dnsRequest2, httpsRequest2) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest2!!.method).isEqualTo(\"GET\")\n assertThat(dnsRequest2).isEqualTo(queryRequest(\"lysine.dev\", TYPE_A))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":207,"symbol":"lookupDoesNotRequestServiceMetadata","kind":"function","lang":"kotlin","code":"@Test\n fun lookupDoesNotRequestServiceMetadata() {\n assumeTrue(entryPoint == EntryPoint.Lookup)\n\n server[\"lysine.dev\"] =\n listOf(\n InetAddress.getByName(\"10.20.30.40\"),\n InetAddress.getByName(\"1:2::3:4\"),\n )\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n val result = dns(entryPoint, \"lysine.dev\")\n assertThat(result).containsExactly(\n address(\"1:2::3:4\"),\n address(\"10.20.30.40\"),\n )\n\n val (dnsRequest1, _) = server.takeRequest() as DnsRequest\n assertThat(dnsRequest1).isEqualTo(queryRequest(\"lysine.dev\", TYPE_AAAA))\n\n val (dnsRequest2, _) = server.takeRequest() as DnsRequest\n assertThat(dnsRequest2).isEqualTo(queryRequest(\"lysine.dev\", TYPE_A))\n\n assertThat(server.pollRequest()).isNull()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":232,"symbol":"failsBecauseNoRecords","kind":"function","lang":"kotlin","code":"@Test\n fun failsBecauseNoRecords() {\n assertFailsWith {\n dns(entryPoint, \"lysine.dev\")\n }\n val (dnsRequest, httpsRequest) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest!!.method).isEqualTo(\"GET\")\n assertThat(dnsRequest)\n .isEqualTo(queryRequest(\"lysine.dev\", TYPE_A))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":243,"symbol":"lookupReturnsNormallyIfIpv4FailsAndIpv6Succeeds","kind":"function","lang":"kotlin","code":"@Test\n fun lookupReturnsNormallyIfIpv4FailsAndIpv6Succeeds() {\n assumeTrue(entryPoint == EntryPoint.Lookup)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true)\n server[\"lysine.dev\"] = listOf(InetAddress.getByName(\"11:22::33:44\"))\n server.sequenceIndexToOverride[1] = overrideResponse(\"\")\n\n val results = dns(entryPoint, \"lysine.dev\")\n assertThat(results).containsExactly(InetAddress.getByName(\"11:22::33:44\"))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":255,"symbol":"lookupReturnsNormallyIfIpv6FailsAndIpv6Succeeds","kind":"function","lang":"kotlin","code":"@Test\n fun lookupReturnsNormallyIfIpv6FailsAndIpv6Succeeds() {\n assumeTrue(entryPoint == EntryPoint.Lookup)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true)\n server[\"lysine.dev\"] = listOf(InetAddress.getByName(\"10.20.30.40\"))\n server.sequenceIndexToOverride[0] = overrideResponse(\"\")\n\n val results = dns(entryPoint, \"lysine.dev\")\n assertThat(results).containsExactly(InetAddress.getByName(\"10.20.30.40\"))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":267,"symbol":"resolveForbiddenPrivateDomain","kind":"function","lang":"kotlin","code":"@Test\n fun resolveForbiddenPrivateDomain() {\n dns = buildLocalhost(bootstrapClient, resolvePrivateAddresses = false)\n\n val e =\n assertFailsWith {\n dns(entryPoint, \"dev\")\n }\n assertThat(e).hasMessage(\"private hosts not resolved\")\n assertThat(server.pollRequest()).isNull()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":279,"symbol":"resolveForbiddenPublicDomain","kind":"function","lang":"kotlin","code":"@Test\n fun resolveForbiddenPublicDomain() {\n dns = buildLocalhost(bootstrapClient, resolvePublicAddresses = false)\n\n val e =\n assertFailsWith {\n dns(entryPoint, \"lysine.dev\")\n }\n assertThat(e).hasMessage(\"public hosts not resolved\")\n assertThat(server.pollRequest()).isNull()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":291,"symbol":"failOnExcessiveResponse","kind":"function","lang":"kotlin","code":"@Test\n fun failOnExcessiveResponse() {\n val array = CharArray(128 * 1024 + 2) { '0' }\n server.sequenceIndexToOverride[0] = overrideResponse(String(array))\n val e =\n assertFailsWith {\n dns(entryPoint, \"lysine.dev\")\n }\n val rootCause = e.cause ?: e\n assertThat(rootCause).hasMessage(\"response size exceeds limit (65536 bytes): 65537 bytes\")\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":303,"symbol":"failOnBadResponse","kind":"function","lang":"kotlin","code":"@Test\n fun failOnBadResponse() {\n server.sequenceIndexToOverride[0] = overrideResponse(\"00\")\n val e =\n assertFailsWith {\n dns(entryPoint, \"lysine.dev\")\n }\n val rootCause = e.cause ?: e\n assertThat(rootCause).isInstanceOf()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":320,"symbol":"usesHttpCache","kind":"function","lang":"kotlin","doc":"TODO GET preferred order - with tests to confirm this 1. successful fresh cached GET response 2. unsuccessful (404, 500) fresh cached GET response 3. successful network response 4. successful stale cached GET response 5. unsuccessful response","code":"@Test\n fun usesHttpCache() {\n val cache = Cache(cacheFs, \"cache\".toPath(), (100 * 1024).toLong())\n val cachedClient = bootstrapClient.newBuilder().cache(cache).build()\n val cachedDns =\n buildLocalhost(\n bootstrapClient = cachedClient,\n dnsCache = DnsCache(maxEntryCount = 0),\n )\n\n server.extraHeaders =\n headersOf(\n \"cache-control\",\n \"private, max-age=298\",\n )\n server[\"lysine.dev\"] = listOf(InetAddress.getByName(\"10.20.30.40\"))\n server[\"alternate.lysine.dev\"] = listOf(InetAddress.getByName(\"55.66.77.88\"))\n\n val result1 = cachedDns(entryPoint, \"lysine.dev\")\n assertThat(result1).containsExactly(address(\"10.20.30.40\"))\n val (dnsRequest1, httpsRequest1) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest1!!.method).isEqualTo(\"GET\")\n assertThat(dnsRequest1)\n .isEqualTo(queryRequest(\"lysine.dev\", TYPE_A))\n\n assertThat(cacheEvents()).containsExactly(CacheMiss::class)\n\n val result2 = cachedDns(entryPoint, \"lysine.dev\")\n assertThat(server.pollRequest()).isNull()\n assertThat(result2).isEqualTo(listOf(address(\"10.20.30.40\")))\n\n assertThat(cacheEvents()).containsExactly(CacheHit::class"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":363,"symbol":"usesHttpCacheEvenForPost","kind":"function","lang":"kotlin","code":"@Test\n fun usesHttpCacheEvenForPost() {\n val cache = Cache(cacheFs, \"cache\".toPath(), (100 * 1024).toLong())\n val cachedClient = bootstrapClient.newBuilder().cache(cache).build()\n val cachedDns =\n buildLocalhost(\n bootstrapClient = cachedClient,\n post = true,\n dnsCache = DnsCache(maxEntryCount = 0),\n )\n server.extraHeaders =\n headersOf(\n \"cache-control\",\n \"private, max-age=298\",\n )\n server[\"lysine.dev\"] = listOf(InetAddress.getByName(\"10.20.30.40\"))\n server[\"alternate.lysine.dev\"] = listOf(InetAddress.getByName(\"55.66.77.88\"))\n\n val result1 = cachedDns(entryPoint, \"lysine.dev\")\n assertThat(result1).containsExactly(address(\"10.20.30.40\"))\n val (_, httpsRequest1) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest1!!.method).isEqualTo(\"POST\")\n assertThat(httpsRequest1.url.encodedQuery)\n .isEqualTo(\"ct\")\n // Cloudflare fails on chunked encoding\n assertThat(httpsRequest1.headers[\"Content-Length\"]?.toLong())\n .isNotNull()\n .isGreaterThan(12L) // A DNS message has a 12-byte header followed by its questions.\n assertThat(httpsRequest1.chunkSizes).isNull()\n\n assertTh"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":411,"symbol":"usesHttpCacheOnlyIfFresh","kind":"function","lang":"kotlin","code":"@Test\n fun usesHttpCacheOnlyIfFresh() {\n val cache = Cache(File(\"./target/DnsOverHttpsTest.cache\"), 100 * 1024L)\n val cachedClient = bootstrapClient.newBuilder().cache(cache).build()\n val cachedDns =\n buildLocalhost(\n bootstrapClient = cachedClient,\n dnsCache = DnsCache(maxEntryCount = 0),\n )\n server.extraHeaders =\n headersOf(\n \"cache-control\",\n \"no-store\",\n )\n server[\"lysine.dev\"] = listOf(InetAddress.getByName(\"10.20.30.40\"))\n val result1 = cachedDns(entryPoint, \"lysine.dev\")\n assertThat(result1).containsExactly(address(\"10.20.30.40\"))\n val (dnsRequest1, httpsRequest1) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest1!!.method).isEqualTo(\"GET\")\n assertThat(dnsRequest1)\n .isEqualTo(queryRequest(\"lysine.dev\", TYPE_A))\n\n assertThat(cacheEvents()).containsExactly(CacheMiss::class)\n\n val result2 = cachedDns(entryPoint, \"lysine.dev\")\n assertThat(result2).isEqualTo(listOf(address(\"10.20.30.40\")))\n val (dnsRequest2, httpsRequest2) = server.takeRequest() as DnsRequest\n assertThat(httpsRequest2!!.method).isEqualTo(\"GET\")\n assertThat(dnsRequest2)\n .isEqualTo(queryRequest(\""} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":445,"symbol":"completeHttpsRecordsReturned","kind":"function","lang":"kotlin","code":"@Test\n fun completeHttpsRecordsReturned() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n server[\"lysine.dev\"] =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"10.20.30.40\"),\n ),\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"1:2::3:4\"),\n ),\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 5,\n targetName = \"cdn.lysine.dev\",\n alpnIds = listOf(Protocol.HTTP_2.toString()),\n port = 8843,\n ipAddressHints =\n listOf(\n InetAddress.getByName(\"55.66.77.88\"),\n InetAddress.getByName(\"aa:bb::cc:dd\"),\n ),\n echConfigList = \"this is an encrypted client hello\".encodeUtf8(),\n ),\n )\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n val dnsEvents = call.toEventsQueue()\n\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = false"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":525,"symbol":"serviceMetadataEmptyTargetNameAliasesToRequestHostname","kind":"function","lang":"kotlin","code":"@Test\n fun serviceMetadataEmptyTargetNameAliasesToRequestHostname() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n server[\"lysine.dev\"] =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"10.20.30.40\"),\n ),\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 5,\n targetName = \"\",\n alpnIds = listOf(Protocol.HTTP_2.toString()),\n ),\n )\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n val dnsEvents = call.toEventsQueue()\n\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = false,\n records =\n listOf(\n Dns.Record.ServiceMetadata(\n hostname = \"lysine.dev\",\n alpnIds = listOf(Protocol.HTTP_2),\n ),\n ),\n ),\n )\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = true,\n records =\n listOf(\n Dns.Record.IpAddress(\n hostname = \"lysine.dev\",\n "} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":575,"symbol":"httpsFailureIsDeliveredAfterIpv6AndIpv4Records","kind":"function","lang":"kotlin","doc":"An HTTPS error is received before the IPv4 results, but the error is delivered last.","code":"@Test\n fun httpsFailureIsDeliveredAfterIpv6AndIpv4Records() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n\n // Fail the HTTPS call, which should have index 0.\n server.sequenceIndexToOverride[0] = overrideResponse(\"\")\n server[\"lysine.dev\"] =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"11:22::33:44\"),\n ),\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"10.20.30.40\"),\n ),\n )\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n val dnsEvents = call.toEventsQueue()\n\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = false,\n records =\n listOf(\n Dns.Record.IpAddress(\n hostname = \"lysine.dev\",\n address = InetAddress.getByName(\"11:22::33:44\"),\n ),\n ),\n ),\n )\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = false,\n records"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":628,"symbol":"ipv6FailureIsDeliveredAfterIpv4Records","kind":"function","lang":"kotlin","doc":"An IPv6 error is received before the IPv4 results, but the error is delivered last.","code":"@Test\n fun ipv6FailureIsDeliveredAfterIpv4Records() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n\n // Fail the IPv6 call, which should have index 1.\n server.sequenceIndexToOverride[1] = overrideResponse(\"\")\n server[\"lysine.dev\"] =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"10.20.30.40\"),\n ),\n )\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n val dnsEvents = call.toEventsQueue()\n\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = false,\n records =\n listOf(\n Dns.Record.IpAddress(\n hostname = \"lysine.dev\",\n address = InetAddress.getByName(\"10.20.30.40\"),\n ),\n ),\n ),\n )\n assertThat(dnsEvents.take()).isInstanceOf()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":664,"symbol":"emptyResultsAreSkipped","kind":"function","lang":"kotlin","doc":"There's no IPv6 event because there's no IPv6 results.","code":"@Test\n fun emptyResultsAreSkipped() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n server[\"lysine.dev\"] =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"10.20.30.40\"),\n ),\n )\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n val dnsEvents = call.toEventsQueue()\n\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = true,\n records =\n listOf(\n Dns.Record.IpAddress(\n hostname = \"lysine.dev\",\n address = InetAddress.getByName(\"10.20.30.40\"),\n ),\n ),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":695,"symbol":"lastEventIsDeliveredEventIfItIsEmpty","kind":"function","lang":"kotlin","code":"@Test\n fun lastEventIsDeliveredEventIfItIsEmpty() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n val dnsEvents = call.toEventsQueue()\n\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = true,\n records = listOf(),\n ),\n )\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":712,"symbol":"callIsCanceledBeforeItIsStarted","kind":"function","lang":"kotlin","code":"@Test\n fun callIsCanceledBeforeItIsStarted() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n call.cancel()\n assertThat(call.isCanceled()).isTrue()\n val dnsEvents = call.toEventsQueue()\n\n assertThat(dnsEvents.take()).isInstanceOf()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":726,"symbol":"callIsCanceledBeforeItReachesTheNetwork","kind":"function","lang":"kotlin","code":"@Test\n fun callIsCanceledBeforeItReachesTheNetwork() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n\n interceptor =\n Interceptor { chain ->\n call.cancel()\n assertThat(call.isCanceled()).isTrue()\n chain.proceed(chain.request())\n }\n\n val dnsEvents = call.toEventsQueue()\n assertThat(dnsEvents.take()).isInstanceOf()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":744,"symbol":"callIsCanceledAfterPartialSuccess","kind":"function","lang":"kotlin","code":"@Test\n fun callIsCanceledAfterPartialSuccess() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true)\n server[\"lysine.dev\"] =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"11:22::33:44\"),\n ),\n )\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n\n interceptor =\n object : Interceptor {\n var requestCount = 0\n\n override fun intercept(chain: Interceptor.Chain): Response {\n if (requestCount++ == 1) {\n call.cancel()\n assertThat(call.isCanceled()).isTrue()\n }\n return chain.proceed(chain.request())\n }\n }\n\n val dnsEvents = call.toEventsQueue()\n assertThat(dnsEvents.take()).isEqualTo(\n DnsEvent.Records(\n last = false,\n records =\n listOf(\n Dns.Record.IpAddress(\n hostname = \"lysine.dev\",\n address = InetAddress.getByName(\"11:22::33:44\"),\n ),\n ),\n ),\n )\n assertThat(dnsEvents.take()).isInstanceOf()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":764,"symbol":"intercept","kind":"function","lang":"kotlin","code":"override fun intercept(chain: Interceptor.Chain): Response {\n if (requestCount++ == 1) {\n call.cancel()\n assertThat(call.isCanceled()).isTrue()\n }\n return chain.proceed(chain.request())\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":789,"symbol":"callbackIsCalledSequentiallyWhenHttpCallsAreParallel","kind":"function","lang":"kotlin","code":"@Test\n fun callbackIsCalledSequentiallyWhenHttpCallsAreParallel() {\n callbackIsCalledSequentially()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":794,"symbol":"callbackIsCalledSequentiallyWhenCallsFail","kind":"function","lang":"kotlin","code":"@Test\n fun callbackIsCalledSequentiallyWhenCallsFail() {\n server.sequenceIndexToOverride[0] = overrideResponse(\"\")\n callbackIsCalledSequentially()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":809,"symbol":"callbackIsCalledSequentially","kind":"function","lang":"kotlin","doc":"Asserting that is awkward, so we're asserting something stronger, advised by the implementation: if the first call to `onRecords()` waits for the other 2 HTTP calls to finish, then all 3 calls will happen on the same thread. (This works because we know the other 2 HTTP calls will finish before their data is emitted.)","code":"private fun callbackIsCalledSequentially() {\n assumeTrue(entryPoint == EntryPoint.NewCall)\n\n dns = buildLocalhost(bootstrapClient, includeIPv6 = true, includeServiceMetadata = true)\n server[\"lysine.dev\"] =\n listOf(\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"10.20.30.40\"),\n ),\n ResourceRecord.IpAddress(\n name = \"lysine.dev\",\n timeToLive = 5,\n address = InetAddress.getByName(\"1:2::3:4\"),\n ),\n ResourceRecord.Https(\n name = \"lysine.dev\",\n timeToLive = 5,\n alpnIds = listOf(Protocol.HTTP_2.toString()),\n ),\n )\n\n // Track which threads receive callbacks.\n val threadsFuture = CompletableFuture>()\n\n dispatcher.maxRequestsPerHost = 3\n\n val call = dns.newCall(Dns.Request(\"lysine.dev\"))\n call.enqueue(\n object : Dns.Callback {\n private val threads = mutableSetOf()\n\n override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n onCallback(last)\n }\n\n override fun o"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":842,"symbol":"onRecords","kind":"function","lang":"kotlin","code":"override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n onCallback(last)\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":850,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Dns.Call,\n e: java.io.IOException,\n ) {\n onCallback(true)\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":857,"symbol":"onCallback","kind":"function","lang":"kotlin","code":"private fun onCallback(last: Boolean) {\n if (threads.isEmpty()) {\n completedRunnables.take()\n completedRunnables.take()\n }\n threads += Thread.currentThread()\n if (last) {\n threadsFuture.complete(threads)\n }\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":873,"symbol":"cacheEvents","kind":"function","lang":"kotlin","code":"private fun cacheEvents(): List> =\n eventRecorder\n .recordedEventTypes()\n .filter { \"Cache\" in it.simpleName!! }\n .also { eventRecorder.clearAllEvents() }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":879,"symbol":"buildLocalhost","kind":"function","lang":"kotlin","code":"private fun buildLocalhost(\n bootstrapClient: OkHttpClient,\n dnsCache: DnsCache = DnsCache(),\n includeIPv6: Boolean = false,\n includeServiceMetadata: Boolean = false,\n post: Boolean = false,\n resolvePrivateAddresses: Boolean = true,\n resolvePublicAddresses: Boolean = true,\n ): DnsOverHttps {\n val url = mockWebServer.url(\"/lookup?ct\")\n return DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .cache(dnsCache)\n .includeIPv6(includeIPv6)\n .includeServiceMetadata(includeServiceMetadata)\n .resolvePrivateAddresses(resolvePrivateAddresses)\n .resolvePublicAddresses(resolvePublicAddresses)\n .url(url)\n .post(post)\n .build()\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":902,"symbol":"overrideResponse","kind":"function","lang":"kotlin","code":"private fun overrideResponse(hexBody: String = \"\"): MockResponse =\n MockResponse\n .Builder()\n .body(Buffer().write(hexBody.decodeHex()))\n .addHeader(\"content-type\", \"application/dns-message\")\n .addHeader(\"content-length\", hexBody.length / 2)\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":910,"symbol":"queryRequest","kind":"function","lang":"kotlin","code":"private fun queryRequest(\n host: String,\n type: Int,\n ): DnsMessage =\n DnsMessage(\n id = 0,\n flags = 256,\n questions =\n listOf(\n Question(\n name = host,\n type = type,\n `class` = CLASS_IN,\n ),\n ),\n )"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsOverHttpsTest.kt","line":928,"symbol":"address","kind":"function","lang":"kotlin","code":"private fun address(host: String) = InetAddress.getByName(host)"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":38,"symbol":"DnsRecordCodecTest","kind":"class","lang":"kotlin","code":"class DnsRecordCodecTest {\n @Test\n fun testGoogleDotComEncoding() {\n val encoded = encodeQuery(\"google.com\", TYPE_A)\n assertThat(encoded).isEqualTo(\"AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ\")\n }\n\n private fun encodeQuery(\n host: String,\n type: Int,\n ): String = DnsMessage.query(Question(host, type)).asQueryParameter()\n\n @Test\n fun testGoogleDotComEncodingWithIPv6() {\n val encoded = encodeQuery(\"google.com\", TYPE_AAAA)\n assertThat(encoded).isEqualTo(\"AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ\")\n }\n\n @Test\n fun testGoogleDotComDecodingFromCloudflare() {\n val encoded =\n decodeAnswers(\n byteString =\n \"\"\"\n 00008180000100010000000006676f6f676c6503636f6d0000010001c00c00010001000000430004d83ad54e\n \"\"\".decodeHex(ignoreWhitespace = true),\n )\n assertThat(encoded).containsExactly(InetAddress.getByName(\"216.58.213.78\"))\n }\n\n @Test\n fun testGoogleDotComDecodingFromGoogle() {\n val decoded =\n decodeAnswers(\n byteString =\n \"\"\"\n 0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c0005000100000a\n 6d000603617069c012c0300005000100000cde000c04737461720463313072c012"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":39,"symbol":"testGoogleDotComEncoding","kind":"function","lang":"kotlin","code":"@Test\n fun testGoogleDotComEncoding() {\n val encoded = encodeQuery(\"google.com\", TYPE_A)\n assertThat(encoded).isEqualTo(\"AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ\")\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":45,"symbol":"encodeQuery","kind":"function","lang":"kotlin","code":"private fun encodeQuery(\n host: String,\n type: Int,\n ): String = DnsMessage.query(Question(host, type)).asQueryParameter()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":50,"symbol":"testGoogleDotComEncodingWithIPv6","kind":"function","lang":"kotlin","code":"@Test\n fun testGoogleDotComEncodingWithIPv6() {\n val encoded = encodeQuery(\"google.com\", TYPE_AAAA)\n assertThat(encoded).isEqualTo(\"AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ\")\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":56,"symbol":"testGoogleDotComDecodingFromCloudflare","kind":"function","lang":"kotlin","code":"@Test\n fun testGoogleDotComDecodingFromCloudflare() {\n val encoded =\n decodeAnswers(\n byteString =\n \"\"\"\n 00008180000100010000000006676f6f676c6503636f6d0000010001c00c00010001000000430004d83ad54e\n \"\"\".decodeHex(ignoreWhitespace = true),\n )\n assertThat(encoded).containsExactly(InetAddress.getByName(\"216.58.213.78\"))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":68,"symbol":"testGoogleDotComDecodingFromGoogle","kind":"function","lang":"kotlin","code":"@Test\n fun testGoogleDotComDecodingFromGoogle() {\n val decoded =\n decodeAnswers(\n byteString =\n \"\"\"\n 0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c0005000100000a\n 6d000603617069c012c0300005000100000cde000c04737461720463313072c012c042000100010000003b0004\n 9df00112\n \"\"\".decodeHex(ignoreWhitespace = true),\n )\n assertThat(decoded).containsExactly(InetAddress.getByName(\"157.240.1.18\"))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":82,"symbol":"testGoogleDotComDecodingFromGoogleIPv6","kind":"function","lang":"kotlin","code":"@Test\n fun testGoogleDotComDecodingFromGoogleIPv6() {\n val decoded =\n decodeAnswers(\n byteString =\n \"\"\"\n 0000818000010003000000000567726170680866616365626f6f6b03636f6d00001c0001c00c0005000100000a\n 1b000603617069c012c0300005000100000b1f000c04737461720463313072c012c042001c00010000003b0010\n 2a032880f0290011faceb00c00000002\n \"\"\".decodeHex(ignoreWhitespace = true),\n )\n assertThat(decoded)\n .containsExactly(InetAddress.getByName(\"2a03:2880:f029:11:face:b00c:0:2\"))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":97,"symbol":"testGoogleDotComDecodingNxdomainFailure","kind":"function","lang":"kotlin","code":"@Test\n fun testGoogleDotComDecodingNxdomainFailure() {\n assertFailsWith {\n decodeAnswers(\n byteString =\n \"\"\"\n 0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b0006000100000707\n 0038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e6574c01b5adb12c100000e\n 10000003840012750000000e10\n \"\"\".decodeHex(ignoreWhitespace = true),\n )\n }\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DnsRecordCodecTest.kt","line":111,"symbol":"decodeAnswers","kind":"function","lang":"kotlin","code":"private fun decodeAnswers(byteString: ByteString): List {\n val reader = DnsMessageReader(Buffer().write(byteString))\n val dnsMessage = reader.read()\n if (dnsMessage.responseCode != RESPONSE_CODE_SUCCESS) {\n throw UnknownHostException()\n }\n return dnsMessage.answers\n .filterIsInstance()\n .map { it.address }\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":28,"symbol":"DohProviders","kind":"object","lang":"kotlin","doc":"Temporary registry of known DNS over HTTPS providers. https://github.com/curl/curl/wiki/DNS-over-HTTPS","code":"object DohProviders {\n private fun buildGoogle(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://dns.google/dns-query\".toHttpUrl())\n .bootstrapDnsHosts(getByIp(\"8.8.4.4\"), getByIp(\"8.8.8.8\"))\n .build()\n\n private fun buildGooglePost(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://dns.google/dns-query\".toHttpUrl())\n .bootstrapDnsHosts(getByIp(\"8.8.4.4\"), getByIp(\"8.8.8.8\"))\n .post(true)\n .build()\n\n private fun buildCloudflareIp(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .includeIPv6(false)\n .build()\n\n private fun buildCloudflare(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .bootstrapDnsHosts(getByIp(\"1.1.1.1\"), getByIp(\"1.0.0.1\"))\n .includeIPv6(false)\n .build()\n\n private fun buildCloudflarePost(bootstrapClient: OkHttpClient): Dns"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":29,"symbol":"buildGoogle","kind":"function","lang":"kotlin","code":"private fun buildGoogle(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://dns.google/dns-query\".toHttpUrl())\n .bootstrapDnsHosts(getByIp(\"8.8.4.4\"), getByIp(\"8.8.8.8\"))\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":37,"symbol":"buildGooglePost","kind":"function","lang":"kotlin","code":"private fun buildGooglePost(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://dns.google/dns-query\".toHttpUrl())\n .bootstrapDnsHosts(getByIp(\"8.8.4.4\"), getByIp(\"8.8.8.8\"))\n .post(true)\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":46,"symbol":"buildCloudflareIp","kind":"function","lang":"kotlin","code":"private fun buildCloudflareIp(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .includeIPv6(false)\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":54,"symbol":"buildCloudflare","kind":"function","lang":"kotlin","code":"private fun buildCloudflare(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .bootstrapDnsHosts(getByIp(\"1.1.1.1\"), getByIp(\"1.0.0.1\"))\n .includeIPv6(false)\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":63,"symbol":"buildCloudflarePost","kind":"function","lang":"kotlin","code":"private fun buildCloudflarePost(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://cloudflare-dns.com/dns-query\".toHttpUrl())\n .bootstrapDnsHosts(getByIp(\"1.1.1.1\"), getByIp(\"1.0.0.1\"))\n .includeIPv6(false)\n .post(true)\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":73,"symbol":"buildCleanBrowsing","kind":"function","lang":"kotlin","code":"fun buildCleanBrowsing(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://doh.cleanbrowsing.org/doh/family-filter/\".toHttpUrl())\n .includeIPv6(false)\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":81,"symbol":"buildChantra","kind":"function","lang":"kotlin","code":"private fun buildChantra(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://dns.dnsoverhttps.net/dns-query\".toHttpUrl())\n .includeIPv6(false)\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":89,"symbol":"buildCryptoSx","kind":"function","lang":"kotlin","code":"private fun buildCryptoSx(bootstrapClient: OkHttpClient): DnsOverHttps =\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(\"https://doh.crypto.sx/dns-query\".toHttpUrl())\n .includeIPv6(false)\n .build()"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":97,"symbol":"providers","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun providers(\n client: OkHttpClient,\n http2Only: Boolean,\n workingOnly: Boolean,\n getOnly: Boolean,\n ): List =\n buildList {\n add(buildGoogle(client))\n if (!getOnly) {\n add(buildGooglePost(client))\n }\n add(buildCloudflare(client))\n add(buildCloudflareIp(client))\n if (!getOnly) {\n add(buildCloudflarePost(client))\n }\n if (!workingOnly) {\n // result += buildCleanBrowsing(client); // timeouts\n add(buildCryptoSx(client)) // 521 - server down\n }\n add(buildChantra(client))\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/DohProviders.kt","line":121,"symbol":"getByIp","kind":"function","lang":"kotlin","code":"private fun getByIp(host: String): InetAddress =\n try {\n InetAddress.getByName(host)\n } catch (e: UnknownHostException) {\n // unlikely\n throw RuntimeException(e)\n }"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/TestDohMain.kt","line":27,"symbol":"runBatch","kind":"function","lang":"kotlin","code":"private fun runBatch(\n dnsProviders: List,\n names: List,\n) {\n var time = System.currentTimeMillis()\n for (dns in dnsProviders) {\n println(\"Testing ${dns.url}\")\n for (host in names) {\n print(\"$host: \")\n System.out.flush()\n try {\n val results = dns.lookup(host)\n println(results)\n } catch (uhe: UnknownHostException) {\n var e: Throwable? = uhe\n while (e != null) {\n println(e)\n e = e.cause\n }\n }\n }\n println()\n }\n time = System.currentTimeMillis() - time\n println(\"Time: ${time.toDouble() / 1000} seconds\\n\")\n}"} {"repo":"okhttp","file":"okhttp-dnsoverhttps/src/test/java/okhttp3/dnsoverhttps/TestDohMain.kt","line":54,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n Security.insertProviderAt(OpenSSLProvider(), 1)\n var bootstrapClient = OkHttpClient()\n var names = listOf(\"google.com\", \"graph.facebook.com\", \"sdflkhfsdlkjdf.ee\")\n try {\n println(\"uncached\\n********\\n\")\n var dnsProviders =\n providers(\n client = bootstrapClient,\n http2Only = false,\n workingOnly = false,\n getOnly = false,\n )\n runBatch(dnsProviders, names)\n val dnsCache =\n Cache(\n directory = File(\"./target/TestDohMain.cache.${System.currentTimeMillis()}\"),\n maxSize = 10L * 1024 * 1024,\n )\n println(\"Bad targets\\n***********\\n\")\n val url = \"https://dns.cloudflare.com/.not-so-well-known/run-dmc-query\".toHttpUrl()\n val badProviders =\n listOf(\n DnsOverHttps\n .Builder()\n .client(bootstrapClient)\n .url(url)\n .post(true)\n .build(),\n )\n runBatch(badProviders, names)\n println(\"cached first run\\n****************\\n\")\n names = listOf(\"google.com\", \"graph.facebook.com\")\n bootstrapClient =\n bootstrapClient\n .newBuilder()\n .cache(dnsCache)\n .build()\n dnsProviders =\n providers(\n client = "} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeInteropTest.kt","line":25,"symbol":"HpackDecodeInteropTest","kind":"class","lang":"kotlin","code":"class HpackDecodeInteropTest : HpackDecodeTestBase() {\n @ParameterizedTest\n @ArgumentsSource(StoriesTestProvider::class)\n fun testGoodDecoderInterop(story: Story) {\n assumeFalse(\n story === Story.MISSING,\n \"Test stories missing, checkout git submodule\",\n )\n testDecoder(story)\n }\n\n internal class StoriesTestProvider : SimpleProvider() {\n override fun arguments(): List = createStories(HpackJsonUtil.storiesForCurrentDraft())\n }\n}"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeInteropTest.kt","line":26,"symbol":"testGoodDecoderInterop","kind":"function","lang":"kotlin","code":"@ParameterizedTest\n @ArgumentsSource(StoriesTestProvider::class)\n fun testGoodDecoderInterop(story: Story) {\n assumeFalse(\n story === Story.MISSING,\n \"Test stories missing, checkout git submodule\",\n )\n testDecoder(story)\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeInteropTest.kt","line":36,"symbol":"StoriesTestProvider","kind":"class","lang":"kotlin","code":"internal class StoriesTestProvider : SimpleProvider() {\n override fun arguments(): List = createStories(HpackJsonUtil.storiesForCurrentDraft())\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeInteropTest.kt","line":37,"symbol":"arguments","kind":"function","lang":"kotlin","code":"override fun arguments(): List = createStories(HpackJsonUtil.storiesForCurrentDraft())"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeTestBase.kt","line":27,"symbol":"HpackDecodeTestBase","kind":"class","lang":"kotlin","doc":"Tests Hpack implementation using https://github.com/http2jp/hpack-test-case/","code":"open class HpackDecodeTestBase {\n private val bytesIn = Buffer()\n private val hpackReader = Hpack.Reader(bytesIn, 4096)\n\n protected fun testDecoder(story: Story) {\n for (testCase in story.cases) {\n val encoded = testCase.wire ?: continue\n bytesIn.write(encoded)\n hpackReader.readHeaders()\n assertSetEquals(\n \"seqno=$testCase.seqno\",\n testCase.headersList,\n hpackReader.getAndResetHeaderList(),\n )\n }\n }\n\n companion object {\n /**\n * Reads all stories in the folders provided, asserts if no story found.\n */\n @JvmStatic\n protected fun createStories(interopTests: Array): List {\n if (interopTests.isEmpty()) return listOf(Story.MISSING)\n\n val result = mutableListOf()\n for (interopTestName in interopTests) {\n val stories = HpackJsonUtil.readStories(interopTestName)\n result.addAll(stories)\n }\n return result\n }\n\n /**\n * Checks if `expected` and `observed` are equal when viewed as a set and headers are\n * deduped.\n *\n * TODO: See if duped headers should be preserved on decode and verify.\n */\n private fun assertSetEquals(\n message"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeTestBase.kt","line":31,"symbol":"testDecoder","kind":"function","lang":"kotlin","code":"protected fun testDecoder(story: Story) {\n for (testCase in story.cases) {\n val encoded = testCase.wire ?: continue\n bytesIn.write(encoded)\n hpackReader.readHeaders()\n assertSetEquals(\n \"seqno=$testCase.seqno\",\n testCase.headersList,\n hpackReader.getAndResetHeaderList(),\n )\n }\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeTestBase.kt","line":48,"symbol":"createStories","kind":"function","lang":"kotlin","doc":"Reads all stories in the folders provided, asserts if no story found.","code":"@JvmStatic\n protected fun createStories(interopTests: Array): List {\n if (interopTests.isEmpty()) return listOf(Story.MISSING)\n\n val result = mutableListOf()\n for (interopTestName in interopTests) {\n val stories = HpackJsonUtil.readStories(interopTestName)\n result.addAll(stories)\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackDecodeTestBase.kt","line":66,"symbol":"assertSetEquals","kind":"function","lang":"kotlin","doc":"Checks if `expected` and `observed` are equal when viewed as a set and headers are deduped. TODO: See if duped headers should be preserved on decode and verify.","code":"private fun assertSetEquals(\n message: String,\n expected: List
,\n observed: List
,\n ) {\n assertThat(LinkedHashSet(observed), message)\n .isEqualTo(LinkedHashSet(expected))\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackRoundTripTest.kt","line":33,"symbol":"HpackRoundTripTest","kind":"class","lang":"kotlin","doc":"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","code":"class HpackRoundTripTest : HpackDecodeTestBase() {\n internal class StoriesTestProvider : SimpleProvider() {\n override fun arguments(): List = createStories(RAW_DATA)\n }\n\n private val bytesOut = Buffer()\n private val hpackWriter = Hpack.Writer(out = bytesOut)\n\n @ParameterizedTest\n @ArgumentsSource(StoriesTestProvider::class)\n fun testRoundTrip(story: Story) {\n assumeFalse(\n story === Story.MISSING,\n \"Test stories missing, checkout git submodule\",\n )\n\n val newCases = mutableListOf()\n for (case in story.cases) {\n hpackWriter.writeHeaders(case.headersList)\n newCases += case.copy(wire = bytesOut.readByteString())\n }\n\n testDecoder(story.copy(cases = newCases))\n }\n\n companion object {\n private val RAW_DATA = arrayOf(\"raw-data\")\n }\n}"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackRoundTripTest.kt","line":34,"symbol":"StoriesTestProvider","kind":"class","lang":"kotlin","code":"internal class StoriesTestProvider : SimpleProvider() {\n override fun arguments(): List = createStories(RAW_DATA)\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackRoundTripTest.kt","line":35,"symbol":"arguments","kind":"function","lang":"kotlin","code":"override fun arguments(): List = createStories(RAW_DATA)"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/HpackRoundTripTest.kt","line":41,"symbol":"testRoundTrip","kind":"function","lang":"kotlin","code":"@ParameterizedTest\n @ArgumentsSource(StoriesTestProvider::class)\n fun testRoundTrip(story: Story) {\n assumeFalse(\n story === Story.MISSING,\n \"Test stories missing, checkout git submodule\",\n )\n\n val newCases = mutableListOf()\n for (case in story.cases) {\n hpackWriter.writeHeaders(case.headersList)\n newCases += case.copy(wire = bytesOut.readByteString())\n }\n\n testDecoder(story.copy(cases = newCases))\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/Case.kt","line":25,"symbol":"Case","kind":"class","lang":"kotlin","doc":"Representation of an individual case (set of headers and wire format). There are many cases for a single story. This class is used reflectively with Moshi to parse stories.","code":"data class Case(\n val seqno: Int = 0,\n val wire: ByteString? = null,\n val headers: List>,\n) : Cloneable {\n val headersList: List
\n get() {\n val result = mutableListOf
()\n for (inputHeader in headers) {\n val (key, value) = inputHeader.entries.iterator().next()\n result.add(Header(key, value))\n }\n return result\n }\n\n public override fun clone() = Case(seqno, this.wire, headers)\n}"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/Case.kt","line":40,"symbol":"clone","kind":"function","lang":"kotlin","code":"public override fun clone() = Case(seqno, this.wire, headers)"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.kt","line":36,"symbol":"HpackJsonUtil","kind":"object","lang":"kotlin","doc":"Utilities for reading HPACK tests.","code":"object HpackJsonUtil {\n @Suppress(\"unused\")\n private val MOSHI =\n Moshi\n .Builder()\n .add(\n object : Any() {\n @ToJson fun byteStringToJson(byteString: ByteString) = byteString.hex()\n\n @FromJson fun byteStringFromJson(json: String) = json.decodeHex()\n },\n ).add(KotlinJsonAdapterFactory())\n .build()\n private val STORY_JSON_ADAPTER = MOSHI.adapter(Story::class.java)\n\n private val fileSystem = FileSystem.SYSTEM\n\n private fun readStory(source: BufferedSource): Story = STORY_JSON_ADAPTER.fromJson(source)!!\n\n private fun readStory(file: Path): Story {\n fileSystem.read(file) {\n return readStory(this)\n }\n }\n\n /** Iterate through the hpack-test-case resources, only picking stories for the current draft. */\n fun storiesForCurrentDraft(): Array {\n val resource =\n HpackJsonUtil::class.java.getResource(\"/hpack-test-case\")\n ?: return arrayOf()\n\n val testCaseDirectory = File(resource.toURI()).toOkioPath()\n val result = mutableListOf()\n for (path in fileSystem.list(testCaseDirectory)) {\n val story00 = path / \"story_00.json\"\n if (!fileSystem.exists(story00)) continue\n tr"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.kt","line":43,"symbol":"byteStringToJson","kind":"function","lang":"kotlin","code":"@ToJson fun byteStringToJson(byteString: ByteString) = byteString.hex()"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.kt","line":45,"symbol":"byteStringFromJson","kind":"function","lang":"kotlin","code":"@FromJson fun byteStringFromJson(json: String) = json.decodeHex()"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.kt","line":53,"symbol":"readStory","kind":"function","lang":"kotlin","code":"private fun readStory(source: BufferedSource): Story = STORY_JSON_ADAPTER.fromJson(source)!!"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.kt","line":55,"symbol":"readStory","kind":"function","lang":"kotlin","code":"private fun readStory(file: Path): Story {\n fileSystem.read(file) {\n return readStory(this)\n }\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.kt","line":62,"symbol":"storiesForCurrentDraft","kind":"function","lang":"kotlin","doc":"Iterate through the hpack-test-case resources, only picking stories for the current draft.","code":"fun storiesForCurrentDraft(): Array {\n val resource =\n HpackJsonUtil::class.java.getResource(\"/hpack-test-case\")\n ?: return arrayOf()\n\n val testCaseDirectory = File(resource.toURI()).toOkioPath()\n val result = mutableListOf()\n for (path in fileSystem.list(testCaseDirectory)) {\n val story00 = path / \"story_00.json\"\n if (!fileSystem.exists(story00)) continue\n try {\n readStory(story00)\n result.add(path.name)\n } catch (ignored: IOException) {\n // Skip this path.\n }\n }\n return result.toTypedArray()\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/HpackJsonUtil.kt","line":85,"symbol":"readStories","kind":"function","lang":"kotlin","doc":"Reads stories named \"story_xx.json\" from the folder provided.","code":"fun readStories(testFolderName: String): List {\n val result = mutableListOf()\n var i = 0\n while (true) { // break after last test.\n val storyResourceName =\n String.format(\n \"/hpack-test-case/%s/story_%02d.json\",\n testFolderName,\n i,\n )\n val storyInputStream =\n HpackJsonUtil::class.java.getResourceAsStream(storyResourceName)\n ?: break\n try {\n storyInputStream.use {\n val story =\n readStory(storyInputStream.source().buffer())\n .copy(fileName = storyResourceName)\n result.add(story)\n i++\n }\n } finally {\n storyInputStream.close()\n }\n }\n\n if (result.isEmpty()) {\n // missing files\n result.add(Story.MISSING)\n }\n\n return result\n }"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/Story.kt","line":22,"symbol":"Story","kind":"class","lang":"kotlin","doc":"Representation of one story, a set of request headers to encode or decode. This class is used reflectively with Moshi to parse stories from files.","code":"data class Story(\n val description: String? = null,\n val cases: List,\n val fileName: String? = null,\n) {\n // Used as the test name.\n override fun toString() = fileName ?: \"?\"\n\n companion object {\n @JvmField\n val MISSING = Story(description = \"Missing\", cases = listOf(), \"missing\")\n }\n}"} {"repo":"okhttp","file":"okhttp-hpacktests/src/test/java/okhttp3/internal/http2/hpackjson/Story.kt","line":28,"symbol":"toString","kind":"function","lang":"kotlin","doc":"Used as the test name.","code":"override fun toString() = fileName ?: \"?\""} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/GenerateIdnaMappingTableCode.kt","line":28,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main(vararg args: String) {\n val data = loadIdnaMappingTableData()\n val file = generateMappingTableFile(data)\n file.writeTo(File(args[0]))\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/GenerateIdnaMappingTableCode.kt","line":34,"symbol":"loadIdnaMappingTableData","kind":"function","lang":"kotlin","code":"fun loadIdnaMappingTableData(): IdnaMappingTableData {\n val path = \"/okhttp3/internal/idna/IdnaMappingTable.txt\".toPath()\n val table =\n FileSystem.RESOURCES.read(path) {\n readPlainTextIdnaMappingTable()\n }\n return buildIdnaMappingTableData(table)\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/GenerateIdnaMappingTableCode.kt","line":54,"symbol":"generateMappingTableFile","kind":"function","lang":"kotlin","doc":"sections = \"...\", ranges = \"...\", mappings = \"\", ) ```","code":"fun generateMappingTableFile(data: IdnaMappingTableData): FileSpec {\n val packageName = \"okhttp3.internal.idn\"\n val idnaMappingTable = ClassName(packageName, \"IdnaMappingTable\")\n\n return FileSpec\n .builder(packageName, \"IdnaMappingTableInstance\")\n .addProperty(\n PropertySpec\n .builder(\"IDNA_MAPPING_TABLE\", idnaMappingTable)\n .addModifiers(KModifier.INTERNAL)\n .initializer(\n \"\"\"\n |%T(⇥\n |sections = \"%L\",\n |ranges = \"%L\",\n |mappings = \"%L\",\n |⇤)\n \"\"\".trimMargin(),\n idnaMappingTable,\n data.sections.escapeDataString(),\n data.ranges.escapeDataString(),\n data.mappings.escapeDataString(),\n ).build(),\n ).build()\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/GenerateIdnaMappingTableCode.kt","line":84,"symbol":"escapeDataString","kind":"function","lang":"kotlin","doc":"KotlinPoet doesn't really know what to do with a string containing NUL, BEL, DEL, etc. We also don't want to perform `trimMargin()` at runtime.","code":"fun String.escapeDataString(): String =\n buildString {\n for (codePoint in this@escapeDataString.codePoints()) {\n when (codePoint) {\n in 0..0x20,\n '\"'.code,\n '$'.code,\n '\\\\'.code,\n '·'.code,\n 127,\n -> append(String.format(\"\\\\u%04x\", codePoint))\n\n else -> appendCodePoint(codePoint)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappedRange.kt","line":21,"symbol":"MappedRange","kind":"interface","lang":"kotlin","code":"internal sealed interface MappedRange {\n val rangeStart: Int\n\n data class Constant(\n override val rangeStart: Int,\n val type: Int,\n ) : MappedRange {\n val b1: Int\n get() =\n when (type) {\n TYPE_IGNORED -> 119\n TYPE_VALID -> 120\n TYPE_DISALLOWED -> 121\n else -> error(\"unexpected type: $type\")\n }\n }\n\n data class Inline1(\n override val rangeStart: Int,\n private val mappedTo: ByteString,\n ) : MappedRange {\n val b1: Int\n get() {\n val b3bit8 = mappedTo[0] and 0x80 != 0\n return if (b3bit8) 123 else 122\n }\n\n val b2: Int\n get() = mappedTo[0] and 0x7f\n }\n\n data class Inline2(\n override val rangeStart: Int,\n private val mappedTo: ByteString,\n ) : MappedRange {\n val b1: Int\n get() {\n val b2bit8 = mappedTo[0] and 0x80 != 0\n val b3bit8 = mappedTo[1] and 0x80 != 0\n return when {\n b2bit8 && b3bit8 -> 127\n b3bit8 -> 126\n b2bit8 -> 125\n else -> 124\n }\n }\n\n val b2: Int\n get() = mappedTo[0] and 0x7f\n\n val b3: Int\n get() = mappedTo[1] and 0x7f\n }\n\n data class InlineDelta(\n override val ran"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappedRange.kt","line":24,"symbol":"Constant","kind":"class","lang":"kotlin","code":"data class Constant(\n override val rangeStart: Int,\n val type: Int,\n ) : MappedRange {\n val b1: Int\n get() =\n when (type) {\n TYPE_IGNORED -> 119\n TYPE_VALID -> 120\n TYPE_DISALLOWED -> 121\n else -> error(\"unexpected type: $type\")\n }\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappedRange.kt","line":38,"symbol":"Inline1","kind":"class","lang":"kotlin","code":"data class Inline1(\n override val rangeStart: Int,\n private val mappedTo: ByteString,\n ) : MappedRange {\n val b1: Int\n get() {\n val b3bit8 = mappedTo[0] and 0x80 != 0\n return if (b3bit8) 123 else 122\n }\n\n val b2: Int\n get() = mappedTo[0] and 0x7f\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappedRange.kt","line":52,"symbol":"Inline2","kind":"class","lang":"kotlin","code":"data class Inline2(\n override val rangeStart: Int,\n private val mappedTo: ByteString,\n ) : MappedRange {\n val b1: Int\n get() {\n val b2bit8 = mappedTo[0] and 0x80 != 0\n val b3bit8 = mappedTo[1] and 0x80 != 0\n return when {\n b2bit8 && b3bit8 -> 127\n b3bit8 -> 126\n b2bit8 -> 125\n else -> 124\n }\n }\n\n val b2: Int\n get() = mappedTo[0] and 0x7f\n\n val b3: Int\n get() = mappedTo[1] and 0x7f\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappedRange.kt","line":75,"symbol":"InlineDelta","kind":"class","lang":"kotlin","code":"data class InlineDelta(\n override val rangeStart: Int,\n val codepointDelta: Int,\n ) : MappedRange {\n private val absoluteDelta = abs(codepointDelta)\n\n val b1: Int\n get() =\n when {\n codepointDelta < 0 -> 0x40 or (absoluteDelta shr 14)\n codepointDelta > 0 -> 0x50 or (absoluteDelta shr 14)\n else -> error(\"Unexpected codepointDelta of 0\")\n }\n\n val b2: Int\n get() = absoluteDelta shr 7 and 0x7f\n\n val b3: Int\n get() = absoluteDelta and 0x7f\n\n companion object {\n const val MAX_VALUE = 0x3FFFF\n }\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":23,"symbol":"buildIdnaMappingTableData","kind":"function","lang":"kotlin","doc":"Index [table] for compactness as specified by `IdnaMappingTable`.","code":"fun buildIdnaMappingTableData(table: SimpleIdnaMappingTable): IdnaMappingTableData {\n val simplified = mergeAdjacentRanges(table.mappings)\n val withoutSectionSpans = withoutSectionSpans(simplified)\n val sections = sections(withoutSectionSpans)\n\n val rangesBuffer = Buffer()\n val mappingsBuffer = StringBuilder()\n val sectionIndexBuffer = Buffer()\n\n var previousMappedRanges: List? = null\n\n for ((section, sectionMappedRanges) in sections) {\n // Skip sequential ranges when they are equal.\n if (sectionMappedRanges == previousMappedRanges) continue\n previousMappedRanges = sectionMappedRanges\n\n val sectionOffset = rangesBuffer.size.toInt() / 4\n\n // Section prefix.\n sectionIndexBuffer.writeByte(section and 0x1fc000 shr 14)\n sectionIndexBuffer.writeByte((section and 0x3f80) shr 7)\n\n // Section index.\n sectionIndexBuffer.writeByte((sectionOffset and 0x3f80) shr 7)\n sectionIndexBuffer.writeByte(sectionOffset and 0x7f)\n\n // Ranges.\n for (range in sectionMappedRanges) {\n rangesBuffer.writeByte(range.rangeStart)\n\n when (range) {\n is MappedRange.Constant -> {\n rangesBuffer.writeByte(range.b1)\n rangesBuffer."} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":114,"symbol":"inlineDeltaOrNull","kind":"function","lang":"kotlin","doc":"If [mapping] qualifies to be encoded as [MappedRange.InlineDelta] return new instance, otherwise null. An [MappedRange.InlineDelta] must be a mapping from a single code-point to a single code-point with a difference that can be represented in 2^18-1.","code":"internal fun inlineDeltaOrNull(mapping: Mapping): MappedRange.InlineDelta? {\n if (mapping.hasSingleSourceCodePoint) {\n val sourceCodePoint = mapping.sourceCodePoint0\n val mappedCodePoints =\n mapping.mappedTo\n .utf8()\n .codePoints()\n .toList()\n if (mappedCodePoints.size == 1) {\n val codePointDelta = mappedCodePoints.single() - sourceCodePoint\n if (MappedRange.InlineDelta.MAX_VALUE >= abs(codePointDelta)) {\n return MappedRange.InlineDelta(mapping.rangeStart, codePointDelta)\n }\n }\n }\n return null\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":135,"symbol":"sections","kind":"function","lang":"kotlin","doc":"Inputs must have applied [withoutSectionSpans].","code":"internal fun sections(mappings: List): Map> {\n val result = mutableMapOf>()\n\n for (mapping in mappings) {\n require(!mapping.spansSections)\n\n val section = mapping.section\n val rangeStart = mapping.rangeStart\n\n val sectionList = result.getOrPut(section) { mutableListOf() }\n\n sectionList +=\n when (mapping.type) {\n TYPE_MAPPED -> {\n run {\n val deltaMapping = inlineDeltaOrNull(mapping)\n if (deltaMapping != null) {\n return@run deltaMapping\n }\n\n when (mapping.mappedTo.size) {\n 1 -> MappedRange.Inline1(rangeStart, mapping.mappedTo)\n 2 -> MappedRange.Inline2(rangeStart, mapping.mappedTo)\n else -> MappedRange.External(rangeStart, mapping.mappedTo)\n }\n }\n }\n\n TYPE_IGNORED, TYPE_VALID, TYPE_DISALLOWED -> {\n MappedRange.Constant(rangeStart, mapping.type)\n }\n\n else -> {\n error(\"unexpected mapping type: ${mapping.type}\")\n }\n }\n }\n\n for (sectionList in result.values) {\n mergeAdjacentDeltaMappedRanges(sectionList)\n }\n\n re"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":184,"symbol":"mergeAdjacentDeltaMappedRanges","kind":"function","lang":"kotlin","doc":"Modifies [ranges] to combine any adjacent [MappedRange.InlineDelta] of same size to single entry. @returns same instance of [ranges] for convenience","code":"internal fun mergeAdjacentDeltaMappedRanges(ranges: MutableList): MutableList {\n var i = 0\n while (i < ranges.size) {\n val curr = ranges[i]\n if (curr is MappedRange.InlineDelta) {\n val j = i + 1\n mergeAdjacent@ while (j < ranges.size) {\n val next = ranges[j]\n if (next is MappedRange.InlineDelta &&\n curr.codepointDelta == next.codepointDelta\n ) {\n ranges.removeAt(j)\n } else {\n break@mergeAdjacent\n }\n }\n }\n i++\n }\n return ranges\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":210,"symbol":"withoutSectionSpans","kind":"function","lang":"kotlin","doc":"Returns a copy of [mappings], splitting to ensure that each mapping is entirely contained within a single section.","code":"internal fun withoutSectionSpans(mappings: List): List {\n val result = mutableListOf()\n\n val i = mappings.iterator()\n var current = i.next()\n\n while (true) {\n if (current.spansSections) {\n result +=\n Mapping(\n current.sourceCodePoint0,\n current.section + 0x7f,\n current.type,\n current.mappedTo,\n )\n current =\n Mapping(\n current.section + 0x80,\n current.sourceCodePoint1,\n current.type,\n current.mappedTo,\n )\n } else {\n result += current\n current = if (i.hasNext()) i.next() else break\n }\n }\n\n return result\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":242,"symbol":"mergeAdjacentRanges","kind":"function","lang":"kotlin","doc":"Returns a copy of [mappings] with adjacent ranges merged wherever possible.","code":"internal fun mergeAdjacentRanges(mappings: List): List {\n var index = 0\n val result = mutableListOf()\n\n while (index < mappings.size) {\n val mapping = mappings[index]\n val type = canonicalizeType(mapping.type)\n val mappedTo = mapping.mappedTo\n\n var unionWith: Mapping = mapping\n index++\n\n while (index < mappings.size) {\n val next = mappings[index]\n\n if (type != canonicalizeType(next.type)) break\n if (type == TYPE_MAPPED && mappedTo != next.mappedTo) break\n\n unionWith = next\n index++\n }\n\n result +=\n Mapping(\n sourceCodePoint0 = mapping.sourceCodePoint0,\n sourceCodePoint1 = unionWith.sourceCodePoint1,\n type = type,\n mappedTo = mappedTo,\n )\n }\n\n return result\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":276,"symbol":"canonicalizeType","kind":"function","lang":"kotlin","code":"internal fun canonicalizeType(type: Int): Int =\n when (type) {\n TYPE_IGNORED -> TYPE_IGNORED\n\n TYPE_MAPPED,\n TYPE_DISALLOWED_STD3_MAPPED,\n -> TYPE_MAPPED\n\n TYPE_DEVIATION,\n TYPE_DISALLOWED_STD3_VALID,\n TYPE_VALID,\n -> TYPE_VALID\n\n TYPE_DISALLOWED -> TYPE_DISALLOWED\n\n else -> error(\"unexpected type: $type\")\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":296,"symbol":"and","kind":"function","lang":"kotlin","code":"internal infix fun Short.and(mask: Int): Int = toInt() and mask"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/MappingTables.kt","line":298,"symbol":"and","kind":"function","lang":"kotlin","code":"internal infix fun Int.and(mask: Long): Long = toLong() and mask"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt","line":39,"symbol":"SimpleIdnaMappingTable","kind":"class","lang":"kotlin","doc":"This implementation's STD3 rules are configured to `UseSTD3ASCIIRules=false`. This is permissive and permits the `_` character. [mapping table]: https://www.unicode.org/reports/tr46/#IDNA_Mapping_Table [mapping step]: https://www.unicode.org/reports/tr46/#ProcessingStepMap","code":"class SimpleIdnaMappingTable internal constructor(\n internal val mappings: List,\n) {\n /**\n * Returns true if the [codePoint] was applied successfully. Returns false if it was disallowed.\n */\n fun map(\n codePoint: Int,\n sink: BufferedSink,\n ): Boolean {\n val index =\n mappings.binarySearch {\n when {\n it.sourceCodePoint1 < codePoint -> -1\n it.sourceCodePoint0 > codePoint -> 1\n else -> 0\n }\n }\n\n // Code points must be in 0..0x10ffff.\n require(index in mappings.indices) { \"unexpected code point: $codePoint\" }\n\n val mapping = mappings[index]\n var result = true\n\n when (mapping.type) {\n TYPE_IGNORED -> {\n Unit\n }\n\n TYPE_MAPPED, TYPE_DISALLOWED_STD3_MAPPED -> {\n sink.write(mapping.mappedTo)\n }\n\n TYPE_DEVIATION, TYPE_DISALLOWED_STD3_VALID, TYPE_VALID -> {\n sink.writeUtf8CodePoint(codePoint)\n }\n\n TYPE_DISALLOWED -> {\n sink.writeUtf8CodePoint(codePoint)\n result = false\n }\n }\n\n return result\n }\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt","line":45,"symbol":"map","kind":"function","lang":"kotlin","doc":"Returns true if the [codePoint] was applied successfully. Returns false if it was disallowed.","code":"fun map(\n codePoint: Int,\n sink: BufferedSink,\n ): Boolean {\n val index =\n mappings.binarySearch {\n when {\n it.sourceCodePoint1 < codePoint -> -1\n it.sourceCodePoint0 > codePoint -> 1\n else -> 0\n }\n }\n\n // Code points must be in 0..0x10ffff.\n require(index in mappings.indices) { \"unexpected code point: $codePoint\" }\n\n val mapping = mappings[index]\n var result = true\n\n when (mapping.type) {\n TYPE_IGNORED -> {\n Unit\n }\n\n TYPE_MAPPED, TYPE_DISALLOWED_STD3_MAPPED -> {\n sink.write(mapping.mappedTo)\n }\n\n TYPE_DEVIATION, TYPE_DISALLOWED_STD3_VALID, TYPE_VALID -> {\n sink.writeUtf8CodePoint(codePoint)\n }\n\n TYPE_DISALLOWED -> {\n sink.writeUtf8CodePoint(codePoint)\n result = false\n }\n }\n\n return result\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt","line":139,"symbol":"skipWhitespace","kind":"function","lang":"kotlin","code":"private fun BufferedSource.skipWhitespace() {\n while (!exhausted()) {\n if (buffer[0] != ' '.code.toByte()) return\n skip(1L)\n }\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt","line":146,"symbol":"skipRestOfLine","kind":"function","lang":"kotlin","code":"private fun BufferedSource.skipRestOfLine() {\n when (val newline = indexOf('\\n'.code.toByte())) {\n -1L -> skip(buffer.size)\n\n // Exhaust this source.\n else -> skip(newline + 1)\n }\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt","line":173,"symbol":"readPlainTextIdnaMappingTable","kind":"function","lang":"kotlin","doc":"For lines that contain a mapping target, the next thing is a sequence of hex code points (like 0031 2044 0034). All other data is ignored.","code":"fun BufferedSource.readPlainTextIdnaMappingTable(): SimpleIdnaMappingTable {\n val mappedTo = Buffer()\n val result = mutableListOf()\n\n while (!exhausted()) {\n // Skip comment and empty lines.\n when (select(optionsDelimiter)) {\n DELIMITER_HASH -> {\n skipRestOfLine()\n continue\n }\n\n DELIMITER_NEWLINE -> {\n continue\n }\n\n DELIMITER_DOT, DELIMITER_SPACE, DELIMITER_SEMICOLON -> {\n throw IOException(\"unexpected delimiter\")\n }\n }\n\n // \"002F\" or \"0000..002C\"\n val sourceCodePoint0 = readHexadecimalUnsignedLong()\n val sourceCodePoint1 =\n when (select(optionsDot)) {\n DELIMITER_DOT -> {\n if (readByte() != '.'.code.toByte()) throw IOException(\"expected '..'\")\n readHexadecimalUnsignedLong()\n }\n\n else -> {\n sourceCodePoint0\n }\n }\n\n skipWhitespace()\n if (readByte() != ';'.code.toByte()) throw IOException(\"expected ';'\")\n\n // \"valid\" or \"mapped\"\n skipWhitespace()\n val type = select(optionsType)\n\n when (type) {\n TYPE_DEVIATION, TYPE_MAPPED, TYPE_DISALLOWED_STD3_MAPPED -> {\n skipWhitespace()\n if (readByte() != ';'.co"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/main/kotlin/okhttp3/internal/idn/SimpleIdnaMappingTable.kt","line":261,"symbol":"Mapping","kind":"class","lang":"kotlin","code":"internal data class Mapping(\n val sourceCodePoint0: Int,\n val sourceCodePoint1: Int,\n val type: Int,\n val mappedTo: ByteString,\n) {\n val section: Int\n get() = sourceCodePoint0 and 0x1fff80\n\n val rangeStart: Int\n get() = sourceCodePoint0 and 0x7f\n\n val hasSingleSourceCodePoint: Boolean\n get() = sourceCodePoint0 == sourceCodePoint1\n\n val spansSections: Boolean\n get() = (sourceCodePoint0 and 0x1fff80) != (sourceCodePoint1 and 0x1fff80)\n}"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":27,"symbol":"MappingTablesTest","kind":"class","lang":"kotlin","code":"class MappingTablesTest {\n @Test fun simplifyCombinesMultipleMappings() {\n assertThat(\n mergeAdjacentRanges(\n listOf(\n Mapping(0x0232, 0x0232, TYPE_MAPPED, \"a\".encodeUtf8()),\n Mapping(0x0233, 0x0233, TYPE_VALID, ByteString.EMPTY),\n Mapping(0x0234, 0x0236, TYPE_VALID, ByteString.EMPTY),\n Mapping(0x0237, 0x0239, TYPE_VALID, ByteString.EMPTY),\n Mapping(0x023a, 0x023a, TYPE_MAPPED, \"b\".encodeUtf8()),\n ),\n ),\n ).containsExactly(\n Mapping(0x0232, 0x0232, TYPE_MAPPED, \"a\".encodeUtf8()),\n Mapping(0x0233, 0x0239, TYPE_VALID, ByteString.EMPTY),\n Mapping(0x023a, 0x023a, TYPE_MAPPED, \"b\".encodeUtf8()),\n )\n }\n\n @Test fun simplifyDoesNotCombineWhenMappedTargetsAreDifferent() {\n assertThat(\n mergeAdjacentRanges(\n listOf(\n Mapping(0x0041, 0x0041, TYPE_MAPPED, \"a\".encodeUtf8()),\n Mapping(0x0042, 0x0042, TYPE_MAPPED, \"b\".encodeUtf8()),\n ),\n ),\n ).containsExactly(\n Mapping(0x0041, 0x0041, TYPE_MAPPED, \"a\".encodeUtf8()),\n Mapping(0x0042, 0x0042, TYPE_MAPPED, \"b\".encodeUtf8()),\n )\n }\n\n @Test fun simplifyCanonicalizesType() {\n assertThat(\n "} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":28,"symbol":"simplifyCombinesMultipleMappings","kind":"function","lang":"kotlin","code":"@Test fun simplifyCombinesMultipleMappings() {\n assertThat(\n mergeAdjacentRanges(\n listOf(\n Mapping(0x0232, 0x0232, TYPE_MAPPED, \"a\".encodeUtf8()),\n Mapping(0x0233, 0x0233, TYPE_VALID, ByteString.EMPTY),\n Mapping(0x0234, 0x0236, TYPE_VALID, ByteString.EMPTY),\n Mapping(0x0237, 0x0239, TYPE_VALID, ByteString.EMPTY),\n Mapping(0x023a, 0x023a, TYPE_MAPPED, \"b\".encodeUtf8()),\n ),\n ),\n ).containsExactly(\n Mapping(0x0232, 0x0232, TYPE_MAPPED, \"a\".encodeUtf8()),\n Mapping(0x0233, 0x0239, TYPE_VALID, ByteString.EMPTY),\n Mapping(0x023a, 0x023a, TYPE_MAPPED, \"b\".encodeUtf8()),\n )\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":46,"symbol":"simplifyDoesNotCombineWhenMappedTargetsAreDifferent","kind":"function","lang":"kotlin","code":"@Test fun simplifyDoesNotCombineWhenMappedTargetsAreDifferent() {\n assertThat(\n mergeAdjacentRanges(\n listOf(\n Mapping(0x0041, 0x0041, TYPE_MAPPED, \"a\".encodeUtf8()),\n Mapping(0x0042, 0x0042, TYPE_MAPPED, \"b\".encodeUtf8()),\n ),\n ),\n ).containsExactly(\n Mapping(0x0041, 0x0041, TYPE_MAPPED, \"a\".encodeUtf8()),\n Mapping(0x0042, 0x0042, TYPE_MAPPED, \"b\".encodeUtf8()),\n )\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":60,"symbol":"simplifyCanonicalizesType","kind":"function","lang":"kotlin","code":"@Test fun simplifyCanonicalizesType() {\n assertThat(\n mergeAdjacentRanges(\n listOf(\n Mapping(0x0000, 0x002c, TYPE_DISALLOWED_STD3_VALID, ByteString.EMPTY),\n ),\n ),\n ).containsExactly(\n Mapping(0x0000, 0x002c, TYPE_VALID, ByteString.EMPTY),\n )\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":72,"symbol":"simplifyCombinesCanonicalEquivalent","kind":"function","lang":"kotlin","code":"@Test fun simplifyCombinesCanonicalEquivalent() {\n assertThat(\n mergeAdjacentRanges(\n listOf(\n Mapping(0x0000, 0x002c, TYPE_DISALLOWED_STD3_VALID, ByteString.EMPTY),\n Mapping(0x002d, 0x002e, TYPE_VALID, ByteString.EMPTY),\n ),\n ),\n ).containsExactly(\n Mapping(0x0000, 0x002e, TYPE_VALID, ByteString.EMPTY),\n )\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":85,"symbol":"withSectionStartsSplits","kind":"function","lang":"kotlin","code":"@Test fun withSectionStartsSplits() {\n assertThat(\n withoutSectionSpans(\n listOf(\n Mapping(0x40000, 0x40180, TYPE_DISALLOWED, ByteString.EMPTY),\n ),\n ),\n ).containsExactly(\n Mapping(0x40000, 0x4007f, TYPE_DISALLOWED, ByteString.EMPTY),\n Mapping(0x40080, 0x400ff, TYPE_DISALLOWED, ByteString.EMPTY),\n Mapping(0x40100, 0x4017f, TYPE_DISALLOWED, ByteString.EMPTY),\n Mapping(0x40180, 0x40180, TYPE_DISALLOWED, ByteString.EMPTY),\n )\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":100,"symbol":"withSectionStartAlreadySplit","kind":"function","lang":"kotlin","code":"@Test fun withSectionStartAlreadySplit() {\n assertThat(\n withoutSectionSpans(\n listOf(\n Mapping(0x40000, 0x4007f, TYPE_DISALLOWED, ByteString.EMPTY),\n Mapping(0x40080, 0x400ff, TYPE_DISALLOWED, ByteString.EMPTY),\n ),\n ),\n ).containsExactly(\n Mapping(0x40000, 0x4007f, TYPE_DISALLOWED, ByteString.EMPTY),\n Mapping(0x40080, 0x400ff, TYPE_DISALLOWED, ByteString.EMPTY),\n )\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":114,"symbol":"mergeAdjacentDeltaMappedRangesWithMultipleDeltas","kind":"function","lang":"kotlin","code":"@Test fun mergeAdjacentDeltaMappedRangesWithMultipleDeltas() {\n assertThat(\n mergeAdjacentDeltaMappedRanges(\n mutableListOf(\n InlineDelta(1, 5),\n InlineDelta(2, 5),\n InlineDelta(3, 5),\n MappedRange.External(4, \"a\".encodeUtf8()),\n ),\n ),\n ).containsExactly(\n InlineDelta(1, 5),\n MappedRange.External(4, \"a\".encodeUtf8()),\n )\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":130,"symbol":"mergeAdjacentDeltaMappedRangesWithDifferentSizedDeltas","kind":"function","lang":"kotlin","code":"@Test fun mergeAdjacentDeltaMappedRangesWithDifferentSizedDeltas() {\n assertThat(\n mergeAdjacentDeltaMappedRanges(\n mutableListOf(\n InlineDelta(1, 5),\n InlineDelta(2, 5),\n InlineDelta(3, 1),\n ),\n ),\n ).containsExactly(\n InlineDelta(1, 5),\n InlineDelta(3, 1),\n )\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":145,"symbol":"inlineDeltaOrNullValid","kind":"function","lang":"kotlin","code":"@Test fun inlineDeltaOrNullValid() {\n assertThat(\n inlineDeltaOrNull(\n mappingOf(\n sourceCodePoint0 = 1,\n sourceCodePoint1 = 1,\n mappedToCodePoints = listOf(2),\n ),\n ),\n ).isEqualTo(InlineDelta(1, 1))\n\n assertThat(\n inlineDeltaOrNull(\n mappingOf(\n sourceCodePoint0 = 2,\n sourceCodePoint1 = 2,\n mappedToCodePoints = listOf(1),\n ),\n ),\n ).isEqualTo(InlineDelta(2, -1))\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":167,"symbol":"inlineDeltaOrNullMultipleSourceCodePoints","kind":"function","lang":"kotlin","code":"@Test fun inlineDeltaOrNullMultipleSourceCodePoints() {\n assertThat(\n inlineDeltaOrNull(\n mappingOf(\n sourceCodePoint0 = 2,\n sourceCodePoint1 = 3,\n mappedToCodePoints = listOf(2),\n ),\n ),\n ).isEqualTo(null)\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":179,"symbol":"inlineDeltaOrNullMultipleMappedToCodePoints","kind":"function","lang":"kotlin","code":"@Test fun inlineDeltaOrNullMultipleMappedToCodePoints() {\n assertThat(\n inlineDeltaOrNull(\n mappingOf(\n sourceCodePoint0 = 1,\n sourceCodePoint1 = 1,\n mappedToCodePoints = listOf(2, 3),\n ),\n ),\n ).isEqualTo(null)\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":191,"symbol":"inlineDeltaOrNullMaxCodepointDelta","kind":"function","lang":"kotlin","code":"@Test fun inlineDeltaOrNullMaxCodepointDelta() {\n assertThat(\n inlineDeltaOrNull(\n mappingOf(\n sourceCodePoint0 = 0,\n sourceCodePoint1 = 0,\n mappedToCodePoints = listOf((1 shl 18) - 1),\n ),\n ),\n ).isEqualTo(\n InlineDelta(\n rangeStart = 0,\n codepointDelta = InlineDelta.MAX_VALUE,\n ),\n )\n\n assertThat(\n inlineDeltaOrNull(\n mappingOf(\n sourceCodePoint0 = 0,\n sourceCodePoint1 = 0,\n mappedToCodePoints = listOf(1 shl 18),\n ),\n ),\n ).isEqualTo(null)\n }"} {"repo":"okhttp","file":"okhttp-idna-mapping-table/src/test/kotlin/okhttp3/internal/idn/MappingTablesTest.kt","line":218,"symbol":"mappingOf","kind":"function","lang":"kotlin","code":"private fun mappingOf(\n sourceCodePoint0: Int,\n sourceCodePoint1: Int,\n mappedToCodePoints: List,\n ): Mapping =\n Mapping(\n sourceCodePoint0 = sourceCodePoint0,\n sourceCodePoint1 = sourceCodePoint1,\n type = TYPE_MAPPED,\n mappedTo =\n Buffer()\n .also {\n for (cp in mappedToCodePoints) {\n it.writeUtf8CodePoint(cp)\n }\n }.readByteString(),\n )"} {"repo":"okhttp","file":"okhttp-java-net-cookiejar/src/main/kotlin/okhttp3/java/net/cookiejar/JavaNetCookieJar.kt","line":33,"symbol":"JavaNetCookieJar","kind":"class","lang":"kotlin","doc":"A cookie jar that delegates to a [java.net.CookieHandler].","code":"class JavaNetCookieJar(\n private val cookieHandler: CookieHandler,\n) : CookieJar {\n override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) {\n val cookieStrings = mutableListOf()\n for (cookie in cookies) {\n cookieStrings.add(cookieToString(cookie, true))\n }\n val multimap = mapOf(\"Set-Cookie\" to cookieStrings)\n try {\n cookieHandler.put(url.toUri(), multimap)\n } catch (e: IOException) {\n Platform.get().log(\"Saving cookies failed for \" + url.resolve(\"/...\")!!, WARN, e)\n }\n }\n\n override fun loadForRequest(url: HttpUrl): List {\n val cookieHeaders =\n try {\n // The RI passes all headers. We don't have 'em, so we don't pass 'em!\n cookieHandler.get(url.toUri(), emptyMap>())\n } catch (e: IOException) {\n Platform.get().log(\"Loading cookies failed for \" + url.resolve(\"/...\")!!, WARN, e)\n return emptyList()\n }\n\n var cookies: MutableList? = null\n for ((key, value) in cookieHeaders) {\n if ((\"Cookie\".equals(key, ignoreCase = true) || \"Cookie2\".equals(key, ignoreCase = true)) &&\n value.isNotEmpty()\n ) {\n for (header "} {"repo":"okhttp","file":"okhttp-java-net-cookiejar/src/main/kotlin/okhttp3/java/net/cookiejar/JavaNetCookieJar.kt","line":36,"symbol":"saveFromResponse","kind":"function","lang":"kotlin","code":"override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) {\n val cookieStrings = mutableListOf()\n for (cookie in cookies) {\n cookieStrings.add(cookieToString(cookie, true))\n }\n val multimap = mapOf(\"Set-Cookie\" to cookieStrings)\n try {\n cookieHandler.put(url.toUri(), multimap)\n } catch (e: IOException) {\n Platform.get().log(\"Saving cookies failed for \" + url.resolve(\"/...\")!!, WARN, e)\n }\n }"} {"repo":"okhttp","file":"okhttp-java-net-cookiejar/src/main/kotlin/okhttp3/java/net/cookiejar/JavaNetCookieJar.kt","line":52,"symbol":"loadForRequest","kind":"function","lang":"kotlin","code":"override fun loadForRequest(url: HttpUrl): List {\n val cookieHeaders =\n try {\n // The RI passes all headers. We don't have 'em, so we don't pass 'em!\n cookieHandler.get(url.toUri(), emptyMap>())\n } catch (e: IOException) {\n Platform.get().log(\"Loading cookies failed for \" + url.resolve(\"/...\")!!, WARN, e)\n return emptyList()\n }\n\n var cookies: MutableList? = null\n for ((key, value) in cookieHeaders) {\n if ((\"Cookie\".equals(key, ignoreCase = true) || \"Cookie2\".equals(key, ignoreCase = true)) &&\n value.isNotEmpty()\n ) {\n for (header in value) {\n if (cookies == null) cookies = mutableListOf()\n cookies.addAll(decodeHeaderAsJavaNetCookies(url, header))\n }\n }\n }\n\n return if (cookies != null) {\n Collections.unmodifiableList(cookies)\n } else {\n emptyList()\n }\n }"} {"repo":"okhttp","file":"okhttp-java-net-cookiejar/src/main/kotlin/okhttp3/java/net/cookiejar/JavaNetCookieJar.kt","line":85,"symbol":"decodeHeaderAsJavaNetCookies","kind":"function","lang":"kotlin","doc":"Convert a request header to OkHttp's cookies via [HttpCookie]. That extra step handles multiple cookies in a single request header, which [Cookie.parse] doesn't support.","code":"private fun decodeHeaderAsJavaNetCookies(\n url: HttpUrl,\n header: String,\n ): List {\n val result = mutableListOf()\n var pos = 0\n val limit = header.length\n var pairEnd: Int\n while (pos < limit) {\n pairEnd = header.delimiterOffset(\";,\", pos, limit)\n val equalsSign = header.delimiterOffset('=', pos, pairEnd)\n val name = header.trimSubstring(pos, equalsSign)\n if (name.startsWith(\"$\")) {\n pos = pairEnd + 1\n continue\n }\n\n // We have either name=value or just a name.\n var value =\n if (equalsSign < pairEnd) {\n header.trimSubstring(equalsSign + 1, pairEnd)\n } else {\n \"\"\n }\n\n // If the value is \"quoted\", drop the quotes.\n if (value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\") && value.length >= 2) {\n value = value.substring(1, value.length - 1)\n }\n\n // Minimal normalisation so Cookie.Builder doesn't crash on values like \"abc123 \".\n value = value.trim()\n\n result.add(\n Cookie\n .Builder()\n .name(name)\n .value(value)\n .domain(url.host)\n .build(),\n )\n pos = pairEnd + 1\n }\n "} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":56,"symbol":"Level","kind":"enum","lang":"kotlin","code":"enum class Level {\n /** No logs. */\n NONE,\n\n /**\n * Logs request and response lines.\n *\n * Example:\n * ```\n * --> POST /greeting http/1.1 (3-byte body)\n *\n * <-- 200 OK (22ms, 6-byte body)\n * ```\n */\n BASIC,\n\n /**\n * Logs request and response lines and their respective headers.\n *\n * Example:\n * ```\n * --> POST /greeting http/1.1\n * Host: example.com\n * Content-Type: plain/text\n * Content-Length: 3\n * --> END POST\n *\n * <-- 200 OK (22ms)\n * Content-Type: plain/text\n * Content-Length: 6\n * <-- END HTTP\n * ```\n */\n HEADERS,\n\n /**\n * Logs request and response lines and their respective headers and bodies (if present).\n *\n * Example:\n * ```\n * --> POST /greeting http/1.1\n * Host: example.com\n * Content-Type: plain/text\n * Content-Length: 3\n *\n * Hi?\n * --> END POST\n *\n * <-- 200 OK (22ms)\n * Content-Type: plain/text\n * Content-Length: 6\n *\n * Hello!\n * <-- END HTTP\n * ```\n */\n BODY"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":58,"symbol":"NONE","kind":"enum_member","lang":"kotlin","doc":"No logs.","code":"NONE"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":70,"symbol":"BASIC","kind":"enum_member","lang":"kotlin","doc":"``` --> POST /greeting http/1.1 (3-byte body) <-- 200 OK (22ms, 6-byte body) ```","code":"BASIC"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":89,"symbol":"HEADERS","kind":"enum_member","lang":"kotlin","doc":"<-- 200 OK (22ms) Content-Type: plain/text Content-Length: 6 <-- END HTTP ```","code":"HEADERS"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":112,"symbol":"BODY","kind":"enum_member","lang":"kotlin","doc":"Content-Length: 6 Hello! <-- END HTTP ```","code":"BODY"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":115,"symbol":"Logger","kind":"interface","lang":"kotlin","code":"fun interface Logger {\n fun log(message: String)\n\n companion object {\n /** A [Logger] defaults output appropriate for the current platform. */\n @JvmField\n val DEFAULT: Logger = DefaultLogger()\n\n private class DefaultLogger : Logger {\n override fun log(message: String) {\n Platform.get().log(message)\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":116,"symbol":"log","kind":"function","lang":"kotlin","code":"fun log(message: String)"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":123,"symbol":"DefaultLogger","kind":"class","lang":"kotlin","code":"private class DefaultLogger : Logger {\n override fun log(message: String) {\n Platform.get().log(message)\n }\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":124,"symbol":"log","kind":"function","lang":"kotlin","code":"override fun log(message: String) {\n Platform.get().log(message)\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":131,"symbol":"redactHeader","kind":"function","lang":"kotlin","code":"fun redactHeader(name: String) {\n val newHeadersToRedact = TreeSet(String.CASE_INSENSITIVE_ORDER)\n newHeadersToRedact += headersToRedact\n newHeadersToRedact += name\n headersToRedact = newHeadersToRedact\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":138,"symbol":"redactQueryParams","kind":"function","lang":"kotlin","code":"fun redactQueryParams(vararg name: String) {\n val newQueryParamsNameToRedact = TreeSet(String.CASE_INSENSITIVE_ORDER)\n newQueryParamsNameToRedact += queryParamsNameToRedact\n newQueryParamsNameToRedact.addAll(name)\n queryParamsNameToRedact = newQueryParamsNameToRedact\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":152,"symbol":"setLevel","kind":"function","lang":"kotlin","doc":"Sets the level and returns this. This was deprecated in OkHttp 4.0 in favor of the [level] val. In OkHttp 4.3 it is un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains deprecated).","code":"fun setLevel(level: Level) =\n apply {\n this.level = level\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":157,"symbol":"getLevel","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_level\")\n @Deprecated(\n message = \"moved to var\",\n replaceWith = ReplaceWith(expression = \"level\"),\n level = DeprecationLevel.ERROR,\n )\n fun getLevel(): Level = level"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":166,"symbol":"intercept","kind":"function","lang":"kotlin","code":"override fun intercept(chain: Interceptor.Chain): Response {\n val level = this.level\n\n val request = chain.request()\n if (level == Level.NONE) {\n return chain.proceed(request)\n }\n\n val logBody = level == Level.BODY\n val logHeaders = logBody || level == Level.HEADERS\n\n val requestBody = request.body\n\n val connection = chain.connection()\n var requestStartMessage =\n (\"--> ${request.method} ${redactUrl(request.url)}${if (connection != null) \" \" + connection.protocol() else \"\"}\")\n if (!logHeaders && requestBody != null) {\n requestStartMessage += \" (${requestBody.contentLength()}-byte body)\"\n }\n logger.log(requestStartMessage)\n\n if (logHeaders) {\n val headers = request.headers\n\n if (requestBody != null) {\n // Request body headers are only present when installed as a network interceptor. When not\n // already present, force them to be included (if available) so their values are known.\n requestBody.contentType()?.let {\n if (headers[\"Content-Type\"] == null) {\n logger.log(\"Content-Type: $it\")\n }\n }\n if (requestBody."} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":333,"symbol":"redactUrl","kind":"function","lang":"kotlin","code":"internal fun redactUrl(url: HttpUrl): String {\n if (queryParamsNameToRedact.isEmpty() || url.querySize == 0) {\n return url.toString()\n }\n return url\n .newBuilder()\n .query(null)\n .apply {\n for (i in 0 until url.querySize) {\n val parameterName = url.queryParameterName(i)\n val newValue = if (parameterName in queryParamsNameToRedact) \"██\" else url.queryParameterValue(i)\n\n addEncodedQueryParameter(parameterName, newValue)\n }\n }.toString()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":350,"symbol":"logHeader","kind":"function","lang":"kotlin","code":"private fun logHeader(\n headers: Headers,\n i: Int,\n ) {\n val value = if (headers.name(i) in headersToRedact) \"██\" else headers.value(i)\n logger.log(headers.name(i) + \": \" + value)\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":358,"symbol":"bodyHasUnknownEncoding","kind":"function","lang":"kotlin","code":"private fun bodyHasUnknownEncoding(headers: Headers): Boolean {\n val contentEncoding = headers[\"Content-Encoding\"] ?: return false\n return !contentEncoding.equals(\"identity\", ignoreCase = true) &&\n !contentEncoding.equals(\"gzip\", ignoreCase = true)\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/HttpLoggingInterceptor.kt","line":364,"symbol":"bodyIsStreaming","kind":"function","lang":"kotlin","code":"private fun bodyIsStreaming(response: Response): Boolean {\n val contentType = response.body.contentType()\n return contentType != null && contentType.type == \"text\" && contentType.subtype == \"event-stream\"\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":41,"symbol":"LoggingEventListener","kind":"class","lang":"kotlin","doc":"An OkHttp EventListener, which logs call events. Can be applied as an [event listener factory][OkHttpClient.eventListenerFactory]. The format of the logs created by this class should not be considered stable and may change slightly between releases. If you need a stable logging format, use your own event listener.","code":"class LoggingEventListener private constructor(\n private val logger: HttpLoggingInterceptor.Logger,\n) : EventListener() {\n private var startNs: Long = 0\n\n override fun callStart(call: Call) {\n startNs = System.nanoTime()\n\n logWithTime(\"callStart: ${call.request()}\")\n }\n\n override fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n logWithTime(\"dispatcherQueueStart: $call queuedCallsCount=${dispatcher.queuedCallsCount()}\")\n }\n\n override fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n logWithTime(\"dispatcherQueueEnd: $call queuedCallsCount=${dispatcher.queuedCallsCount()}\")\n }\n\n override fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) {\n logWithTime(\"proxySelectStart: $url\")\n }\n\n override fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List,\n ) {\n logWithTime(\"proxySelectEnd: $proxies\")\n }\n\n override fun dnsStart(\n call: Call,\n domainName: String,\n ) {\n logWithTime(\"dnsStart: $domainName\")\n }\n\n override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List,\n ) {\n logWithTime(\"dnsEnd: $inetAddressList\")\n }\n\n ov"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":46,"symbol":"callStart","kind":"function","lang":"kotlin","code":"override fun callStart(call: Call) {\n startNs = System.nanoTime()\n\n logWithTime(\"callStart: ${call.request()}\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":52,"symbol":"dispatcherQueueStart","kind":"function","lang":"kotlin","code":"override fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n logWithTime(\"dispatcherQueueStart: $call queuedCallsCount=${dispatcher.queuedCallsCount()}\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":59,"symbol":"dispatcherQueueEnd","kind":"function","lang":"kotlin","code":"override fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n logWithTime(\"dispatcherQueueEnd: $call queuedCallsCount=${dispatcher.queuedCallsCount()}\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":66,"symbol":"proxySelectStart","kind":"function","lang":"kotlin","code":"override fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) {\n logWithTime(\"proxySelectStart: $url\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":73,"symbol":"proxySelectEnd","kind":"function","lang":"kotlin","code":"override fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List,\n ) {\n logWithTime(\"proxySelectEnd: $proxies\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":81,"symbol":"dnsStart","kind":"function","lang":"kotlin","code":"override fun dnsStart(\n call: Call,\n domainName: String,\n ) {\n logWithTime(\"dnsStart: $domainName\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":88,"symbol":"dnsEnd","kind":"function","lang":"kotlin","code":"override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List,\n ) {\n logWithTime(\"dnsEnd: $inetAddressList\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":96,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n logWithTime(\"connectStart: $inetSocketAddress $proxy\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":104,"symbol":"secureConnectStart","kind":"function","lang":"kotlin","code":"override fun secureConnectStart(call: Call) {\n logWithTime(\"secureConnectStart\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":108,"symbol":"secureConnectEnd","kind":"function","lang":"kotlin","code":"override fun secureConnectEnd(\n call: Call,\n handshake: Handshake?,\n ) {\n logWithTime(\"secureConnectEnd: $handshake\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":115,"symbol":"connectEnd","kind":"function","lang":"kotlin","code":"override fun connectEnd(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ) {\n logWithTime(\"connectEnd: $protocol\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":124,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ioe: IOException,\n ) {\n logWithTime(\"connectFailed: $protocol $ioe\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":134,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n logWithTime(\"connectionAcquired: $connection\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":141,"symbol":"connectionReleased","kind":"function","lang":"kotlin","code":"override fun connectionReleased(\n call: Call,\n connection: Connection,\n ) {\n logWithTime(\"connectionReleased\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":148,"symbol":"requestHeadersStart","kind":"function","lang":"kotlin","code":"override fun requestHeadersStart(call: Call) {\n logWithTime(\"requestHeadersStart\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":152,"symbol":"requestHeadersEnd","kind":"function","lang":"kotlin","code":"override fun requestHeadersEnd(\n call: Call,\n request: Request,\n ) {\n logWithTime(\"requestHeadersEnd\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":159,"symbol":"requestBodyStart","kind":"function","lang":"kotlin","code":"override fun requestBodyStart(call: Call) {\n logWithTime(\"requestBodyStart\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":163,"symbol":"requestBodyEnd","kind":"function","lang":"kotlin","code":"override fun requestBodyEnd(\n call: Call,\n byteCount: Long,\n ) {\n logWithTime(\"requestBodyEnd: byteCount=$byteCount\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":170,"symbol":"requestFailed","kind":"function","lang":"kotlin","code":"override fun requestFailed(\n call: Call,\n ioe: IOException,\n ) {\n logWithTime(\"requestFailed: $ioe\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":177,"symbol":"responseHeadersStart","kind":"function","lang":"kotlin","code":"override fun responseHeadersStart(call: Call) {\n logWithTime(\"responseHeadersStart\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":181,"symbol":"responseHeadersEnd","kind":"function","lang":"kotlin","code":"override fun responseHeadersEnd(\n call: Call,\n response: Response,\n ) {\n logWithTime(\"responseHeadersEnd: $response\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":188,"symbol":"responseBodyStart","kind":"function","lang":"kotlin","code":"override fun responseBodyStart(call: Call) {\n logWithTime(\"responseBodyStart\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":192,"symbol":"responseBodyEnd","kind":"function","lang":"kotlin","code":"override fun responseBodyEnd(\n call: Call,\n byteCount: Long,\n ) {\n logWithTime(\"responseBodyEnd: byteCount=$byteCount\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":199,"symbol":"responseFailed","kind":"function","lang":"kotlin","code":"override fun responseFailed(\n call: Call,\n ioe: IOException,\n ) {\n logWithTime(\"responseFailed: $ioe\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":206,"symbol":"callEnd","kind":"function","lang":"kotlin","code":"override fun callEnd(call: Call) {\n logWithTime(\"callEnd\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":210,"symbol":"callFailed","kind":"function","lang":"kotlin","code":"override fun callFailed(\n call: Call,\n ioe: IOException,\n ) {\n logWithTime(\"callFailed: $ioe\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":217,"symbol":"canceled","kind":"function","lang":"kotlin","code":"override fun canceled(call: Call) {\n logWithTime(\"canceled\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":221,"symbol":"satisfactionFailure","kind":"function","lang":"kotlin","code":"override fun satisfactionFailure(\n call: Call,\n response: Response,\n ) {\n logWithTime(\"satisfactionFailure: $response\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":228,"symbol":"cacheHit","kind":"function","lang":"kotlin","code":"override fun cacheHit(\n call: Call,\n response: Response,\n ) {\n logWithTime(\"cacheHit: $response\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":235,"symbol":"cacheMiss","kind":"function","lang":"kotlin","code":"override fun cacheMiss(call: Call) {\n logWithTime(\"cacheMiss\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":239,"symbol":"cacheConditionalHit","kind":"function","lang":"kotlin","code":"override fun cacheConditionalHit(\n call: Call,\n cachedResponse: Response,\n ) {\n logWithTime(\"cacheConditionalHit: $cachedResponse\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":246,"symbol":"logWithTime","kind":"function","lang":"kotlin","code":"private fun logWithTime(message: String) {\n val timeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)\n logger.log(\"[$timeMs ms] $message\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/main/kotlin/okhttp3/logging/LoggingEventListener.kt","line":256,"symbol":"create","kind":"function","lang":"kotlin","code":"override fun create(call: Call): EventListener = LoggingEventListener(logger)"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":50,"symbol":"HttpLoggingInterceptorTest","kind":"class","lang":"kotlin","code":"class HttpLoggingInterceptorTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private val hostnameVerifier = RecordingHostnameVerifier()\n private lateinit var client: OkHttpClient\n private lateinit var host: String\n private lateinit var url: HttpUrl\n private val networkLogs = LogRecorder()\n private val networkInterceptor = HttpLoggingInterceptor(networkLogs)\n private val applicationLogs = LogRecorder()\n private val applicationInterceptor = HttpLoggingInterceptor(applicationLogs)\n private var extraNetworkInterceptor: Interceptor? = null\n\n private fun setLevel(level: Level) {\n networkInterceptor.setLevel(level)\n applicationInterceptor.setLevel(level)\n }\n\n @BeforeEach\n fun setUp() {\n client =\n OkHttpClient\n .Builder()\n .addNetworkInterceptor(\n Interceptor { chain ->\n when {\n extraNetworkInterceptor != null -> extraNetworkInterceptor!!.intercept(chain)\n else -> chain.proceed(chain.request())\n }\n },\n ).addNetworkInterceptor(networkI"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":68,"symbol":"setLevel","kind":"function","lang":"kotlin","code":"private fun setLevel(level: Level) {\n networkInterceptor.setLevel(level)\n applicationInterceptor.setLevel(level)\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":73,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n client =\n OkHttpClient\n .Builder()\n .addNetworkInterceptor(\n Interceptor { chain ->\n when {\n extraNetworkInterceptor != null -> extraNetworkInterceptor!!.intercept(chain)\n else -> chain.proceed(chain.request())\n }\n },\n ).addNetworkInterceptor(networkInterceptor)\n .addInterceptor(applicationInterceptor)\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).hostnameVerifier(hostnameVerifier)\n .build()\n host = \"${server.hostName}:${server.port}\"\n url = server.url(\"/\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":96,"symbol":"levelGetter","kind":"function","lang":"kotlin","code":"@Test\n fun levelGetter() {\n // The default is NONE.\n assertThat(applicationInterceptor.level).isEqualTo(Level.NONE)\n for (level in Level.entries) {\n applicationInterceptor.setLevel(level)\n assertThat(applicationInterceptor.level).isEqualTo(level)\n }\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":106,"symbol":"setLevelShouldReturnSameInstanceOfInterceptor","kind":"function","lang":"kotlin","code":"@Test\n fun setLevelShouldReturnSameInstanceOfInterceptor() {\n for (level in Level.entries) {\n assertThat(applicationInterceptor.setLevel(level)).isSameInstanceAs(applicationInterceptor)\n }\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":113,"symbol":"none","kind":"function","lang":"kotlin","code":"@Test\n fun none() {\n server.enqueue(MockResponse())\n client.newCall(request().build()).execute()\n applicationLogs.assertNoMoreLogs()\n networkLogs.assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":121,"symbol":"basicGet","kind":"function","lang":"kotlin","code":"@Test\n fun basicGet() {\n setLevel(Level.BASIC)\n server.enqueue(MockResponse())\n client.newCall(request().build()).execute()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":136,"symbol":"basicPost","kind":"function","lang":"kotlin","code":"@Test\n fun basicPost() {\n setLevel(Level.BASIC)\n server.enqueue(MockResponse())\n client.newCall(request().post(\"Hi?\".toRequestBody(PLAIN)).build()).execute()\n applicationLogs\n .assertLogEqual(\"--> POST $url (3-byte body)\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> POST $url http/1.1 (3-byte body)\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":151,"symbol":"basicResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun basicResponseBody() {\n setLevel(Level.BASIC)\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello!\")\n .setHeader(\"Content-Type\", PLAIN)\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms, 6-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms, 6-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":173,"symbol":"basicChunkedResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun basicChunkedResponseBody() {\n setLevel(Level.BASIC)\n server.enqueue(\n MockResponse\n .Builder()\n .chunkedBody(\"Hello!\", 2)\n .setHeader(\"Content-Type\", PLAIN)\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms, unknown-length body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms, unknown-length body\\)\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":195,"symbol":"headersGet","kind":"function","lang":"kotlin","code":"@Test\n fun headersGet() {\n setLevel(Level.HEADERS)\n server.enqueue(MockResponse())\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":221,"symbol":"headersPost","kind":"function","lang":"kotlin","code":"@Test\n fun headersPost() {\n setLevel(Level.HEADERS)\n server.enqueue(MockResponse())\n val request = request().post(\"Hi?\".toRequestBody(PLAIN)).build()\n val response = client.newCall(request).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> POST $url\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"Content-Length: 3\")\n .assertLogEqual(\"--> END POST\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> POST $url http/1.1\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"Content-Length: 3\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END POST\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":252,"symbol":"headersPostNoContentType","kind":"function","lang":"kotlin","code":"@Test\n fun headersPostNoContentType() {\n setLevel(Level.HEADERS)\n server.enqueue(MockResponse())\n val request = request().post(\"Hi?\".toRequestBody(null)).build()\n val response = client.newCall(request).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> POST $url\")\n .assertLogEqual(\"Content-Length: 3\")\n .assertLogEqual(\"--> END POST\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> POST $url http/1.1\")\n .assertLogEqual(\"Content-Length: 3\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END POST\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":281,"symbol":"headersPostNoLength","kind":"function","lang":"kotlin","code":"@Test\n fun headersPostNoLength() {\n setLevel(Level.HEADERS)\n server.enqueue(MockResponse())\n val body: RequestBody =\n object : RequestBody() {\n override fun contentType() = PLAIN\n\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"Hi!\")\n }\n }\n val response = client.newCall(request().post(body).build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> POST $url\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"--> END POST\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> POST $url http/1.1\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"Transfer-Encoding: chunked\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END POST\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\""} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":287,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = PLAIN"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":289,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"Hi!\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":318,"symbol":"headersPostWithHeaderOverrides","kind":"function","lang":"kotlin","code":"@Test\n fun headersPostWithHeaderOverrides() {\n setLevel(Level.HEADERS)\n extraNetworkInterceptor =\n Interceptor { chain: Interceptor.Chain ->\n chain.proceed(\n chain\n .request()\n .newBuilder()\n .header(\"Content-Length\", \"2\")\n .header(\"Content-Type\", \"text/plain-ish\")\n .build(),\n )\n }\n server.enqueue(MockResponse())\n client\n .newCall(\n request()\n .post(\"Hi?\".toRequestBody(PLAIN))\n .build(),\n ).execute()\n applicationLogs\n .assertLogEqual(\"--> POST $url\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"Content-Length: 3\")\n .assertLogEqual(\"--> END POST\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> POST $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"Content-L"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":363,"symbol":"headersResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun headersResponseBody() {\n setLevel(Level.HEADERS)\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello!\")\n .setHeader(\"Content-Type\", PLAIN)\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 6\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 6\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"<-- END HTTP\")\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":397,"symbol":"bodyGet","kind":"function","lang":"kotlin","code":"@Test\n fun bodyGet() {\n setLevel(Level.BODY)\n server.enqueue(MockResponse())\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":423,"symbol":"bodyGet204","kind":"function","lang":"kotlin","code":"@Test\n fun bodyGet204() {\n setLevel(Level.BODY)\n bodyGetNoBody(204)\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":429,"symbol":"bodyGet205","kind":"function","lang":"kotlin","code":"@Test\n fun bodyGet205() {\n setLevel(Level.BODY)\n bodyGetNoBody(205)\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":435,"symbol":"bodyGetNoBody","kind":"function","lang":"kotlin","code":"private fun bodyGetNoBody(code: Int) {\n server.enqueue(\n MockResponse\n .Builder()\n .status(\"HTTP/1.1 $code No Content\")\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- $code No Content $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- $code No Content $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":464,"symbol":"bodyPost","kind":"function","lang":"kotlin","code":"@Test\n fun bodyPost() {\n setLevel(Level.BODY)\n server.enqueue(MockResponse())\n val request = request().post(\"Hi?\".toRequestBody(PLAIN)).build()\n val response = client.newCall(request).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> POST $url\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"Content-Length: 3\")\n .assertLogEqual(\"\")\n .assertLogEqual(\"Hi?\")\n .assertLogEqual(\"--> END POST (3-byte body)\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> POST $url http/1.1\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"Content-Length: 3\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"\")\n .assertLogEqual(\"Hi?\")\n .assertLogEqual(\"--> END POST (3-byte body)\")\n .assertLogMatch"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":499,"symbol":"bodyResponseBody","kind":"function","lang":"kotlin","code":"@Test\n fun bodyResponseBody() {\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello!\")\n .setHeader(\"Content-Type\", PLAIN)\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 6\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"\")\n .assertLogEqual(\"Hello!\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 6-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 6\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"\""} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":537,"symbol":"bodyResponseBodyChunked","kind":"function","lang":"kotlin","code":"@Test\n fun bodyResponseBodyChunked() {\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder()\n .chunkedBody(\"Hello!\", 2)\n .setHeader(\"Content-Type\", PLAIN)\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Transfer-encoding: chunked\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogEqual(\"\")\n .assertLogEqual(\"Hello!\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 6-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Transfer-encoding: chunked\")\n .assertLogEqual(\"Content-Type: text/plain; chars"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":575,"symbol":"bodyRequestGzipEncoded","kind":"function","lang":"kotlin","code":"@Test\n fun bodyRequestGzipEncoded() {\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder()\n .setHeader(\"Content-Type\", PLAIN)\n .body(Buffer().writeUtf8(\"Uncompressed\"))\n .build(),\n )\n val response =\n client\n .newCall(\n request()\n .post(\"Uncompressed\".toRequestBody())\n .gzip()\n .build(),\n ).execute()\n val responseBody = response.body\n assertThat(responseBody.string(), \"Expected response body to be valid\")\n .isEqualTo(\"Uncompressed\")\n responseBody.close()\n networkLogs\n .assertLogEqual(\"--> POST $url http/1.1\")\n .assertLogEqual(\"Content-Encoding: gzip\")\n .assertLogEqual(\"Transfer-Encoding: chunked\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"\")\n .assertLogEqual(\"--> END POST (12-byte, 32-gzipped-byte body)\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogMatch(Regex(\"\"\"C"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":616,"symbol":"bodyResponseGzipEncoded","kind":"function","lang":"kotlin","code":"@Test\n fun bodyResponseGzipEncoded() {\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder()\n .setHeader(\"Content-Encoding\", \"gzip\")\n .setHeader(\"Content-Type\", PLAIN)\n .body(Buffer().write(\"H4sIAAAAAAAAAPNIzcnJ11HwQKIAdyO+9hMAAAA=\".decodeBase64()!!))\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n val responseBody = response.body\n assertThat(responseBody.string(), \"Expected response body to be valid\")\n .isEqualTo(\"Hello, Hello, Hello\")\n responseBody.close()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Encoding: gzip\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogMatch(Regex(\"\"\"Content-Length: \\d+\"\"\"))\n .assertLogEqual(\"\")\n .assertLogEqual(\"Hello, Hello, Hello\")\n .assertLogMatch(Regex(\"\"\"<-- END H"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":658,"symbol":"bodyResponseUnknownEncoded","kind":"function","lang":"kotlin","code":"@Test\n fun bodyResponseUnknownEncoded() {\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder() // It's invalid to return this if not requested, but the server might anyway\n .setHeader(\"Content-Encoding\", \"br\")\n .setHeader(\"Content-Type\", PLAIN)\n .body(Buffer().write(\"iwmASGVsbG8sIEhlbGxvLCBIZWxsbwoD\".decodeBase64()!!))\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Encoding: br\")\n .assertLogEqual(\"Content-Type: text/plain; charset=utf-8\")\n .assertLogMatch(Regex(\"\"\"Content-Length: \\d+\"\"\"))\n .assertLogEqual(\"<-- END HTTP (encoded body omitted)\")\n .assertNoMoreLogs()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assert"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":695,"symbol":"bodyResponseIsStreaming","kind":"function","lang":"kotlin","code":"@Test\n fun bodyResponseIsStreaming() {\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder()\n .setHeader(\"Content-Type\", \"text/event-stream\")\n .chunkedBody(\n \"\"\"\n |event: add\n |data: 73857293\n |\n |event: remove\n |data: 2153\n |\n |event: add\n |data: 113411\n |\n |\n \"\"\".trimMargin(),\n 8,\n ).build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Type: text/event-stream\")\n .assertLogMatch(Regex(\"\"\"Transfer-encoding: chunked\"\"\"))\n .assertLogEqual(\"<-- END HTTP (streaming)\")\n .assertNoMoreLogs()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\""} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":742,"symbol":"bodyResponseIsUnreadable","kind":"function","lang":"kotlin","code":"@Test\n fun bodyResponseIsUnreadable() {\n setLevel(Level.BODY)\n val serverListener = object : WebSocketListener() {}\n server.enqueue(\n MockResponse\n .Builder()\n .webSocketUpgrade(serverListener)\n .build(),\n )\n val response =\n client\n .newCall(\n request()\n .header(\"Connection\", \"Upgrade\")\n .header(\"Upgrade\", \"websocket\")\n .header(\"Sec-WebSocket-Key\", \"abc123\")\n .build(),\n ).execute()\n response.body.close()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Connection: Upgrade\")\n .assertLogEqual(\"Upgrade: websocket\")\n .assertLogEqual(\"Sec-WebSocket-Key: abc123\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 101 Switching Protocols $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 0\")\n .assertLogEqual(\"Connection: Upgrade\")\n .assertLogEqual(\"Upgrade: websocket\")\n .assertLogMatch(Regex(\"\"\"Sec-WebSocket-Accept: .+\"\"\"))\n .assertLogEqual"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":793,"symbol":"bodyGetMalformedCharset","kind":"function","lang":"kotlin","code":"@Test\n fun bodyGetMalformedCharset() {\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder()\n .setHeader(\"Content-Type\", \"text/html; charset=0\")\n .body(\"Body with unknown charset\")\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogEqual(\"Accept-Encoding: gzip\")\n .assertLogMatch(Regex(\"\"\"User-Agent: okhttp/.+\"\"\"))\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Type: text/html; charset=0\")\n .assertLogMatch(Regex(\"\"\"Content-Length: \\d+\"\"\"))\n .assertLogMatch(Regex(\"\"))\n .assertLogEqual(\"Body with unknown charset\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 25-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Type: text/html; charse"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":831,"symbol":"responseBodyIsBinary","kind":"function","lang":"kotlin","code":"@Test\n fun responseBodyIsBinary() {\n setLevel(Level.BODY)\n val buffer = Buffer()\n buffer.writeUtf8CodePoint(0x89)\n buffer.writeUtf8CodePoint(0x50)\n buffer.writeUtf8CodePoint(0x4e)\n buffer.writeUtf8CodePoint(0x47)\n buffer.writeUtf8CodePoint(0x0d)\n buffer.writeUtf8CodePoint(0x0a)\n buffer.writeUtf8CodePoint(0x1a)\n buffer.writeUtf8CodePoint(0x0a)\n server.enqueue(\n MockResponse\n .Builder()\n .body(buffer)\n .setHeader(\"Content-Type\", \"image/png; charset=utf-8\")\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"Content-Length: 9\")\n .assertLogEqual(\"Content-Type: image/png; charset=utf-8\")\n .assertLogEqual(\"\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, binary 9-byte body omitted\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url http/1.1\")\n .assertLogEqual(\"Host: $host\")\n .assertLogEqual(\"Connection: Keep-Alive\")\n .assertLogE"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":876,"symbol":"connectFail","kind":"function","lang":"kotlin","code":"@Test\n fun connectFail() {\n setLevel(Level.BASIC)\n client =\n OkHttpClient\n .Builder()\n .dns { hostname: String? -> throw UnknownHostException(\"reason\") }\n .addInterceptor(applicationInterceptor)\n .build()\n try {\n client.newCall(request().build()).execute()\n fail()\n } catch (expected: UnknownHostException) {\n }\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogMatch(Regex(\"\"\"<-- HTTP FAILED: java.net.UnknownHostException: reason. $url \\(\\d+ms\\)\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":896,"symbol":"http2","kind":"function","lang":"kotlin","code":"@Test\n fun http2() {\n server.useHttps(handshakeCertificates.sslSocketFactory())\n url = server.url(\"/\")\n setLevel(Level.BASIC)\n server.enqueue(MockResponse())\n val response = client.newCall(request().build()).execute()\n Assumptions.assumeTrue(response.protocol == Protocol.HTTP_2)\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogMatch(Regex(\"\"\"<-- 200 $url \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n networkLogs\n .assertLogEqual(\"--> GET $url h2\")\n .assertLogMatch(Regex(\"\"\"<-- 200 $url \\(\\d+ms, 0-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":914,"symbol":"headersAreRedacted","kind":"function","lang":"kotlin","code":"@Test\n fun headersAreRedacted() {\n val networkInterceptor =\n HttpLoggingInterceptor(networkLogs).setLevel(\n Level.HEADERS,\n )\n networkInterceptor.redactHeader(\"sEnSiTiVe\")\n val applicationInterceptor =\n HttpLoggingInterceptor(applicationLogs).setLevel(\n Level.HEADERS,\n )\n applicationInterceptor.redactHeader(\"sEnSiTiVe\")\n client =\n OkHttpClient\n .Builder()\n .addNetworkInterceptor(networkInterceptor)\n .addInterceptor(applicationInterceptor)\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .addHeader(\"SeNsItIvE\", \"Value\")\n .addHeader(\"Not-Sensitive\", \"Value\")\n .build(),\n )\n val response =\n client\n .newCall(\n request()\n .addHeader(\"SeNsItIvE\", \"Value\")\n .addHeader(\"Not-Sensitive\", \"Value\")\n .build(),\n ).execute()\n response.body.close()\n applicationLogs\n .assertLogEqual(\"--> GET $url\")\n .assertLogEqual(\"SeNsItIvE: ██\")\n .assertLogEqual(\"Not-Sensitive: Value\")\n .assertLogEqual(\"--> END GET\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual("} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":976,"symbol":"sensitiveQueryParamsAreRedacted","kind":"function","lang":"kotlin","code":"@Test\n fun sensitiveQueryParamsAreRedacted() {\n url = server.url(\"/api/login?user=test_user&authentication=basic&password=confidential_password\")\n val networkInterceptor =\n HttpLoggingInterceptor(networkLogs).setLevel(\n Level.BASIC,\n )\n networkInterceptor.redactQueryParams(\"user\", \"passWord\")\n\n val applicationInterceptor =\n HttpLoggingInterceptor(applicationLogs).setLevel(\n Level.BASIC,\n )\n applicationInterceptor.redactQueryParams(\"user\", \"PassworD\")\n\n client =\n OkHttpClient\n .Builder()\n .addNetworkInterceptor(networkInterceptor)\n .addInterceptor(applicationInterceptor)\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .build(),\n )\n val response =\n client\n .newCall(\n request()\n .build(),\n ).execute()\n response.body.close()\n val redactedUrl = networkInterceptor.redactUrl(url)\n val redactedUrlPattern = redactedUrl.replace(\"?\", \"\"\"\\?\"\"\")\n applicationLogs\n .assertLogEqual(\"--> GET $redactedUrl\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $redactedUrlPattern \\(\\d+ms, \\d+-byte body\\)\"\"\"))\n .assertNoMoreLogs()\n "} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1021,"symbol":"preserveQueryParamsAfterRedacted","kind":"function","lang":"kotlin","code":"@Test\n fun preserveQueryParamsAfterRedacted() {\n url =\n server.url(\n \"\"\"/api/login?\n |user=test_user&\n |authentication=basic&\n |password=confidential_password&\n |authentication=rather simple login method\n \"\"\".trimMargin(),\n )\n val networkInterceptor =\n HttpLoggingInterceptor(networkLogs).setLevel(\n Level.BASIC,\n )\n networkInterceptor.redactQueryParams(\"user\", \"passWord\")\n\n val applicationInterceptor =\n HttpLoggingInterceptor(applicationLogs).setLevel(\n Level.BASIC,\n )\n applicationInterceptor.redactQueryParams(\"user\", \"PassworD\")\n\n client =\n OkHttpClient\n .Builder()\n .addNetworkInterceptor(networkInterceptor)\n .addInterceptor(applicationInterceptor)\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .build(),\n )\n val response =\n client\n .newCall(\n request()\n .build(),\n ).execute()\n response.body.close()\n val redactedUrl = networkInterceptor.redactUrl(url)\n val redactedUrlPattern = redactedUrl.replace(\"?\", \"\"\"\\?\"\"\")\n applicationLogs\n .assertLogEqual(\"--> GET $redactedUrl"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1074,"symbol":"duplexRequestsAreNotLogged","kind":"function","lang":"kotlin","code":"@Test\n fun duplexRequestsAreNotLogged() {\n platform.assumeHttp2Support()\n server.useHttps(handshakeCertificates.sslSocketFactory()) // HTTP/2\n url = server.url(\"/\")\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello response!\")\n .build(),\n )\n val asyncRequestBody: RequestBody =\n object : RequestBody() {\n override fun contentType(): MediaType? = null\n\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"Hello request!\")\n sink.close()\n }\n\n override fun isDuplex(): Boolean = true\n }\n val request =\n request()\n .post(asyncRequestBody)\n .build()\n val response = client.newCall(request).execute()\n Assumptions.assumeTrue(response.protocol == Protocol.HTTP_2)\n assertThat(response.body.string()).isEqualTo(\"Hello response!\")\n applicationLogs\n .assertLogEqual(\"--> POST $url\")\n .assertLogEqual(\"--> END POST (duplex request body omitted)\")\n .assertLogMatch(Regex(\"\"\"<-- 200 $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"content-length: 15\")\n .assertLogEqual(\"\")\n .assertLogEqual(\"Hello response!\")\n .as"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1088,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1090,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"Hello request!\")\n sink.close()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1095,"symbol":"isDuplex","kind":"function","lang":"kotlin","code":"override fun isDuplex(): Boolean = true"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1115,"symbol":"oneShotRequestsAreNotLogged","kind":"function","lang":"kotlin","code":"@Test\n fun oneShotRequestsAreNotLogged() {\n url = server.url(\"/\")\n setLevel(Level.BODY)\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello response!\")\n .build(),\n )\n val asyncRequestBody: RequestBody =\n object : RequestBody() {\n var counter = 0\n\n override fun contentType() = null\n\n override fun writeTo(sink: BufferedSink) {\n counter++\n assertThat(counter).isLessThanOrEqualTo(1)\n sink.writeUtf8(\"Hello request!\")\n sink.close()\n }\n\n override fun isOneShot() = true\n }\n val request =\n request()\n .post(asyncRequestBody)\n .build()\n val response = client.newCall(request).execute()\n assertThat(response.body.string()).isEqualTo(\"Hello response!\")\n applicationLogs\n .assertLogEqual(\"\"\"--> POST $url\"\"\")\n .assertLogEqual(\"\"\"--> END POST (one-shot body omitted)\"\"\")\n .assertLogMatch(Regex(\"\"\"<-- 200 OK $url \\(\\d+ms\\)\"\"\"))\n .assertLogEqual(\"\"\"Content-Length: 15\"\"\")\n .assertLogEqual(\"\")\n .assertLogEqual(\"\"\"Hello response!\"\"\")\n .assertLogMatch(Regex(\"\"\"<-- END HTTP \\(\\d+ms, 15-byte body\\)\"\"\"))\n .assertNo"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1129,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = null"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1131,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n counter++\n assertThat(counter).isLessThanOrEqualTo(1)\n sink.writeUtf8(\"Hello request!\")\n sink.close()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1138,"symbol":"isOneShot","kind":"function","lang":"kotlin","code":"override fun isOneShot() = true"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1157,"symbol":"request","kind":"function","lang":"kotlin","code":"private fun request(): Request.Builder = Request.Builder().url(url)"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1159,"symbol":"LogRecorder","kind":"class","lang":"kotlin","code":"internal class LogRecorder(\n val prefix: Regex = Regex(\"\"),\n ) : HttpLoggingInterceptor.Logger {\n private val logs = mutableListOf()\n private var index = 0\n\n fun assertLogEqual(expected: String) =\n apply {\n assertThat(index, \"No more messages found\")\n .isLessThan(logs.size)\n assertThat(logs[index++]).isEqualTo(expected)\n return this\n }\n\n fun assertLogMatch(regex: Regex) =\n apply {\n assertThat(index, \"No more messages found\")\n .isLessThan(logs.size)\n assertThat(logs[index++])\n .matches(Regex(prefix.pattern + regex.pattern, RegexOption.DOT_MATCHES_ALL))\n }\n\n fun assertNoMoreLogs() {\n assertThat(logs.size, \"More messages remain: ${logs.subList(index, logs.size)}\")\n .isEqualTo(index)\n }\n\n override fun log(message: String) {\n logs.add(message)\n }\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1165,"symbol":"assertLogEqual","kind":"function","lang":"kotlin","code":"fun assertLogEqual(expected: String) =\n apply {\n assertThat(index, \"No more messages found\")\n .isLessThan(logs.size)\n assertThat(logs[index++]).isEqualTo(expected)\n return this\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1173,"symbol":"assertLogMatch","kind":"function","lang":"kotlin","code":"fun assertLogMatch(regex: Regex) =\n apply {\n assertThat(index, \"No more messages found\")\n .isLessThan(logs.size)\n assertThat(logs[index++])\n .matches(Regex(prefix.pattern + regex.pattern, RegexOption.DOT_MATCHES_ALL))\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1181,"symbol":"assertNoMoreLogs","kind":"function","lang":"kotlin","code":"fun assertNoMoreLogs() {\n assertThat(logs.size, \"More messages remain: ${logs.subList(index, logs.size)}\")\n .isEqualTo(index)\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/HttpLoggingInterceptorTest.kt","line":1186,"symbol":"log","kind":"function","lang":"kotlin","code":"override fun log(message: String) {\n logs.add(message)\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":41,"symbol":"LoggingEventListenerTest","kind":"class","lang":"kotlin","code":"@Suppress(\"ktlint:standard:max-line-length\")\nclass LoggingEventListenerTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n @StartStop\n private val server = MockWebServer()\n\n private val handshakeCertificates = platform.localhostHandshakeCertificates()\n private val logRecorder =\n HttpLoggingInterceptorTest.LogRecorder(\n prefix = Regex(\"\"\"\\[\\d+ ms] \"\"\"),\n )\n private val loggingEventListenerFactory = LoggingEventListener.Factory(logRecorder)\n private lateinit var client: OkHttpClient\n private lateinit var url: HttpUrl\n\n @BeforeEach\n fun setUp() {\n client =\n clientTestRule\n .newClientBuilder()\n .eventListenerFactory(loggingEventListenerFactory)\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).retryOnConnectionFailure(false)\n .build()\n url = server.url(\"/\")\n }\n\n @Test\n fun get() {\n assumeNotWindows()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello!\")\n .setHeader(\"Content-Type\", PLAIN)\n .build(),\n )\n val response = clie"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":61,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n client =\n clientTestRule\n .newClientBuilder()\n .eventListenerFactory(loggingEventListenerFactory)\n .sslSocketFactory(\n handshakeCertificates.sslSocketFactory(),\n handshakeCertificates.trustManager,\n ).retryOnConnectionFailure(false)\n .build()\n url = server.url(\"/\")\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":75,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test\n fun get() {\n assumeNotWindows()\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"Hello!\")\n .setHeader(\"Content-Type\", PLAIN)\n .build(),\n )\n val response = client.newCall(request().build()).execute()\n assertThat(response.body).isNotNull()\n response.body.bytes()\n logRecorder\n .assertLogMatch(Regex(\"\"\"callStart: Request\\{method=GET, url=$url\\}\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectStart: $url\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectEnd: \\[DIRECT]\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsStart: ${url.host}\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsEnd: \\[.+]\"\"\"))\n .assertLogMatch(Regex(\"\"\"connectStart: ${url.host}/.+ DIRECT\"\"\"))\n .assertLogMatch(Regex(\"\"\"connectEnd: http/1.1\"\"\"))\n .assertLogMatch(\n Regex(\n \"\"\"connectionAcquired: Connection\\{${url.host}:\\d+, proxy=DIRECT hostAddress=${url.host}/.+ cipherSuite=none protocol=http/1\\.1\\}\"\"\",\n ),\n ).assertLogMatch(Regex(\"\"\"requestHeadersStart\"\"\"))\n .assertLogMatch(Regex(\"\"\"requestHeadersEnd\"\"\"))\n .assertLogMatch(Regex(\"\"\"responseHeadersStart\"\"\"))\n .assertLogMatch(Regex(\"\"\"responseHeadersEnd: Response\\{pro"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":111,"symbol":"post","kind":"function","lang":"kotlin","code":"@Test\n fun post() {\n assumeNotWindows()\n server.enqueue(MockResponse())\n client.newCall(request().post(\"Hello!\".toRequestBody(PLAIN)).build()).execute()\n logRecorder\n .assertLogMatch(Regex(\"\"\"callStart: Request\\{method=POST, url=$url\\}\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectStart: $url\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectEnd: \\[DIRECT]\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsStart: ${url.host}\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsEnd: \\[.+]\"\"\"))\n .assertLogMatch(Regex(\"\"\"connectStart: ${url.host}/.+ DIRECT\"\"\"))\n .assertLogMatch(Regex(\"\"\"connectEnd: http/1.1\"\"\"))\n .assertLogMatch(\n Regex(\n \"\"\"connectionAcquired: Connection\\{${url.host}:\\d+, proxy=DIRECT hostAddress=${url.host}/.+ cipherSuite=none protocol=http/1\\.1\\}\"\"\",\n ),\n ).assertLogMatch(Regex(\"\"\"requestHeadersStart\"\"\"))\n .assertLogMatch(Regex(\"\"\"requestHeadersEnd\"\"\"))\n .assertLogMatch(Regex(\"\"\"requestBodyStart\"\"\"))\n .assertLogMatch(Regex(\"\"\"requestBodyEnd: byteCount=6\"\"\"))\n .assertLogMatch(Regex(\"\"\"responseHeadersStart\"\"\"))\n .assertLogMatch(Regex(\"\"\"responseHeadersEnd: Response\\{protocol=http/1\\.1, code=200, message=OK, ur"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":141,"symbol":"secureGet","kind":"function","lang":"kotlin","code":"@Test\n fun secureGet() {\n assumeNotWindows()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n url = server.url(\"/\")\n server.enqueue(MockResponse())\n val response = client.newCall(request().build()).execute()\n assertThat(response.body).isNotNull()\n response.body.bytes()\n platform.assumeHttp2Support()\n logRecorder\n .assertLogMatch(Regex(\"\"\"callStart: Request\\{method=GET, url=$url\\}\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectStart: $url\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectEnd: \\[DIRECT]\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsStart: ${url.host}\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsEnd: \\[.+]\"\"\"))\n .assertLogMatch(Regex(\"\"\"connectStart: ${url.host}/.+ DIRECT\"\"\"))\n .assertLogMatch(Regex(\"\"\"secureConnectStart\"\"\"))\n .assertLogMatch(\n Regex(\n \"\"\"secureConnectEnd: Handshake\\{tlsVersion=TLS_1_[23] cipherSuite=TLS_.* peerCertificates=\\[CN=localhost] localCertificates=\\[]\\}\"\"\",\n ),\n ).assertLogMatch(Regex(\"\"\"connectEnd: h2\"\"\"))\n .assertLogMatch(\n Regex(\"\"\"connectionAcquired: Connection\\{${url.host}:\\d+, proxy=DIRECT hostAddress=${url.host}/.+ cipherSuite=.+ protocol=h2\\}\"\"\"),\n "} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":177,"symbol":"dnsFail","kind":"function","lang":"kotlin","code":"@Test\n fun dnsFail() {\n client =\n OkHttpClient\n .Builder()\n .dns { _ -> throw UnknownHostException(\"reason\") }\n .eventListenerFactory(loggingEventListenerFactory)\n .build()\n try {\n client.newCall(request().build()).execute()\n fail()\n } catch (expected: UnknownHostException) {\n }\n logRecorder\n .assertLogMatch(Regex(\"\"\"callStart: Request\\{method=GET, url=$url\\}\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectStart: $url\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectEnd: \\[DIRECT]\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsStart: ${url.host}\"\"\"))\n .assertLogMatch(Regex(\"\"\"callFailed: java.net.UnknownHostException: reason\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":199,"symbol":"connectFail","kind":"function","lang":"kotlin","code":"@Test\n fun connectFail() {\n assumeNotWindows()\n server.useHttps(handshakeCertificates.sslSocketFactory())\n server.protocols = Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)\n server.enqueue(\n MockResponse\n .Builder()\n .failHandshake()\n .build(),\n )\n url = server.url(\"/\")\n try {\n client.newCall(request().build()).execute()\n fail()\n } catch (expected: IOException) {\n }\n logRecorder\n .assertLogMatch(Regex(\"\"\"callStart: Request\\{method=GET, url=$url\\}\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectStart: $url\"\"\"))\n .assertLogMatch(Regex(\"\"\"proxySelectEnd: \\[DIRECT]\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsStart: ${url.host}\"\"\"))\n .assertLogMatch(Regex(\"\"\"dnsEnd: \\[.+]\"\"\"))\n .assertLogMatch(Regex(\"\"\"connectStart: ${url.host}/.+ DIRECT\"\"\"))\n .assertLogMatch(Regex(\"\"\"secureConnectStart\"\"\"))\n .assertLogMatch(\n Regex(\n \"\"\"connectFailed: null \\S+(?:SSLProtocolException|SSLHandshakeException|TlsFatalAlert): .*(?:Unexpected handshake message: client_hello|Handshake message sequence violation, 1|Read error|Handshake failed|unexpected_message\\(10\\)).*\"\"\",\n ),\n ).asser"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":235,"symbol":"testCacheEvents","kind":"function","lang":"kotlin","code":"@Test\n fun testCacheEvents() {\n val request = Request.Builder().url(url).build()\n val call = client.newCall(request)\n val response =\n Response\n .Builder()\n .request(request)\n .code(200)\n .message(\"\")\n .protocol(Protocol.HTTP_2)\n .build()\n val listener = loggingEventListenerFactory.create(call)\n listener.cacheConditionalHit(call, response)\n listener.cacheHit(call, response)\n listener.cacheMiss(call)\n listener.satisfactionFailure(call, response)\n logRecorder\n .assertLogMatch(Regex(\"\"\"cacheConditionalHit: Response\\{protocol=h2, code=200, message=, url=$url\\}\"\"\"))\n .assertLogMatch(Regex(\"\"\"cacheHit: Response\\{protocol=h2, code=200, message=, url=$url\\}\"\"\"))\n .assertLogMatch(Regex(\"\"\"cacheMiss\"\"\"))\n .assertLogMatch(Regex(\"\"\"satisfactionFailure: Response\\{protocol=h2, code=200, message=, url=$url\\}\"\"\"))\n .assertNoMoreLogs()\n }"} {"repo":"okhttp","file":"okhttp-logging-interceptor/src/test/java/okhttp3/logging/LoggingEventListenerTest.kt","line":260,"symbol":"request","kind":"function","lang":"kotlin","code":"private fun request(): Request.Builder = Request.Builder().url(url)"} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":33,"symbol":"OsgiTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slow\")\nclass OsgiTest {\n private lateinit var testResourceDir: Path\n private lateinit var workspaceDir: Path\n\n @BeforeEach\n fun setUp() {\n testResourceDir = \"./build/resources/test/okhttp3/osgi\".toPath()\n workspaceDir = testResourceDir / \"workspace\"\n\n // Ensure we start from scratch.\n fileSystem.deleteRecursively(workspaceDir)\n fileSystem.createDirectories(workspaceDir)\n }\n\n /**\n * Resolve the OSGi metadata of the all okhttp3 modules. If required modules do not have OSGi\n * metadata this will fail with an exception.\n */\n @Test\n fun testMainModuleWithSiblings() {\n createWorkspace().use { workspace ->\n createBndRun(workspace).use { bndRun ->\n bndRun.resolve(\n false,\n false,\n )\n }\n }\n }\n\n private fun createWorkspace(): Workspace {\n val bndDir = workspaceDir / \"cnf\"\n val repoDir = bndDir / \"repo\"\n fileSystem.createDirectories(repoDir)\n return Workspace(workspaceDir.toFile(), bndDir.name)\n .apply {\n setProperty(\n \"${Constants.PLUGIN}.$REPO_NAME\",\n LocalIndexedRepo::class.java.getName() +\n \"; ${LocalIndexedRepo.PROP_NAME} = '$REPO_NAME'\" +\n "} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":38,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach\n fun setUp() {\n testResourceDir = \"./build/resources/test/okhttp3/osgi\".toPath()\n workspaceDir = testResourceDir / \"workspace\"\n\n // Ensure we start from scratch.\n fileSystem.deleteRecursively(workspaceDir)\n fileSystem.createDirectories(workspaceDir)\n }"} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":52,"symbol":"testMainModuleWithSiblings","kind":"function","lang":"kotlin","doc":"Resolve the OSGi metadata of the all okhttp3 modules. If required modules do not have OSGi metadata this will fail with an exception.","code":"@Test\n fun testMainModuleWithSiblings() {\n createWorkspace().use { workspace ->\n createBndRun(workspace).use { bndRun ->\n bndRun.resolve(\n false,\n false,\n )\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":64,"symbol":"createWorkspace","kind":"function","lang":"kotlin","code":"private fun createWorkspace(): Workspace {\n val bndDir = workspaceDir / \"cnf\"\n val repoDir = bndDir / \"repo\"\n fileSystem.createDirectories(repoDir)\n return Workspace(workspaceDir.toFile(), bndDir.name)\n .apply {\n setProperty(\n \"${Constants.PLUGIN}.$REPO_NAME\",\n LocalIndexedRepo::class.java.getName() +\n \"; ${LocalIndexedRepo.PROP_NAME} = '$REPO_NAME'\" +\n \"; ${LocalIndexedRepo.PROP_LOCAL_DIR} = '$repoDir'\",\n )\n refresh()\n prepareWorkspace()\n }\n }"} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":81,"symbol":"prepareWorkspace","kind":"function","lang":"kotlin","code":"private fun Workspace.prepareWorkspace() {\n val repositoryPlugin = getRepository(REPO_NAME)\n\n // Deploy the bundles in the deployments test directory.\n repositoryPlugin.deployDirectory(testResourceDir / \"deployments\")\n repositoryPlugin.deployClassPath()\n }"} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":89,"symbol":"createBndRun","kind":"function","lang":"kotlin","code":"private fun createBndRun(workspace: Workspace): Bndrun {\n // Creating the run require string. It will always use the latest version of each bundle\n // available in the repository.\n val runRequireString =\n REQUIRED_BUNDLES.joinToString(separator = \",\") {\n \"osgi.identity;filter:='(osgi.identity=$it)'\"\n }\n\n val bndEditModel =\n BndEditModel(workspace).apply {\n // Temporary project to satisfy bnd API.\n project = Project(workspace, workspaceDir.toFile())\n }\n\n return Bndrun(bndEditModel).apply {\n setRunfw(RESOLVE_OSGI_FRAMEWORK)\n runee = RESOLVE_JAVA_VERSION\n setRunRequires(runRequireString)\n }\n }"} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":110,"symbol":"deployDirectory","kind":"function","lang":"kotlin","code":"private fun RepositoryPlugin.deployDirectory(directory: Path) {\n for (path in fileSystem.list(directory)) {\n deployFile(path)\n }\n }"} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":116,"symbol":"deployClassPath","kind":"function","lang":"kotlin","code":"private fun RepositoryPlugin.deployClassPath() {\n val classpath = System.getProperty(\"java.class.path\")\n val entries =\n classpath\n .split(File.pathSeparator.toRegex())\n .dropLastWhile { it.isEmpty() }\n .toTypedArray()\n for (classPathEntry in entries) {\n deployFile(classPathEntry.toPath())\n }\n }"} {"repo":"okhttp","file":"okhttp-osgi-tests/src/test/kotlin/okhttp3/osgi/OsgiTest.kt","line":128,"symbol":"deployFile","kind":"function","lang":"kotlin","code":"private fun RepositoryPlugin.deployFile(file: Path) {\n if (fileSystem.metadataOrNull(file)?.isRegularFile != true) return\n try {\n fileSystem.read(file) {\n put(inputStream(), RepositoryPlugin.PutOptions())\n println(\"Deployed ${file.name}\")\n }\n } catch (e: IllegalArgumentException) {\n if (\"Jar does not have a symbolic name\" in e.message!!) {\n println(\"Skipped non-OSGi dependency: ${file.name}\")\n return\n }\n throw e\n }\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSource.kt","line":20,"symbol":"EventSource","kind":"interface","lang":"kotlin","code":"interface EventSource {\n /** Returns the original request that initiated this event source. */\n fun request(): Request\n\n /**\n * Immediately and violently release resources held by this event source. This does nothing if\n * the event source has already been closed or canceled.\n */\n fun cancel()\n\n fun interface Factory {\n /**\n * Creates a new event source and immediately returns it. Creating an event source initiates an\n * asynchronous process to connect the socket. Once that succeeds or fails, `listener` will be\n * notified. The caller must cancel the returned event source when it is no longer in use.\n */\n fun newEventSource(\n request: Request,\n listener: EventSourceListener,\n ): EventSource\n }\n}"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSource.kt","line":22,"symbol":"request","kind":"function","lang":"kotlin","doc":"Returns the original request that initiated this event source.","code":"fun request(): Request"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSource.kt","line":28,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"Immediately and violently release resources held by this event source. This does nothing if the event source has already been closed or canceled.","code":"fun cancel()"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSource.kt","line":30,"symbol":"Factory","kind":"interface","lang":"kotlin","code":"fun interface Factory {\n /**\n * Creates a new event source and immediately returns it. Creating an event source initiates an\n * asynchronous process to connect the socket. Once that succeeds or fails, `listener` will be\n * notified. The caller must cancel the returned event source when it is no longer in use.\n */\n fun newEventSource(\n request: Request,\n listener: EventSourceListener,\n ): EventSource\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSource.kt","line":36,"symbol":"newEventSource","kind":"function","lang":"kotlin","doc":"Creates a new event source and immediately returns it. Creating an event source initiates an asynchronous process to connect the socket. Once that succeeds or fails, `listener` will be notified. The caller must cancel the returned event source when it is no longer in use.","code":"fun newEventSource(\n request: Request,\n listener: EventSourceListener,\n ): EventSource"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSourceListener.kt","line":20,"symbol":"EventSourceListener","kind":"class","lang":"kotlin","code":"abstract class EventSourceListener {\n /**\n * Invoked when an event source has been accepted by the remote peer and may begin transmitting\n * events.\n */\n open fun onOpen(\n eventSource: EventSource,\n response: Response,\n ) {\n }\n\n open fun onEvent(\n eventSource: EventSource,\n id: String?,\n type: String?,\n data: String,\n ) {\n }\n\n /**\n * No further calls to this listener will be made.\n */\n open fun onClosed(eventSource: EventSource) {\n }\n\n /**\n * Invoked when an event source has been closed due to an error reading from or writing to the\n * network. Incoming events may have been lost. No further calls to this listener will be made.\n */\n open fun onFailure(\n eventSource: EventSource,\n t: Throwable?,\n response: Response?,\n ) {\n }\n}"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSourceListener.kt","line":25,"symbol":"onOpen","kind":"function","lang":"kotlin","doc":"Invoked when an event source has been accepted by the remote peer and may begin transmitting events.","code":"open fun onOpen(\n eventSource: EventSource,\n response: Response,\n ) {\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSourceListener.kt","line":31,"symbol":"onEvent","kind":"function","lang":"kotlin","code":"open fun onEvent(\n eventSource: EventSource,\n id: String?,\n type: String?,\n data: String,\n ) {\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSourceListener.kt","line":42,"symbol":"onClosed","kind":"function","lang":"kotlin","doc":"No further calls to this listener will be made.","code":"open fun onClosed(eventSource: EventSource) {\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSourceListener.kt","line":49,"symbol":"onFailure","kind":"function","lang":"kotlin","doc":"Invoked when an event source has been closed due to an error reading from or writing to the network. Incoming events may have been lost. No further calls to this listener will be made.","code":"open fun onFailure(\n eventSource: EventSource,\n t: Throwable?,\n response: Response?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSources.kt","line":23,"symbol":"EventSources","kind":"object","lang":"kotlin","code":"object EventSources {\n @Deprecated(\n message = \"required for binary-compatibility!\",\n level = DeprecationLevel.HIDDEN,\n )\n @JvmStatic\n fun createFactory(client: OkHttpClient) = createFactory(client as Call.Factory)\n\n @JvmStatic\n fun createFactory(callFactory: Call.Factory): EventSource.Factory =\n EventSource.Factory { request, listener ->\n val actualRequest =\n if (request.header(\"Accept\") == null) {\n request.newBuilder().addHeader(\"Accept\", \"text/event-stream\").build()\n } else {\n request\n }\n\n RealEventSource(actualRequest, listener).apply {\n connect(callFactory)\n }\n }\n\n @JvmStatic\n fun processResponse(\n response: Response,\n listener: EventSourceListener,\n ) {\n val eventSource = RealEventSource(response.request, listener)\n eventSource.processResponse(response)\n }\n}"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSources.kt","line":24,"symbol":"createFactory","kind":"function","lang":"kotlin","code":"@Deprecated(\n message = \"required for binary-compatibility!\",\n level = DeprecationLevel.HIDDEN,\n )\n @JvmStatic\n fun createFactory(client: OkHttpClient) = createFactory(client as Call.Factory)"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSources.kt","line":31,"symbol":"createFactory","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun createFactory(callFactory: Call.Factory): EventSource.Factory =\n EventSource.Factory { request, listener ->\n val actualRequest =\n if (request.header(\"Accept\") == null) {\n request.newBuilder().addHeader(\"Accept\", \"text/event-stream\").build()\n } else {\n request\n }\n\n RealEventSource(actualRequest, listener).apply {\n connect(callFactory)\n }\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/EventSources.kt","line":46,"symbol":"processResponse","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun processResponse(\n response: Response,\n listener: EventSourceListener,\n ) {\n val eventSource = RealEventSource(response.request, listener)\n eventSource.processResponse(response)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":28,"symbol":"RealEventSource","kind":"class","lang":"kotlin","code":"internal class RealEventSource(\n private val request: Request,\n private val listener: EventSourceListener,\n) : EventSource,\n ServerSentEventReader.Callback,\n Callback {\n private var call: Call? = null\n\n @Volatile private var canceled = false\n\n fun connect(callFactory: Call.Factory) {\n call =\n callFactory.newCall(request).apply {\n enqueue(this@RealEventSource)\n }\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n processResponse(response)\n }\n\n fun processResponse(response: Response) {\n response.use {\n if (!response.isSuccessful) {\n listener.onFailure(this, null, response)\n return\n }\n\n val body = response.body\n\n if (!body.isEventStream()) {\n listener.onFailure(\n this,\n IllegalStateException(\"Invalid content-type: ${body.contentType()}\"),\n response,\n )\n return\n }\n\n // This is a long-lived response. Cancel full-call timeouts.\n call?.timeout()?.cancel()\n\n // Replace the body with a stripped one so the callbacks can't see real data.\n val response = response.stripBody()\n\n val reader = ServerSentEventReader(body.sourc"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":38,"symbol":"connect","kind":"function","lang":"kotlin","code":"fun connect(callFactory: Call.Factory) {\n call =\n callFactory.newCall(request).apply {\n enqueue(this@RealEventSource)\n }\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":45,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n processResponse(response)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":52,"symbol":"processResponse","kind":"function","lang":"kotlin","code":"fun processResponse(response: Response) {\n response.use {\n if (!response.isSuccessful) {\n listener.onFailure(this, null, response)\n return\n }\n\n val body = response.body\n\n if (!body.isEventStream()) {\n listener.onFailure(\n this,\n IllegalStateException(\"Invalid content-type: ${body.contentType()}\"),\n response,\n )\n return\n }\n\n // This is a long-lived response. Cancel full-call timeouts.\n call?.timeout()?.cancel()\n\n // Replace the body with a stripped one so the callbacks can't see real data.\n val response = response.stripBody()\n\n val reader = ServerSentEventReader(body.source(), this)\n try {\n if (!canceled) {\n listener.onOpen(this, response)\n while (!canceled && reader.processNextEvent()) {\n }\n }\n } catch (e: Exception) {\n val exception =\n when {\n canceled -> IOException(\"canceled\", e)\n else -> e\n }\n listener.onFailure(this, exception, response)\n return\n }\n if (canceled) {\n listener.onFailure(this, IOException(\"canceled\"), response)\n } else"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":100,"symbol":"isEventStream","kind":"function","lang":"kotlin","code":"private fun ResponseBody.isEventStream(): Boolean {\n val contentType = contentType() ?: return false\n return contentType.type == \"text\" && contentType.subtype == \"event-stream\"\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":105,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n listener.onFailure(this, e, null)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":112,"symbol":"request","kind":"function","lang":"kotlin","code":"override fun request(): Request = request"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":114,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel() {\n canceled = true\n call?.cancel()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":119,"symbol":"onEvent","kind":"function","lang":"kotlin","code":"override fun onEvent(\n id: String?,\n type: String?,\n data: String,\n ) {\n listener.onEvent(this, id, type, data)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt","line":127,"symbol":"onRetryChange","kind":"function","lang":"kotlin","code":"override fun onRetryChange(timeMs: Long) {\n // Ignored. We do not auto-retry.\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/ServerSentEventReader.kt","line":25,"symbol":"ServerSentEventReader","kind":"class","lang":"kotlin","code":"class ServerSentEventReader(\n private val source: BufferedSource,\n private val callback: Callback,\n) {\n private var lastId: String? = null\n\n interface Callback {\n fun onEvent(\n id: String?,\n type: String?,\n data: String,\n )\n\n fun onRetryChange(timeMs: Long)\n }\n\n /**\n * Process the next event. This will result in a single call to [Callback.onEvent] *unless* the\n * data section was empty. Any number of calls to [Callback.onRetryChange] may occur while\n * processing an event.\n *\n * @return false when EOF is reached\n */\n @Throws(IOException::class)\n fun processNextEvent(): Boolean {\n var id = lastId\n var type: String? = null\n val data = Buffer()\n\n while (true) {\n when (source.select(options)) {\n in 0..2 -> {\n completeEvent(id, type, data)\n return true\n }\n\n in 3..4 -> {\n source.readData(data)\n }\n\n in 5..7 -> {\n data.writeByte('\\n'.code) // 'data' on a line of its own.\n }\n\n in 8..9 -> {\n id = source.readUtf8LineStrict().takeIf { it.isNotEmpty() }\n }\n\n in 10..12 -> {\n id = null // 'id' on a line of its own.\n "} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/ServerSentEventReader.kt","line":31,"symbol":"Callback","kind":"interface","lang":"kotlin","code":"interface Callback {\n fun onEvent(\n id: String?,\n type: String?,\n data: String,\n )\n\n fun onRetryChange(timeMs: Long)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/ServerSentEventReader.kt","line":32,"symbol":"onEvent","kind":"function","lang":"kotlin","code":"fun onEvent(\n id: String?,\n type: String?,\n data: String,\n )"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/ServerSentEventReader.kt","line":38,"symbol":"onRetryChange","kind":"function","lang":"kotlin","code":"fun onRetryChange(timeMs: Long)"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/ServerSentEventReader.kt","line":48,"symbol":"processNextEvent","kind":"function","lang":"kotlin","doc":"Process the next event. This will result in a single call to [Callback.onEvent] *unless* the data section was empty. Any number of calls to [Callback.onRetryChange] may occur while processing an event. @return false when EOF is reached","code":"@Throws(IOException::class)\n fun processNextEvent(): Boolean {\n var id = lastId\n var type: String? = null\n val data = Buffer()\n\n while (true) {\n when (source.select(options)) {\n in 0..2 -> {\n completeEvent(id, type, data)\n return true\n }\n\n in 3..4 -> {\n source.readData(data)\n }\n\n in 5..7 -> {\n data.writeByte('\\n'.code) // 'data' on a line of its own.\n }\n\n in 8..9 -> {\n id = source.readUtf8LineStrict().takeIf { it.isNotEmpty() }\n }\n\n in 10..12 -> {\n id = null // 'id' on a line of its own.\n }\n\n in 13..14 -> {\n type = source.readUtf8LineStrict().takeIf { it.isNotEmpty() }\n }\n\n in 15..17 -> {\n type = null // 'event' on a line of its own\n }\n\n in 18..19 -> {\n val retryMs = source.readRetryMs()\n if (retryMs != -1L) {\n callback.onRetryChange(retryMs)\n }\n }\n\n -1 -> {\n val lineEnd = source.indexOfElement(CRLF)\n if (lineEnd != -1L) {\n // Skip the line and newline\n source.skip(lineEnd)\n source.select("} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/ServerSentEventReader.kt","line":110,"symbol":"completeEvent","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun completeEvent(\n id: String?,\n type: String?,\n data: Buffer,\n ) {\n if (data.size != 0L) {\n lastId = id\n data.skip(1L) // Leading newline.\n callback.onEvent(id, type, data.readUtf8())\n }\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/ServerSentEventReader.kt","line":170,"symbol":"readData","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun BufferedSource.readData(data: Buffer) {\n data.writeByte('\\n'.code)\n readFully(data, indexOfElement(CRLF))\n select(options) // Skip the newline bytes.\n }"} {"repo":"okhttp","file":"okhttp-sse/src/main/kotlin/okhttp3/sse/internal/ServerSentEventReader.kt","line":177,"symbol":"readRetryMs","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n private fun BufferedSource.readRetryMs(): Long {\n val retryString = readUtf8LineStrict()\n return retryString.toLongOrDefault(-1L)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":55,"symbol":"EventSourceHttpTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass EventSourceHttpTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n private val eventRecorder = EventRecorder()\n private val listener = EventSourceRecorder()\n private var client =\n clientTestRule\n .newClientBuilder()\n .eventListenerFactory(clientTestRule.wrap(eventRecorder))\n .build()\n\n @AfterEach\n fun after() {\n listener.assertExhausted()\n }\n\n @Test\n fun event() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n val source = newEventSource()\n assertThat(source.request().url.encodedPath).isEqualTo(\"/\")\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n }\n\n @RetryingTest(5)\n fun cancelInEventShortCircuits() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargi"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":73,"symbol":"after","kind":"function","lang":"kotlin","code":"@AfterEach\n fun after() {\n listener.assertExhausted()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":78,"symbol":"event","kind":"function","lang":"kotlin","code":"@Test\n fun event() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n val source = newEventSource()\n assertThat(source.request().url.encodedPath).isEqualTo(\"/\")\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":99,"symbol":"cancelInEventShortCircuits","kind":"function","lang":"kotlin","code":"@RetryingTest(5)\n fun cancelInEventShortCircuits() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n listener.enqueueCancel() // Will cancel in onOpen().\n newEventSource()\n listener.assertOpen()\n listener.assertFailure(\"canceled\")\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":119,"symbol":"badContentType","kind":"function","lang":"kotlin","code":"@Test\n fun badContentType() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/plain\")\n .build(),\n )\n newEventSource()\n listener.assertFailure(\"Invalid content-type: text/plain\")\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":137,"symbol":"badResponseCode","kind":"function","lang":"kotlin","code":"@Test\n fun badResponseCode() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .code(401)\n .build(),\n )\n newEventSource()\n listener.assertFailure(null)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":156,"symbol":"fullCallTimeoutDoesNotApplyOnceConnected","kind":"function","lang":"kotlin","code":"@Test\n fun fullCallTimeoutDoesNotApplyOnceConnected() {\n client =\n client\n .newBuilder()\n .callTimeout(250, TimeUnit.MILLISECONDS)\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .bodyDelay(500, TimeUnit.MILLISECONDS)\n .setHeader(\"content-type\", \"text/event-stream\")\n .body(\"data: hey\\n\\n\")\n .build(),\n )\n val source = newEventSource()\n assertThat(source.request().url.encodedPath).isEqualTo(\"/\")\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":178,"symbol":"fullCallTimeoutAppliesToSetup","kind":"function","lang":"kotlin","code":"@Test\n fun fullCallTimeoutAppliesToSetup() {\n client =\n client\n .newBuilder()\n .callTimeout(250, TimeUnit.MILLISECONDS)\n .build()\n server.enqueue(\n MockResponse\n .Builder()\n .headersDelay(500, TimeUnit.MILLISECONDS)\n .setHeader(\"content-type\", \"text/event-stream\")\n .body(\"data: hey\\n\\n\")\n .build(),\n )\n newEventSource()\n listener.assertFailure(\"timeout\")\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":197,"symbol":"retainsAccept","kind":"function","lang":"kotlin","code":"@Test\n fun retainsAccept() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n newEventSource(\"text/plain\")\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n assertThat(server.takeRequest().headers[\"Accept\"]).isEqualTo(\"text/plain\")\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":218,"symbol":"setsMissingAccept","kind":"function","lang":"kotlin","code":"@Test\n fun setsMissingAccept() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n newEventSource()\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n assertThat(server.takeRequest().headers[\"Accept\"])\n .isEqualTo(\"text/event-stream\")\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":240,"symbol":"eventListenerEvents","kind":"function","lang":"kotlin","code":"@Test\n fun eventListenerEvents() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n val source = newEventSource()\n assertThat(source.request().url.encodedPath).isEqualTo(\"/\")\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n assertThat(eventRecorder.recordedEventTypes()).containsExactly(\n CallStart::class,\n ProxySelectStart::class,\n ProxySelectEnd::class,\n DnsStart::class,\n DnsEnd::class,\n ConnectStart::class,\n ConnectEnd::class,\n ConnectionAcquired::class,\n RequestHeadersStart::class,\n RequestHeadersEnd::class,\n ResponseHeadersStart::class,\n ResponseHeadersEnd::class,\n FollowUpDecision::class,\n ResponseBodyStart::class,\n ResponseBodyEnd::class,\n ConnectionReleased::class,\n CallEnd::class,\n )\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":280,"symbol":"sseReauths","kind":"function","lang":"kotlin","code":"@Test\n fun sseReauths() {\n client =\n client\n .newBuilder()\n .authenticator { route, response ->\n response.request\n .newBuilder()\n .header(\"Authorization\", \"XYZ\")\n .build()\n }.build()\n server.enqueue(\n MockResponse(\n code = 401,\n body = \"{\\\"error\\\":{\\\"message\\\":\\\"No auth credentials found\\\",\\\"code\\\":401}}\",\n headers = Headers.headersOf(\"content-type\", \"application/json\"),\n ),\n )\n server.enqueue(\n MockResponse(\n body =\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n headers = Headers.headersOf(\"content-type\", \"text/event-stream\"),\n ),\n )\n val source = newEventSource()\n assertThat(source.request().url.encodedPath).isEqualTo(\"/\")\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":316,"symbol":"sseWithoutAuthenticator","kind":"function","lang":"kotlin","code":"@Test\n fun sseWithoutAuthenticator() {\n server.enqueue(\n MockResponse(\n code = 401,\n body = \"{\\\"error\\\":{\\\"message\\\":\\\"No auth credentials found\\\",\\\"code\\\":401}}\",\n headers = Headers.headersOf(\"content-type\", \"application/json\"),\n ),\n )\n val source = newEventSource()\n assertThat(source.request().url.encodedPath).isEqualTo(\"/\")\n listener.assertFailure(code = 401, message = \"{\\\"error\\\":{\\\"message\\\":\\\"No auth credentials found\\\",\\\"code\\\":401}}"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceHttpTest.kt","line":330,"symbol":"newEventSource","kind":"function","lang":"kotlin","code":"private fun newEventSource(accept: String? = null): EventSource {\n val builder =\n Request\n .Builder()\n .url(server.url(\"/\"))\n if (accept != null) {\n builder.header(\"Accept\", accept)\n }\n val request = builder.build()\n val factory = createFactory(client)\n return factory.newEventSource(request, listener)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":30,"symbol":"EventSourceRecorder","kind":"class","lang":"kotlin","code":"class EventSourceRecorder : EventSourceListener() {\n private val events = LinkedBlockingDeque()\n private var cancel = false\n\n fun enqueueCancel() {\n cancel = true\n }\n\n override fun onOpen(\n eventSource: EventSource,\n response: Response,\n ) {\n get().log(\"[ES] onOpen\", Platform.INFO, null)\n events.add(Open(eventSource, response))\n drainCancelQueue(eventSource)\n }\n\n override fun onEvent(\n eventSource: EventSource,\n id: String?,\n type: String?,\n data: String,\n ) {\n get().log(\"[ES] onEvent\", Platform.INFO, null)\n events.add(Event(id, type, data))\n drainCancelQueue(eventSource)\n }\n\n override fun onClosed(eventSource: EventSource) {\n get().log(\"[ES] onClosed\", Platform.INFO, null)\n events.add(Closed)\n drainCancelQueue(eventSource)\n }\n\n override fun onFailure(\n eventSource: EventSource,\n t: Throwable?,\n response: Response?,\n ) {\n get().log(\"[ES] onFailure\", Platform.INFO, t)\n events.add(Failure(t, response, t?.message ?: response?.body?.string()))\n drainCancelQueue(eventSource)\n }\n\n private fun drainCancelQueue(eventSource: EventSource) {\n if (cancel) {\n cancel = false\n eventSource.cancel()\n"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":34,"symbol":"enqueueCancel","kind":"function","lang":"kotlin","code":"fun enqueueCancel() {\n cancel = true\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":38,"symbol":"onOpen","kind":"function","lang":"kotlin","code":"override fun onOpen(\n eventSource: EventSource,\n response: Response,\n ) {\n get().log(\"[ES] onOpen\", Platform.INFO, null)\n events.add(Open(eventSource, response))\n drainCancelQueue(eventSource)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":47,"symbol":"onEvent","kind":"function","lang":"kotlin","code":"override fun onEvent(\n eventSource: EventSource,\n id: String?,\n type: String?,\n data: String,\n ) {\n get().log(\"[ES] onEvent\", Platform.INFO, null)\n events.add(Event(id, type, data))\n drainCancelQueue(eventSource)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":58,"symbol":"onClosed","kind":"function","lang":"kotlin","code":"override fun onClosed(eventSource: EventSource) {\n get().log(\"[ES] onClosed\", Platform.INFO, null)\n events.add(Closed)\n drainCancelQueue(eventSource)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":64,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n eventSource: EventSource,\n t: Throwable?,\n response: Response?,\n ) {\n get().log(\"[ES] onFailure\", Platform.INFO, t)\n events.add(Failure(t, response, t?.message ?: response?.body?.string()))\n drainCancelQueue(eventSource)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":74,"symbol":"drainCancelQueue","kind":"function","lang":"kotlin","code":"private fun drainCancelQueue(eventSource: EventSource) {\n if (cancel) {\n cancel = false\n eventSource.cancel()\n }\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":81,"symbol":"nextEvent","kind":"function","lang":"kotlin","code":"private fun nextEvent(): Any =\n events.poll(10, TimeUnit.SECONDS)\n ?: throw AssertionError(\"Timed out waiting for event.\")"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":85,"symbol":"assertExhausted","kind":"function","lang":"kotlin","code":"fun assertExhausted() {\n assertThat(events).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":89,"symbol":"assertEvent","kind":"function","lang":"kotlin","code":"fun assertEvent(\n id: String?,\n type: String?,\n data: String,\n ) {\n assertThat(nextEvent()).isEqualTo(Event(id, type, data))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":97,"symbol":"assertOpen","kind":"function","lang":"kotlin","code":"fun assertOpen(): EventSource {\n val event = nextEvent() as Open\n return event.eventSource\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":102,"symbol":"assertClose","kind":"function","lang":"kotlin","code":"fun assertClose() {\n nextEvent() as Closed\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":106,"symbol":"assertFailure","kind":"function","lang":"kotlin","code":"fun assertFailure(\n message: String?,\n code: Int? = null,\n ) {\n val event = nextEvent() as Failure\n if (code != null) {\n assertThat(event.response?.code).isEqualTo(code)\n }\n if (message != null) {\n assertThat(event.message).isEqualTo(message)\n } else {\n assertThat(event.t).isNull()\n }\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourceRecorder.kt","line":132,"symbol":"Closed","kind":"object","lang":"kotlin","code":"internal object Closed"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourcesHttpTest.kt","line":33,"symbol":"EventSourcesHttpTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass EventSourcesHttpTest {\n @RegisterExtension\n val platform = PlatformRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @RegisterExtension\n val clientTestRule = OkHttpClientTestRule()\n\n private val listener = EventSourceRecorder()\n private val client = clientTestRule.newClient()\n\n @AfterEach\n fun after() {\n listener.assertExhausted()\n }\n\n @Test\n fun processResponse() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n val request = Request.Builder().url(server.url(\"/\")).build()\n val response = client.newCall(request).execute()\n processResponse(response, listener)\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n }\n\n @Test\n fun cancelShortCircuits() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n "} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourcesHttpTest.kt","line":47,"symbol":"after","kind":"function","lang":"kotlin","code":"@AfterEach\n fun after() {\n listener.assertExhausted()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourcesHttpTest.kt","line":52,"symbol":"processResponse","kind":"function","lang":"kotlin","code":"@Test\n fun processResponse() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n val request = Request.Builder().url(server.url(\"/\")).build()\n val response = client.newCall(request).execute()\n processResponse(response, listener)\n listener.assertOpen()\n listener.assertEvent(null, null, \"hey\")\n listener.assertClose()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourcesHttpTest.kt","line":74,"symbol":"cancelShortCircuits","kind":"function","lang":"kotlin","code":"@Test\n fun cancelShortCircuits() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n ).setHeader(\"content-type\", \"text/event-stream\")\n .build(),\n )\n listener.enqueueCancel() // Will cancel in onOpen().\n val request = Request.Builder().url(server.url(\"/\")).build()\n val response = client.newCall(request).execute()\n processResponse(response, listener)\n listener.assertOpen()\n listener.assertFailure(\"canceled\")\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/EventSourcesHttpTest.kt","line":96,"symbol":"failureWith401IsReadable","kind":"function","lang":"kotlin","code":"@Test\n fun failureWith401IsReadable() {\n server.enqueue(\n MockResponse(\n code = 401,\n body = \"{\\\"error\\\":{\\\"message\\\":\\\"No auth credentials found\\\",\\\"code\\\":401}}\",\n headers = Headers.headersOf(\"content-type\", \"application/json\"),\n ),\n )\n server.enqueue(\n MockResponse(\n body =\n \"\"\"\n |data: hey\n |\n |\n \"\"\".trimMargin(),\n headers = Headers.headersOf(\"content-type\", \"text/event-stream\"),\n ),\n )\n\n val request1 = Request.Builder().url(server.url(\"/\")).build()\n val response1 = client.newCall(request1).execute()\n assertThat(response1.code).isEqualTo(401)\n assertThat(response1.body.string())\n .isEqualTo(\"{\\\"error\\\":{\\\"message\\\":\\\"No auth credentials found\\\",\\\"code\\\":401}}"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":27,"symbol":"ServerSentEventIteratorTest","kind":"class","lang":"kotlin","code":"class ServerSentEventIteratorTest {\n /** Either [Event] or [Long] items for events and retry changes, respectively. */\n private val callbacks: Deque = ArrayDeque()\n\n @AfterEach\n fun after() {\n assertThat(callbacks).isEmpty()\n }\n\n @Test\n fun multiline() {\n consumeEvents(\n \"\"\"\n |data: YHOO\n |data: +2\n |data: 10\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"YHOO\\n+2\\n10\"))\n }\n\n @Test\n fun multilineCr() {\n consumeEvents(\n \"\"\"\n |data: YHOO\n |data: +2\n |data: 10\n |\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\"),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"YHOO\\n+2\\n10\"))\n }\n\n @Test\n fun multilineCrLf() {\n consumeEvents(\n \"\"\"\n |data: YHOO\n |data: +2\n |data: 10\n |\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\"),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"YHOO\\n+2\\n10\"))\n }\n\n @Test\n fun eventType() {\n consumeEvents(\n \"\"\"\n |event: add\n |data: 73857293\n |\n |event: remove\n |data: 2153\n |\n |event: add\n |data: 113411\n "} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":31,"symbol":"after","kind":"function","lang":"kotlin","code":"@AfterEach\n fun after() {\n assertThat(callbacks).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":36,"symbol":"multiline","kind":"function","lang":"kotlin","code":"@Test\n fun multiline() {\n consumeEvents(\n \"\"\"\n |data: YHOO\n |data: +2\n |data: 10\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"YHOO\\n+2\\n10\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":50,"symbol":"multilineCr","kind":"function","lang":"kotlin","code":"@Test\n fun multilineCr() {\n consumeEvents(\n \"\"\"\n |data: YHOO\n |data: +2\n |data: 10\n |\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\"),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"YHOO\\n+2\\n10\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":64,"symbol":"multilineCrLf","kind":"function","lang":"kotlin","code":"@Test\n fun multilineCrLf() {\n consumeEvents(\n \"\"\"\n |data: YHOO\n |data: +2\n |data: 10\n |\n |\n \"\"\".trimMargin().replace(\"\\n\", \"\\r\\n\"),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"YHOO\\n+2\\n10\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":78,"symbol":"eventType","kind":"function","lang":"kotlin","code":"@Test\n fun eventType() {\n consumeEvents(\n \"\"\"\n |event: add\n |data: 73857293\n |\n |event: remove\n |data: 2153\n |\n |event: add\n |data: 113411\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, \"add\", \"73857293\"))\n assertThat(callbacks.remove()).isEqualTo(Event(null, \"remove\", \"2153\"))\n assertThat(callbacks.remove()).isEqualTo(Event(null, \"add\", \"113411\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":99,"symbol":"commentsIgnored","kind":"function","lang":"kotlin","code":"@Test\n fun commentsIgnored() {\n consumeEvents(\n \"\"\"\n |: test stream\n |\n |data: first event\n |id: 1\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(\"1\", null, \"first event\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":114,"symbol":"idCleared","kind":"function","lang":"kotlin","code":"@Test\n fun idCleared() {\n consumeEvents(\n \"\"\"\n |data: first event\n |id: 1\n |\n |data: second event\n |id\n |\n |data: third event\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(\"1\", null, \"first event\"))\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"second event\"))\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"third event\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":134,"symbol":"nakedFieldNames","kind":"function","lang":"kotlin","code":"@Test\n fun nakedFieldNames() {\n consumeEvents(\n \"\"\"\n |data\n |\n |data\n |data\n |\n |data:\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"\"))\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"\\n\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":151,"symbol":"colonSpaceOptional","kind":"function","lang":"kotlin","code":"@Test\n fun colonSpaceOptional() {\n consumeEvents(\n \"\"\"\n |data:test\n |\n |data: test\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"test\"))\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"test\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":166,"symbol":"leadingWhitespace","kind":"function","lang":"kotlin","code":"@Test\n fun leadingWhitespace() {\n consumeEvents(\n \"\"\"\n |data: test\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \" test\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":178,"symbol":"idReusedAcrossEvents","kind":"function","lang":"kotlin","code":"@Test\n fun idReusedAcrossEvents() {\n consumeEvents(\n \"\"\"\n |data: first event\n |id: 1\n |\n |data: second event\n |\n |id: 2\n |data: third event\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(\"1\", null, \"first event\"))\n assertThat(callbacks.remove()).isEqualTo(Event(\"1\", null, \"second event\"))\n assertThat(callbacks.remove()).isEqualTo(Event(\"2\", null, \"third event\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":198,"symbol":"idIgnoredFromEmptyEvent","kind":"function","lang":"kotlin","code":"@Test\n fun idIgnoredFromEmptyEvent() {\n consumeEvents(\n \"\"\"\n |data: first event\n |id: 1\n |\n |id: 2\n |\n |data: second event\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(\"1\", null, \"first event\"))\n assertThat(callbacks.remove()).isEqualTo(Event(\"1\", null, \"second event\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":216,"symbol":"retry","kind":"function","lang":"kotlin","code":"@Test\n fun retry() {\n consumeEvents(\n \"\"\"\n |retry: 22\n |\n |data: first event\n |id: 1\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(22L)\n assertThat(callbacks.remove()).isEqualTo(Event(\"1\", null, \"first event\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":232,"symbol":"retryInvalidFormatIgnored","kind":"function","lang":"kotlin","code":"@Test\n fun retryInvalidFormatIgnored() {\n consumeEvents(\n \"\"\"\n |retry: 22\n |\n |retry: hey\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(22L)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":245,"symbol":"namePrefixIgnored","kind":"function","lang":"kotlin","code":"@Test\n fun namePrefixIgnored() {\n consumeEvents(\n \"\"\"\n |data: a\n |eventually\n |database\n |identity\n |retrying\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"a\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":261,"symbol":"nakedNameClearsIdAndTypeAppendsData","kind":"function","lang":"kotlin","code":"@Test\n fun nakedNameClearsIdAndTypeAppendsData() {\n consumeEvents(\n \"\"\"\n |id: a\n |event: b\n |data: c\n |id\n |event\n |data\n |\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks.remove()).isEqualTo(Event(null, null, \"c\\n\"))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":278,"symbol":"nakedRetryIgnored","kind":"function","lang":"kotlin","code":"@Test\n fun nakedRetryIgnored() {\n consumeEvents(\n \"\"\"\n |retry\n |\n \"\"\".trimMargin(),\n )\n assertThat(callbacks).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":289,"symbol":"consumeEvents","kind":"function","lang":"kotlin","code":"private fun consumeEvents(source: String) {\n val callback: ServerSentEventReader.Callback =\n object : ServerSentEventReader.Callback {\n override fun onEvent(\n id: String?,\n type: String?,\n data: String,\n ) {\n callbacks.add(Event(id, type, data))\n }\n\n override fun onRetryChange(timeMs: Long) {\n callbacks.add(timeMs)\n }\n }\n val buffer = Buffer().writeUtf8(source)\n val reader = ServerSentEventReader(buffer, callback)\n while (reader.processNextEvent()) {\n }\n assertThat(buffer.size, \"Unconsumed buffer: ${buffer.readUtf8()}\")\n .isEqualTo(0)\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":292,"symbol":"onEvent","kind":"function","lang":"kotlin","code":"override fun onEvent(\n id: String?,\n type: String?,\n data: String,\n ) {\n callbacks.add(Event(id, type, data))\n }"} {"repo":"okhttp","file":"okhttp-sse/src/test/java/okhttp3/sse/internal/ServerSentEventIteratorTest.kt","line":300,"symbol":"onRetryChange","kind":"function","lang":"kotlin","code":"override fun onRetryChange(timeMs: Long) {\n callbacks.add(timeMs)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":26,"symbol":"CallEvent","kind":"class","lang":"kotlin","doc":"Data classes that correspond to each of the methods of [EventListener].","code":"@SuppressSignatureCheck\nsealed class CallEvent {\n abstract val timestampNs: Long\n abstract val call: Call\n\n val name: String\n get() = javaClass.simpleName\n\n /** Returns if the event closes this event, or null if this is no open event. */\n open fun closes(event: CallEvent): Boolean? = null\n\n data class DispatcherQueueStart(\n override val timestampNs: Long,\n override val call: Call,\n val dispatcher: Dispatcher,\n ) : CallEvent()\n\n data class DispatcherQueueEnd(\n override val timestampNs: Long,\n override val call: Call,\n val dispatcher: Dispatcher,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is DispatcherQueueStart && call == event.call\n }\n\n data class ProxySelectStart(\n override val timestampNs: Long,\n override val call: Call,\n val url: HttpUrl,\n ) : CallEvent()\n\n data class ProxySelectEnd(\n override val timestampNs: Long,\n override val call: Call,\n val url: HttpUrl,\n val proxies: List?,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is ProxySelectStart && call == event.call && url == event.url\n }\n\n data class DnsStart(\n override val timestampNs: Long,\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":35,"symbol":"closes","kind":"function","lang":"kotlin","doc":"Returns if the event closes this event, or null if this is no open event.","code":"open fun closes(event: CallEvent): Boolean? = null"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":43,"symbol":"DispatcherQueueEnd","kind":"class","lang":"kotlin","code":"data class DispatcherQueueEnd(\n override val timestampNs: Long,\n override val call: Call,\n val dispatcher: Dispatcher,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is DispatcherQueueStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":48,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is DispatcherQueueStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":57,"symbol":"ProxySelectEnd","kind":"class","lang":"kotlin","code":"data class ProxySelectEnd(\n override val timestampNs: Long,\n override val call: Call,\n val url: HttpUrl,\n val proxies: List?,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is ProxySelectStart && call == event.call && url == event.url\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":63,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is ProxySelectStart && call == event.call && url == event.url"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":72,"symbol":"DnsEnd","kind":"class","lang":"kotlin","code":"data class DnsEnd(\n override val timestampNs: Long,\n override val call: Call,\n val domainName: String,\n val inetAddressList: List,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is DnsStart && call == event.call && domainName == event.domainName\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":78,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is DnsStart && call == event.call && domainName == event.domainName"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":88,"symbol":"ConnectEnd","kind":"class","lang":"kotlin","code":"data class ConnectEnd(\n override val timestampNs: Long,\n override val call: Call,\n val inetSocketAddress: InetSocketAddress,\n val proxy: Proxy?,\n val protocol: Protocol?,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean =\n event is ConnectStart && call == event.call && inetSocketAddress == event.inetSocketAddress && proxy == event.proxy\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":95,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean =\n event is ConnectStart && call == event.call && inetSocketAddress == event.inetSocketAddress && proxy == event.proxy"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":99,"symbol":"ConnectFailed","kind":"class","lang":"kotlin","code":"data class ConnectFailed(\n override val timestampNs: Long,\n override val call: Call,\n val inetSocketAddress: InetSocketAddress,\n val proxy: Proxy,\n val protocol: Protocol?,\n val ioe: IOException,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean =\n event is ConnectStart && call == event.call && inetSocketAddress == event.inetSocketAddress && proxy == event.proxy\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":107,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean =\n event is ConnectStart && call == event.call && inetSocketAddress == event.inetSocketAddress && proxy == event.proxy"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":116,"symbol":"SecureConnectEnd","kind":"class","lang":"kotlin","code":"data class SecureConnectEnd(\n override val timestampNs: Long,\n override val call: Call,\n val handshake: Handshake?,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is SecureConnectStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":121,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is SecureConnectStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":130,"symbol":"ConnectionReleased","kind":"class","lang":"kotlin","code":"data class ConnectionReleased(\n override val timestampNs: Long,\n override val call: Call,\n val connection: Connection,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is ConnectionAcquired && call == event.call && connection == event.connection\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":135,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is ConnectionAcquired && call == event.call && connection == event.connection"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":143,"symbol":"CallEnd","kind":"class","lang":"kotlin","code":"data class CallEnd(\n override val timestampNs: Long,\n override val call: Call,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is CallStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":147,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is CallStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":150,"symbol":"CallFailed","kind":"class","lang":"kotlin","code":"data class CallFailed(\n override val timestampNs: Long,\n override val call: Call,\n val ioe: IOException,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is CallStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":155,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is CallStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":168,"symbol":"RequestHeadersEnd","kind":"class","lang":"kotlin","code":"data class RequestHeadersEnd(\n override val timestampNs: Long,\n override val call: Call,\n val headerLength: Long,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is RequestHeadersStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":173,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is RequestHeadersStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":181,"symbol":"RequestBodyEnd","kind":"class","lang":"kotlin","code":"data class RequestBodyEnd(\n override val timestampNs: Long,\n override val call: Call,\n val bytesWritten: Long,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is RequestBodyStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":186,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is RequestBodyStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":189,"symbol":"RequestFailed","kind":"class","lang":"kotlin","code":"data class RequestFailed(\n override val timestampNs: Long,\n override val call: Call,\n val ioe: IOException,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is RequestHeadersStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":194,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is RequestHeadersStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":202,"symbol":"ResponseHeadersEnd","kind":"class","lang":"kotlin","code":"data class ResponseHeadersEnd(\n override val timestampNs: Long,\n override val call: Call,\n val headerLength: Long,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is ResponseHeadersStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":207,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is ResponseHeadersStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":215,"symbol":"ResponseBodyEnd","kind":"class","lang":"kotlin","code":"data class ResponseBodyEnd(\n override val timestampNs: Long,\n override val call: Call,\n val bytesRead: Long,\n ) : CallEvent() {\n override fun closes(event: CallEvent): Boolean = event is ResponseBodyStart && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/CallEvent.kt","line":220,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: CallEvent): Boolean = event is ResponseBodyStart && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":24,"symbol":"ClientRuleEventListener","kind":"class","lang":"kotlin","code":"class ClientRuleEventListener(\n var logger: (String) -> Unit,\n) : EventListener(),\n EventListener.Factory {\n private var startNs: Long? = null\n\n override fun create(call: Call): EventListener = this\n\n override fun callStart(call: Call) {\n startNs = System.nanoTime()\n\n logWithTime(\"callStart: ${call.request()}\")\n }\n\n override fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n logWithTime(\"dispatcherQueueStart: queuedCallsCount=${dispatcher.queuedCallsCount()}\")\n }\n\n override fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n logWithTime(\"dispatcherQueueEnd: queuedCallsCount=${dispatcher.queuedCallsCount()}\")\n }\n\n override fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) {\n logWithTime(\"proxySelectStart: $url\")\n }\n\n override fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List,\n ) {\n logWithTime(\"proxySelectEnd: $proxies\")\n }\n\n override fun dnsStart(\n call: Call,\n domainName: String,\n ) {\n logWithTime(\"dnsStart: $domainName\")\n }\n\n override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List,\n ) {\n logWithTime(\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":30,"symbol":"create","kind":"function","lang":"kotlin","code":"override fun create(call: Call): EventListener = this"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":32,"symbol":"callStart","kind":"function","lang":"kotlin","code":"override fun callStart(call: Call) {\n startNs = System.nanoTime()\n\n logWithTime(\"callStart: ${call.request()}\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":38,"symbol":"dispatcherQueueStart","kind":"function","lang":"kotlin","code":"override fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n logWithTime(\"dispatcherQueueStart: queuedCallsCount=${dispatcher.queuedCallsCount()}\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":45,"symbol":"dispatcherQueueEnd","kind":"function","lang":"kotlin","code":"override fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) {\n logWithTime(\"dispatcherQueueEnd: queuedCallsCount=${dispatcher.queuedCallsCount()}\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":52,"symbol":"proxySelectStart","kind":"function","lang":"kotlin","code":"override fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) {\n logWithTime(\"proxySelectStart: $url\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":59,"symbol":"proxySelectEnd","kind":"function","lang":"kotlin","code":"override fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List,\n ) {\n logWithTime(\"proxySelectEnd: $proxies\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":67,"symbol":"dnsStart","kind":"function","lang":"kotlin","code":"override fun dnsStart(\n call: Call,\n domainName: String,\n ) {\n logWithTime(\"dnsStart: $domainName\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":74,"symbol":"dnsEnd","kind":"function","lang":"kotlin","code":"override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List,\n ) {\n logWithTime(\"dnsEnd: $inetAddressList\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":82,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) {\n logWithTime(\"connectStart: $inetSocketAddress $proxy\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":90,"symbol":"secureConnectStart","kind":"function","lang":"kotlin","code":"override fun secureConnectStart(call: Call) {\n logWithTime(\"secureConnectStart\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":94,"symbol":"secureConnectEnd","kind":"function","lang":"kotlin","code":"override fun secureConnectEnd(\n call: Call,\n handshake: Handshake?,\n ) {\n logWithTime(\"secureConnectEnd: $handshake\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":101,"symbol":"connectEnd","kind":"function","lang":"kotlin","code":"override fun connectEnd(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ) {\n logWithTime(\"connectEnd: $protocol\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":110,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ioe: IOException,\n ) {\n logWithTime(\"connectFailed: $protocol $ioe\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":120,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n logWithTime(\"connectionAcquired: $connection\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":127,"symbol":"connectionReleased","kind":"function","lang":"kotlin","code":"override fun connectionReleased(\n call: Call,\n connection: Connection,\n ) {\n logWithTime(\"connectionReleased\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":134,"symbol":"requestHeadersStart","kind":"function","lang":"kotlin","code":"override fun requestHeadersStart(call: Call) {\n logWithTime(\"requestHeadersStart\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":138,"symbol":"requestHeadersEnd","kind":"function","lang":"kotlin","code":"override fun requestHeadersEnd(\n call: Call,\n request: Request,\n ) {\n logWithTime(\"requestHeadersEnd\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":145,"symbol":"requestBodyStart","kind":"function","lang":"kotlin","code":"override fun requestBodyStart(call: Call) {\n logWithTime(\"requestBodyStart\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":149,"symbol":"requestBodyEnd","kind":"function","lang":"kotlin","code":"override fun requestBodyEnd(\n call: Call,\n byteCount: Long,\n ) {\n logWithTime(\"requestBodyEnd: byteCount=$byteCount\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":156,"symbol":"requestFailed","kind":"function","lang":"kotlin","code":"override fun requestFailed(\n call: Call,\n ioe: IOException,\n ) {\n logWithTime(\"requestFailed: $ioe\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":163,"symbol":"responseHeadersStart","kind":"function","lang":"kotlin","code":"override fun responseHeadersStart(call: Call) {\n logWithTime(\"responseHeadersStart\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":167,"symbol":"responseHeadersEnd","kind":"function","lang":"kotlin","code":"override fun responseHeadersEnd(\n call: Call,\n response: Response,\n ) {\n logWithTime(\"responseHeadersEnd: $response\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":174,"symbol":"responseBodyStart","kind":"function","lang":"kotlin","code":"override fun responseBodyStart(call: Call) {\n logWithTime(\"responseBodyStart\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":178,"symbol":"responseBodyEnd","kind":"function","lang":"kotlin","code":"override fun responseBodyEnd(\n call: Call,\n byteCount: Long,\n ) {\n logWithTime(\"responseBodyEnd: byteCount=$byteCount\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":185,"symbol":"responseFailed","kind":"function","lang":"kotlin","code":"override fun responseFailed(\n call: Call,\n ioe: IOException,\n ) {\n logWithTime(\"responseFailed: $ioe\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":192,"symbol":"callEnd","kind":"function","lang":"kotlin","code":"override fun callEnd(call: Call) {\n logWithTime(\"callEnd\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":196,"symbol":"callFailed","kind":"function","lang":"kotlin","code":"override fun callFailed(\n call: Call,\n ioe: IOException,\n ) {\n logWithTime(\"callFailed: $ioe\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":203,"symbol":"canceled","kind":"function","lang":"kotlin","code":"override fun canceled(call: Call) {\n logWithTime(\"canceled\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":207,"symbol":"satisfactionFailure","kind":"function","lang":"kotlin","code":"override fun satisfactionFailure(\n call: Call,\n response: Response,\n ) {\n logWithTime(\"satisfactionFailure\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":214,"symbol":"cacheMiss","kind":"function","lang":"kotlin","code":"override fun cacheMiss(call: Call) {\n logWithTime(\"cacheMiss\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":218,"symbol":"cacheHit","kind":"function","lang":"kotlin","code":"override fun cacheHit(\n call: Call,\n response: Response,\n ) {\n logWithTime(\"cacheHit\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":225,"symbol":"cacheConditionalHit","kind":"function","lang":"kotlin","code":"override fun cacheConditionalHit(\n call: Call,\n cachedResponse: Response,\n ) {\n logWithTime(\"cacheConditionalHit\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":232,"symbol":"retryDecision","kind":"function","lang":"kotlin","code":"override fun retryDecision(\n call: Call,\n exception: IOException,\n retry: Boolean,\n ) {\n logWithTime(\"retryDecision\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":240,"symbol":"followUpDecision","kind":"function","lang":"kotlin","code":"override fun followUpDecision(\n call: Call,\n networkResponse: Response,\n nextRequest: Request?,\n ) {\n logWithTime(\"followUpDecision\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ClientRuleEventListener.kt","line":248,"symbol":"logWithTime","kind":"function","lang":"kotlin","code":"private fun logWithTime(message: String) {\n val startNs = startNs\n val timeMs =\n if (startNs == null) {\n // Event occurred before start, for an example an early cancel.\n 0L\n } else {\n TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)\n }\n\n logger.invoke(\"[$timeMs ms] $message\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ConnectionEvent.kt","line":28,"symbol":"ConnectionEvent","kind":"class","lang":"kotlin","doc":"Data classes that correspond to each of the methods of [ConnectionListener].","code":"@SuppressSignatureCheck\nsealed class ConnectionEvent {\n abstract val timestampNs: Long\n open val connection: Connection?\n get() = null\n\n /** Returns if the event closes this event, or null if this is no open event. */\n open fun closes(event: ConnectionEvent): Boolean? = null\n\n val name: String\n get() = javaClass.simpleName\n\n data class ConnectStart(\n override val timestampNs: Long,\n val route: Route,\n val call: Call,\n ) : ConnectionEvent()\n\n data class ConnectFailed(\n override val timestampNs: Long,\n val route: Route,\n val call: Call,\n val exception: IOException,\n ) : ConnectionEvent() {\n override fun closes(event: ConnectionEvent): Boolean = event is ConnectStart && call == event.call && route == event.route\n }\n\n data class ConnectEnd(\n override val timestampNs: Long,\n override val connection: Connection,\n val route: Route,\n val call: Call,\n ) : ConnectionEvent() {\n override fun closes(event: ConnectionEvent): Boolean = event is ConnectStart && call == event.call && route == event.route\n }\n\n data class ConnectionClosed(\n override val timestampNs: Long,\n override val connection: Connection,\n ) : ConnectionEvent()\n\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ConnectionEvent.kt","line":35,"symbol":"closes","kind":"function","lang":"kotlin","doc":"Returns if the event closes this event, or null if this is no open event.","code":"open fun closes(event: ConnectionEvent): Boolean? = null"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ConnectionEvent.kt","line":46,"symbol":"ConnectFailed","kind":"class","lang":"kotlin","code":"data class ConnectFailed(\n override val timestampNs: Long,\n val route: Route,\n val call: Call,\n val exception: IOException,\n ) : ConnectionEvent() {\n override fun closes(event: ConnectionEvent): Boolean = event is ConnectStart && call == event.call && route == event.route\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ConnectionEvent.kt","line":52,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: ConnectionEvent): Boolean = event is ConnectStart && call == event.call && route == event.route"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ConnectionEvent.kt","line":55,"symbol":"ConnectEnd","kind":"class","lang":"kotlin","code":"data class ConnectEnd(\n override val timestampNs: Long,\n override val connection: Connection,\n val route: Route,\n val call: Call,\n ) : ConnectionEvent() {\n override fun closes(event: ConnectionEvent): Boolean = event is ConnectStart && call == event.call && route == event.route\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ConnectionEvent.kt","line":61,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: ConnectionEvent): Boolean = event is ConnectStart && call == event.call && route == event.route"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ConnectionEvent.kt","line":75,"symbol":"ConnectionReleased","kind":"class","lang":"kotlin","code":"data class ConnectionReleased(\n override val timestampNs: Long,\n override val connection: Connection,\n val call: Call,\n ) : ConnectionEvent() {\n override fun closes(event: ConnectionEvent): Boolean =\n event is ConnectionAcquired && connection == event.connection && call == event.call\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ConnectionEvent.kt","line":80,"symbol":"closes","kind":"function","lang":"kotlin","code":"override fun closes(event: ConnectionEvent): Boolean =\n event is ConnectionAcquired && connection == event.connection && call == event.call"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":60,"symbol":"EventListenerAdapter","kind":"class","lang":"kotlin","doc":"This accepts events as function calls on [EventListener], and publishes them as subtypes of [CallEvent].","code":"class EventListenerAdapter : EventListener() {\n var listeners = listOf<(CallEvent) -> Unit>()\n\n private fun onEvent(listener: CallEvent) {\n for (function in listeners) {\n function(listener)\n }\n }\n\n override fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) = onEvent(DispatcherQueueStart(System.nanoTime(), call, dispatcher))\n\n override fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) = onEvent(DispatcherQueueEnd(System.nanoTime(), call, dispatcher))\n\n override fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) = onEvent(ProxySelectStart(System.nanoTime(), call, url))\n\n override fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List,\n ) = onEvent(ProxySelectEnd(System.nanoTime(), call, url, proxies))\n\n override fun dnsStart(\n call: Call,\n domainName: String,\n ) = onEvent(DnsStart(System.nanoTime(), call, domainName))\n\n override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List,\n ) = onEvent(DnsEnd(System.nanoTime(), call, domainName, inetAddressList))\n\n override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":63,"symbol":"onEvent","kind":"function","lang":"kotlin","code":"private fun onEvent(listener: CallEvent) {\n for (function in listeners) {\n function(listener)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":69,"symbol":"dispatcherQueueStart","kind":"function","lang":"kotlin","code":"override fun dispatcherQueueStart(\n call: Call,\n dispatcher: Dispatcher,\n ) = onEvent(DispatcherQueueStart(System.nanoTime(), call, dispatcher))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":74,"symbol":"dispatcherQueueEnd","kind":"function","lang":"kotlin","code":"override fun dispatcherQueueEnd(\n call: Call,\n dispatcher: Dispatcher,\n ) = onEvent(DispatcherQueueEnd(System.nanoTime(), call, dispatcher))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":79,"symbol":"proxySelectStart","kind":"function","lang":"kotlin","code":"override fun proxySelectStart(\n call: Call,\n url: HttpUrl,\n ) = onEvent(ProxySelectStart(System.nanoTime(), call, url))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":84,"symbol":"proxySelectEnd","kind":"function","lang":"kotlin","code":"override fun proxySelectEnd(\n call: Call,\n url: HttpUrl,\n proxies: List,\n ) = onEvent(ProxySelectEnd(System.nanoTime(), call, url, proxies))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":90,"symbol":"dnsStart","kind":"function","lang":"kotlin","code":"override fun dnsStart(\n call: Call,\n domainName: String,\n ) = onEvent(DnsStart(System.nanoTime(), call, domainName))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":95,"symbol":"dnsEnd","kind":"function","lang":"kotlin","code":"override fun dnsEnd(\n call: Call,\n domainName: String,\n inetAddressList: List,\n ) = onEvent(DnsEnd(System.nanoTime(), call, domainName, inetAddressList))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":101,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n ) = onEvent(ConnectStart(System.nanoTime(), call, inetSocketAddress, proxy))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":107,"symbol":"secureConnectStart","kind":"function","lang":"kotlin","code":"override fun secureConnectStart(call: Call) =\n onEvent(\n SecureConnectStart(\n System.nanoTime(),\n call,\n ),\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":115,"symbol":"secureConnectEnd","kind":"function","lang":"kotlin","code":"override fun secureConnectEnd(\n call: Call,\n handshake: Handshake?,\n ) = onEvent(SecureConnectEnd(System.nanoTime(), call, handshake))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":120,"symbol":"connectEnd","kind":"function","lang":"kotlin","code":"override fun connectEnd(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ) = onEvent(ConnectEnd(System.nanoTime(), call, inetSocketAddress, proxy, protocol))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":127,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n call: Call,\n inetSocketAddress: InetSocketAddress,\n proxy: Proxy,\n protocol: Protocol?,\n ioe: IOException,\n ) = onEvent(\n ConnectFailed(\n System.nanoTime(),\n call,\n inetSocketAddress,\n proxy,\n protocol,\n ioe,\n ),\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":144,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) = onEvent(ConnectionAcquired(System.nanoTime(), call, connection))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":149,"symbol":"connectionReleased","kind":"function","lang":"kotlin","code":"override fun connectionReleased(\n call: Call,\n connection: Connection,\n ) = onEvent(ConnectionReleased(System.nanoTime(), call, connection))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":154,"symbol":"callStart","kind":"function","lang":"kotlin","code":"override fun callStart(call: Call) = onEvent(CallStart(System.nanoTime(), call))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":156,"symbol":"requestHeadersStart","kind":"function","lang":"kotlin","code":"override fun requestHeadersStart(call: Call) =\n onEvent(\n RequestHeadersStart(\n System.nanoTime(),\n call,\n ),\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":164,"symbol":"requestHeadersEnd","kind":"function","lang":"kotlin","code":"override fun requestHeadersEnd(\n call: Call,\n request: Request,\n ) = onEvent(RequestHeadersEnd(System.nanoTime(), call, request.headers.byteCount()))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":169,"symbol":"requestBodyStart","kind":"function","lang":"kotlin","code":"override fun requestBodyStart(call: Call) =\n onEvent(\n RequestBodyStart(\n System.nanoTime(),\n call,\n ),\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":177,"symbol":"requestBodyEnd","kind":"function","lang":"kotlin","code":"override fun requestBodyEnd(\n call: Call,\n byteCount: Long,\n ) = onEvent(RequestBodyEnd(System.nanoTime(), call, byteCount))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":182,"symbol":"requestFailed","kind":"function","lang":"kotlin","code":"override fun requestFailed(\n call: Call,\n ioe: IOException,\n ) = onEvent(RequestFailed(System.nanoTime(), call, ioe))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":187,"symbol":"responseHeadersStart","kind":"function","lang":"kotlin","code":"override fun responseHeadersStart(call: Call) =\n onEvent(\n ResponseHeadersStart(\n System.nanoTime(),\n call,\n ),\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":195,"symbol":"responseHeadersEnd","kind":"function","lang":"kotlin","code":"override fun responseHeadersEnd(\n call: Call,\n response: Response,\n ) = onEvent(ResponseHeadersEnd(System.nanoTime(), call, response.headers.byteCount()))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":200,"symbol":"responseBodyStart","kind":"function","lang":"kotlin","code":"override fun responseBodyStart(call: Call) =\n onEvent(\n ResponseBodyStart(\n System.nanoTime(),\n call,\n ),\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":208,"symbol":"responseBodyEnd","kind":"function","lang":"kotlin","code":"override fun responseBodyEnd(\n call: Call,\n byteCount: Long,\n ) = onEvent(ResponseBodyEnd(System.nanoTime(), call, byteCount))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":213,"symbol":"responseFailed","kind":"function","lang":"kotlin","code":"override fun responseFailed(\n call: Call,\n ioe: IOException,\n ) = onEvent(ResponseFailed(System.nanoTime(), call, ioe))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":218,"symbol":"callEnd","kind":"function","lang":"kotlin","code":"override fun callEnd(call: Call) = onEvent(CallEnd(System.nanoTime(), call))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":220,"symbol":"callFailed","kind":"function","lang":"kotlin","code":"override fun callFailed(\n call: Call,\n ioe: IOException,\n ) = onEvent(CallFailed(System.nanoTime(), call, ioe))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":225,"symbol":"canceled","kind":"function","lang":"kotlin","code":"override fun canceled(call: Call) = onEvent(Canceled(System.nanoTime(), call))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":227,"symbol":"satisfactionFailure","kind":"function","lang":"kotlin","code":"override fun satisfactionFailure(\n call: Call,\n response: Response,\n ) = onEvent(SatisfactionFailure(System.nanoTime(), call))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":232,"symbol":"cacheMiss","kind":"function","lang":"kotlin","code":"override fun cacheMiss(call: Call) = onEvent(CacheMiss(System.nanoTime(), call))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":234,"symbol":"cacheHit","kind":"function","lang":"kotlin","code":"override fun cacheHit(\n call: Call,\n response: Response,\n ) = onEvent(CacheHit(System.nanoTime(), call))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":239,"symbol":"cacheConditionalHit","kind":"function","lang":"kotlin","code":"override fun cacheConditionalHit(\n call: Call,\n cachedResponse: Response,\n ) = onEvent(CacheConditionalHit(System.nanoTime(), call))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":244,"symbol":"retryDecision","kind":"function","lang":"kotlin","code":"override fun retryDecision(\n call: Call,\n exception: IOException,\n retry: Boolean,\n ) = onEvent(RetryDecision(System.nanoTime(), call, exception, retry))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerAdapter.kt","line":250,"symbol":"followUpDecision","kind":"function","lang":"kotlin","code":"override fun followUpDecision(\n call: Call,\n networkResponse: Response,\n nextRequest: Request?,\n ) = onEvent(FollowUpDecision(System.nanoTime(), call, networkResponse, nextRequest))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerRelay.kt","line":27,"symbol":"EventListenerRelay","kind":"class","lang":"kotlin","doc":"Each instance processes a single event on [call], and then adds a successor [EventListenerRelay] on the same [call] to process the next event. By forcing the list of listeners to change after every event, we can detect if buggy code caches a stale [EventListener] in a field or local variable.","code":"class EventListenerRelay(\n val call: Call,\n val eventRecorder: EventRecorder,\n) {\n private val eventListenerAdapter =\n EventListenerAdapter()\n .apply {\n listeners += ::onEvent\n }\n\n val eventListener: EventListener\n get() = eventListenerAdapter\n\n var eventCount = 0\n\n private fun onEvent(callEvent: CallEvent) {\n if (eventCount++ == 0) {\n eventRecorder.logEvent(callEvent)\n val next = EventListenerRelay(call, eventRecorder)\n call.addEventListener(next.eventListener)\n }\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventListenerRelay.kt","line":42,"symbol":"onEvent","kind":"function","lang":"kotlin","code":"private fun onEvent(callEvent: CallEvent) {\n if (eventCount++ == 0) {\n eventRecorder.logEvent(callEvent)\n val next = EventListenerRelay(call, eventRecorder)\n call.addEventListener(next.eventListener)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":30,"symbol":"EventRecorder","kind":"class","lang":"kotlin","code":"open class EventRecorder(\n /**\n * An override to ignore the normal order that is enforced.\n * EventListeners added by Interceptors will not see all events.\n */\n private val enforceOrder: Boolean = true,\n) {\n private val eventListenerAdapter =\n EventListenerAdapter()\n .apply {\n listeners += ::logEvent\n }\n\n val eventListener: EventListener\n get() = eventListenerAdapter\n\n /** Events that haven't yet been removed. */\n val eventSequence = LinkedBlockingQueue()\n\n /** The full set of events, used to match starts with ends. */\n private val eventsForMatching = ConcurrentLinkedDeque()\n\n private val forbiddenLocks = mutableListOf()\n\n /** The timestamp of the last taken event, used to measure elapsed time between events. */\n private var lastTimestampNs: Long? = null\n\n /** Confirm that the thread does not hold a lock on `lock` during the callback. */\n fun forbidLock(lock: Any) {\n forbiddenLocks.add(lock)\n }\n\n /**\n * Removes recorded events up to (and including) an event is found whose class equals [eventClass]\n * and returns it.\n */\n fun removeUpToEvent(eventClass: Class): T {\n val fullEventSe"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":58,"symbol":"forbidLock","kind":"function","lang":"kotlin","doc":"Confirm that the thread does not hold a lock on `lock` during the callback.","code":"fun forbidLock(lock: Any) {\n forbiddenLocks.add(lock)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":66,"symbol":"removeUpToEvent","kind":"function","lang":"kotlin","doc":"Removes recorded events up to (and including) an event is found whose class equals [eventClass] and returns it.","code":"fun removeUpToEvent(eventClass: Class): T {\n val fullEventSequence = eventSequence.toList()\n try {\n while (true) {\n val event = takeEvent()\n if (eventClass.isInstance(event)) {\n return eventClass.cast(event)\n }\n }\n } catch (e: NoSuchElementException) {\n throw AssertionError(\"full event sequence: $fullEventSequence\", e)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":80,"symbol":"removeUpToEvent","kind":"function","lang":"kotlin","code":"inline fun removeUpToEvent(): T = removeUpToEvent(T::class.java)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":82,"symbol":"findEvent","kind":"function","lang":"kotlin","code":"inline fun findEvent(): T = eventSequence.first { it is T } as T"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":92,"symbol":"takeEvent","kind":"function","lang":"kotlin","doc":"@param eventClass a class to assert that the returned event is an instance of, or null to take any event class. @param elapsedMs the time in milliseconds elapsed since the immediately-preceding event, or -1L to take any duration.","code":"fun takeEvent(\n eventClass: Class? = null,\n elapsedMs: Long = -1L,\n ): CallEvent {\n val result = eventSequence.take()\n val actualElapsedNs = result.timestampNs - (lastTimestampNs ?: result.timestampNs)\n lastTimestampNs = result.timestampNs\n\n if (eventClass != null) {\n assertThat(result).isInstanceOf(eventClass)\n }\n\n if (elapsedMs != -1L) {\n assertThat(\n TimeUnit.NANOSECONDS\n .toMillis(actualElapsedNs)\n .toDouble(),\n ).isCloseTo(elapsedMs.toDouble(), 100.0)\n }\n\n return result\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":115,"symbol":"recordedEventTypes","kind":"function","lang":"kotlin","code":"fun recordedEventTypes() = eventSequence.map { it::class }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":117,"symbol":"clearAllEvents","kind":"function","lang":"kotlin","code":"fun clearAllEvents() {\n while (eventSequence.isNotEmpty()) {\n takeEvent()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":123,"symbol":"logEvent","kind":"function","lang":"kotlin","code":"internal fun logEvent(e: CallEvent) {\n for (lock in forbiddenLocks) {\n assertThat(Thread.holdsLock(lock), lock.toString()).isFalse()\n }\n\n if (enforceOrder) {\n checkForStartEvent(e)\n }\n\n eventsForMatching.offer(e)\n eventSequence.offer(e)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/EventRecorder.kt","line":136,"symbol":"checkForStartEvent","kind":"function","lang":"kotlin","code":"private fun checkForStartEvent(e: CallEvent) {\n if (eventsForMatching.isEmpty()) {\n assertThat(e).matchesPredicate { it is CallStart || it is Canceled }\n } else {\n eventsForMatching.forEach loop@{\n when (e.closes(it)) {\n null -> return\n\n // no open event\n true -> return\n\n // found open event\n false -> return@loop // this is not the open event so continue\n }\n }\n fail(\"event $e without matching start event\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":21,"symbol":"FailingCall","kind":"class","lang":"kotlin","code":"open class FailingCall : Call {\n override fun request(): Request = error(\"unexpected\")\n\n override fun execute(): Response = error(\"unexpected\")\n\n override fun enqueue(responseCallback: Callback): Unit = error(\"unexpected\")\n\n override fun cancel(): Unit = error(\"unexpected\")\n\n override fun isExecuted(): Boolean = error(\"unexpected\")\n\n override fun isCanceled(): Boolean = error(\"unexpected\")\n\n override fun timeout(): Timeout = error(\"unexpected\")\n\n override fun addEventListener(eventListener: EventListener) = error(\"unexpected\")\n\n override fun tag(type: KClass): T? = error(\"unexpected\")\n\n override fun tag(type: Class): T? = error(\"unexpected\")\n\n override fun tag(\n type: KClass,\n computeIfAbsent: () -> T,\n ): T = error(\"unexpected\")\n\n override fun tag(\n type: Class,\n computeIfAbsent: () -> T,\n ): T = error(\"unexpected\")\n\n override fun clone(): Call = error(\"unexpected\")\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":22,"symbol":"request","kind":"function","lang":"kotlin","code":"override fun request(): Request = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":24,"symbol":"execute","kind":"function","lang":"kotlin","code":"override fun execute(): Response = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":26,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"override fun enqueue(responseCallback: Callback): Unit = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":28,"symbol":"cancel","kind":"function","lang":"kotlin","code":"override fun cancel(): Unit = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":30,"symbol":"isExecuted","kind":"function","lang":"kotlin","code":"override fun isExecuted(): Boolean = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":32,"symbol":"isCanceled","kind":"function","lang":"kotlin","code":"override fun isCanceled(): Boolean = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":34,"symbol":"timeout","kind":"function","lang":"kotlin","code":"override fun timeout(): Timeout = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":36,"symbol":"addEventListener","kind":"function","lang":"kotlin","code":"override fun addEventListener(eventListener: EventListener) = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":38,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(type: KClass): T? = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":40,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(type: Class): T? = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":42,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(\n type: KClass,\n computeIfAbsent: () -> T,\n ): T = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":47,"symbol":"tag","kind":"function","lang":"kotlin","code":"override fun tag(\n type: Class,\n computeIfAbsent: () -> T,\n ): T = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FailingCall.kt","line":52,"symbol":"clone","kind":"function","lang":"kotlin","code":"override fun clone(): Call = error(\"unexpected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":48,"symbol":"FakeDns","kind":"class","lang":"kotlin","doc":"Handles DNS calls using in-memory records.","code":"class FakeDns(\n private val taskRunner: TaskRunner = TaskRunner.INSTANCE,\n) : Dns {\n private val data = ConcurrentHashMap>()\n\n var extraHeaders: Headers = Headers.headersOf()\n private val requests = LinkedBlockingDeque()\n val nextSequenceIndex = AtomicInteger(0)\n val sequenceIndexToOverride = ConcurrentHashMap()\n private var nextAddress = 0xff000064L // 255.0.0.100 in IPv4; ::ff00:64 in IPv6.\n\n /** Returns a MockWebServer dispatcher that serves DNS over HTTPS records. */\n val dispatcher =\n object : Dispatcher() {\n override fun dispatch(request: RecordedRequest): MockResponse {\n val sequenceIndex = nextSequenceIndex.getAndIncrement()\n val override = sequenceIndexToOverride.remove(sequenceIndex)\n if (override != null) return override\n\n val requestBody = request.body\n val queryParameter = request.url.queryParameter(\"dns\")\n val encodedDnsQuery =\n when {\n requestBody != null -> Buffer().write(requestBody)\n queryParameter != null -> Buffer().write(queryParameter.decodeBase64()!!)\n else -> return MockResponse(code = 400)\n }\n"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":62,"symbol":"dispatch","kind":"function","lang":"kotlin","code":"override fun dispatch(request: RecordedRequest): MockResponse {\n val sequenceIndex = nextSequenceIndex.getAndIncrement()\n val override = sequenceIndexToOverride.remove(sequenceIndex)\n if (override != null) return override\n\n val requestBody = request.body\n val queryParameter = request.url.queryParameter(\"dns\")\n val encodedDnsQuery =\n when {\n requestBody != null -> Buffer().write(requestBody)\n queryParameter != null -> Buffer().write(queryParameter.decodeBase64()!!)\n else -> return MockResponse(code = 400)\n }\n\n val dnsRequest = DnsMessageReader(encodedDnsQuery).read()\n requests.put(Request.DnsRequest(dnsRequest, request))\n\n val dnsResponse = invoke(dnsRequest)\n\n val body = Buffer()\n DnsMessageWriter(body).write(dnsResponse)\n\n return MockResponse\n .Builder()\n .addHeader(\"content-type\", \"application/dns-message\")\n .apply {\n for ((name, value) in extraHeaders) {\n addHeader(name, value)\n }\n }.body(body)\n .build()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":96,"symbol":"set","kind":"function","lang":"kotlin","code":"operator fun set(\n hostname: String,\n records: List,\n ) {\n data[hostname] = records\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":103,"symbol":"set","kind":"function","lang":"kotlin","code":"@JvmName(\"set-inetAddresses\") // Avoid raw types collision.\n operator fun set(\n hostname: String,\n inetAddresses: List,\n ) {\n set(\n hostname,\n inetAddresses.map { inetAddress ->\n ResourceRecord.IpAddress(\n name = hostname,\n timeToLive = 5,\n address = inetAddress,\n )\n },\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":120,"symbol":"addRecord","kind":"function","lang":"kotlin","code":"fun addRecord(\n hostname: String,\n timeToLive: Int = 5,\n address: InetAddress,\n ) {\n val previous = data[hostname] ?: listOf()\n data[hostname] = previous +\n ResourceRecord.IpAddress(\n name = hostname,\n timeToLive = timeToLive,\n address = address,\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":134,"symbol":"addRecord","kind":"function","lang":"kotlin","code":"fun addRecord(\n hostname: String,\n timeToLive: Int = 5,\n priority: Int = 1,\n targetName: String = \"\",\n alpnIds: List? = null,\n port: Int = 443,\n ipAddressHints: List = listOf(),\n echConfigList: ByteString? = null,\n ) {\n val previous = data[hostname] ?: listOf()\n data[hostname] = previous +\n ResourceRecord.Https(\n name = hostname,\n timeToLive = timeToLive,\n priority = priority,\n targetName = targetName,\n alpnIds = alpnIds,\n port = port,\n ipAddressHints = ipAddressHints,\n echConfigList = echConfigList,\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":158,"symbol":"newCall","kind":"function","lang":"kotlin","code":"override fun newCall(request: Dns.Request): Dns.Call = FakeDnsCall(request)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":160,"symbol":"lookup","kind":"function","lang":"kotlin","code":"@Throws(UnknownHostException::class)\n override fun lookup(hostname: String): List {\n requests.put(Request.FunctionCall(hostname))\n return get(hostname)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":167,"symbol":"get","kind":"function","lang":"kotlin","doc":"Note that this request is not recorded.","code":"@Throws(UnknownHostException::class)\n operator fun get(hostname: String): List {\n val records = data[hostname] ?: throw UnknownHostException()\n return records\n .filterIsInstance()\n .map { it.address }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":176,"symbol":"clear","kind":"function","lang":"kotlin","doc":"Clears the results for `hostname`.","code":"fun clear(hostname: String) {\n data.remove(hostname)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":180,"symbol":"takeRequest","kind":"function","lang":"kotlin","code":"fun takeRequest(): Request = requests.take()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":182,"symbol":"pollRequest","kind":"function","lang":"kotlin","code":"fun pollRequest(): Request? = requests.poll()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":184,"symbol":"takeAllRequests","kind":"function","lang":"kotlin","code":"fun takeAllRequests(): List =\n buildList {\n while (true) {\n val pair = pollRequest()\n add(pair ?: break)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":196,"symbol":"assertRequests","kind":"function","lang":"kotlin","doc":"Takes all requests received thus far (for all question types), and asserts that they match [expectedHosts].","code":"fun assertRequests(vararg expectedHosts: String?) {\n val actualHostnames = takeAllRequests().map { it.hostname }\n assertThat(actualHostnames).containsExactly(*expectedHosts)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":202,"symbol":"allocate","kind":"function","lang":"kotlin","doc":"Allocates and returns `count` fake IPv4 addresses like [255.0.0.100, 255.0.0.101].","code":"fun allocate(count: Int): List {\n val from = nextAddress\n nextAddress += count\n return (from until nextAddress)\n .map {\n return@map InetAddress.getByAddress(\n Buffer().writeInt(it.toInt()).readByteArray(),\n )\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":214,"symbol":"allocateIpv6","kind":"function","lang":"kotlin","doc":"Allocates and returns `count` fake IPv6 addresses like [::ff00:64, ::ff00:65].","code":"fun allocateIpv6(count: Int): List {\n val from = nextAddress\n nextAddress += count\n return (from until nextAddress)\n .map {\n return@map InetAddress.getByAddress(\n Buffer().writeLong(0L).writeLong(it).readByteArray(),\n )\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":225,"symbol":"query","kind":"function","lang":"kotlin","code":"fun query(request: DnsMessage): DnsMessage {\n requests.put(Request.DnsRequest(request))\n return invoke(request)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":230,"symbol":"invoke","kind":"function","lang":"kotlin","code":"private fun invoke(request: DnsMessage): DnsMessage {\n val answers =\n buildList {\n for (question in request.questions) {\n val records = data[question.name] ?: continue\n for (record in records) {\n if (!record.matches(question)) continue\n add(record)\n }\n }\n }\n\n return DnsMessage.response(\n id = request.id,\n questions = request.questions,\n answers = answers,\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":249,"symbol":"matches","kind":"function","lang":"kotlin","code":"private fun ResourceRecord.matches(question: Question): Boolean {\n if (question.`class` != CLASS_IN) return false\n\n return when (question.type) {\n TYPE_A -> (this as? ResourceRecord.IpAddress)?.address is Inet4Address\n TYPE_AAAA -> (this as? ResourceRecord.IpAddress)?.address is Inet6Address\n TYPE_HTTPS -> this is ResourceRecord.Https\n else -> false\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":264,"symbol":"FakeDnsCall","kind":"class","lang":"kotlin","doc":"Deliver each kind of DNS record in a separate callback, to most accurately simulate what a real DNS server does.","code":"private inner class FakeDnsCall(\n override val request: Dns.Request,\n ) : Dns.Call {\n @Volatile private var canceled = false\n private var executed = false\n private val taskQueue = taskRunner.newQueue()\n\n override fun cancel() {\n canceled = true\n }\n\n override fun isCanceled() = canceled\n\n override fun enqueue(callback: Dns.Callback) {\n check(!executed)\n executed = true\n\n requests.put(Request.FunctionCall(request.hostname))\n\n if (canceled) {\n taskQueue.execute(\"${request.hostname} dns\") {\n callback.onFailure(\n call = this,\n e = IOException(\"canceled\"),\n )\n }\n return\n }\n\n val resourceRecords = data[request.hostname] ?: listOf()\n if (resourceRecords.isEmpty()) {\n taskQueue.execute(\"${request.hostname} dns\") {\n callback.onRecords(\n call = this,\n last = true,\n records = listOf(),\n )\n }\n return\n }\n\n val serviceMetadataRecords = mutableListOf()\n val ipv6Records = mutableListOf()\n val ipv4Records = mutableListOf()\n val ipv6Records = mutableListOf()\n val ipv4Records = mutableListOf()\n for (resourceRecord in resourceRecords) {\n when (resourceRecord) {\n is ResourceRecord.Https -> {\n serviceMetadataRecords +=\n Dns.Record.ServiceMetadata(\n hostname = resourceRecord.targetName.takeIf { it != \"\" } ?: request.hostname,\n p"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":358,"symbol":"Request","kind":"interface","lang":"kotlin","code":"sealed interface Request {\n val hostname: String\n\n data class DnsRequest(\n val dnsRequest: DnsMessage,\n val httpRequest: RecordedRequest? = null,\n ) : Request {\n override val hostname: String\n get() = dnsRequest.questions.single().name\n }\n\n data class FunctionCall(\n override val hostname: String,\n ) : Request\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt","line":361,"symbol":"DnsRequest","kind":"class","lang":"kotlin","code":"data class DnsRequest(\n val dnsRequest: DnsMessage,\n val httpRequest: RecordedRequest? = null,\n ) : Request {\n override val hostname: String\n get() = dnsRequest.questions.single().name\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeProxySelector.kt","line":24,"symbol":"FakeProxySelector","kind":"class","lang":"kotlin","code":"class FakeProxySelector : ProxySelector() {\n val proxies: MutableList = mutableListOf()\n\n fun addProxy(proxy: Proxy): FakeProxySelector {\n proxies.add(proxy)\n return this\n }\n\n override fun select(uri: URI): List {\n // Don't handle 'socket' schemes, which the RI's Socket class may request (for SOCKS).\n return if (uri.scheme == \"http\" || uri.scheme == \"https\") proxies else listOf(Proxy.NO_PROXY)\n }\n\n override fun connectFailed(\n uri: URI,\n sa: SocketAddress,\n ioe: IOException,\n ) {\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeProxySelector.kt","line":27,"symbol":"addProxy","kind":"function","lang":"kotlin","code":"fun addProxy(proxy: Proxy): FakeProxySelector {\n proxies.add(proxy)\n return this\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeProxySelector.kt","line":32,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI): List {\n // Don't handle 'socket' schemes, which the RI's Socket class may request (for SOCKS).\n return if (uri.scheme == \"http\" || uri.scheme == \"https\") proxies else listOf(Proxy.NO_PROXY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeProxySelector.kt","line":37,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI,\n sa: SocketAddress,\n ioe: IOException,\n ) {\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":28,"symbol":"FakeSSLSession","kind":"class","lang":"kotlin","code":"class FakeSSLSession(\n vararg val certificates: Certificate,\n) : SSLSession {\n override fun getApplicationBufferSize(): Int = throw UnsupportedOperationException()\n\n override fun getCipherSuite(): String = throw UnsupportedOperationException()\n\n override fun getCreationTime(): Long = throw UnsupportedOperationException()\n\n override fun getId(): ByteArray = throw UnsupportedOperationException()\n\n override fun getLastAccessedTime(): Long = throw UnsupportedOperationException()\n\n override fun getLocalCertificates(): Array = throw UnsupportedOperationException()\n\n override fun getLocalPrincipal(): Principal = throw UnsupportedOperationException()\n\n override fun getPacketBufferSize(): Int = throw UnsupportedOperationException()\n\n @Suppress(\"UNCHECKED_CAST\")\n @Throws(SSLPeerUnverifiedException::class)\n override fun getPeerCertificates(): Array =\n if (certificates.isEmpty()) {\n throw SSLPeerUnverifiedException(\"peer not authenticated\")\n } else {\n certificates as Array\n }\n\n @Suppress(\"removal\", \"OVERRIDE_DEPRECATION\")\n @Throws(\n SSLPeerUnverifiedException::class,\n )\n override fun getPeerCertificateChain(): Array = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":43,"symbol":"getLocalPrincipal","kind":"function","lang":"kotlin","code":"override fun getLocalPrincipal(): Principal = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":45,"symbol":"getPacketBufferSize","kind":"function","lang":"kotlin","code":"override fun getPacketBufferSize(): Int = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":47,"symbol":"getPeerCertificates","kind":"function","lang":"kotlin","code":"@Suppress(\"UNCHECKED_CAST\")\n @Throws(SSLPeerUnverifiedException::class)\n override fun getPeerCertificates(): Array =\n if (certificates.isEmpty()) {\n throw SSLPeerUnverifiedException(\"peer not authenticated\")\n } else {\n certificates as Array\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":56,"symbol":"getPeerCertificateChain","kind":"function","lang":"kotlin","code":"@Suppress(\"removal\", \"OVERRIDE_DEPRECATION\")\n @Throws(\n SSLPeerUnverifiedException::class,\n )\n override fun getPeerCertificateChain(): Array = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":62,"symbol":"getPeerHost","kind":"function","lang":"kotlin","code":"override fun getPeerHost(): String = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":64,"symbol":"getPeerPort","kind":"function","lang":"kotlin","code":"override fun getPeerPort(): Int = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":66,"symbol":"getPeerPrincipal","kind":"function","lang":"kotlin","code":"@Throws(SSLPeerUnverifiedException::class)\n override fun getPeerPrincipal(): Principal = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":69,"symbol":"getProtocol","kind":"function","lang":"kotlin","code":"override fun getProtocol(): String = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":71,"symbol":"getSessionContext","kind":"function","lang":"kotlin","code":"override fun getSessionContext(): SSLSessionContext = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":73,"symbol":"putValue","kind":"function","lang":"kotlin","code":"override fun putValue(\n s: String,\n obj: Any,\n ): Unit = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":78,"symbol":"removeValue","kind":"function","lang":"kotlin","code":"override fun removeValue(s: String): Unit = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":80,"symbol":"getValue","kind":"function","lang":"kotlin","code":"override fun getValue(s: String): Any = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":82,"symbol":"getValueNames","kind":"function","lang":"kotlin","code":"override fun getValueNames(): Array = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":84,"symbol":"invalidate","kind":"function","lang":"kotlin","code":"override fun invalidate(): Unit = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/FakeSSLSession.kt","line":86,"symbol":"isValid","kind":"function","lang":"kotlin","code":"override fun isValid(): Boolean = throw UnsupportedOperationException()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingRequestBody.kt","line":21,"symbol":"ForwardingRequestBody","kind":"class","lang":"kotlin","code":"open class ForwardingRequestBody(\n delegate: RequestBody?,\n) : RequestBody() {\n private val delegate: RequestBody\n\n fun delegate(): RequestBody = delegate\n\n override fun contentType(): MediaType? = delegate.contentType()\n\n @Throws(IOException::class)\n override fun contentLength(): Long = delegate.contentLength()\n\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n delegate.writeTo(sink)\n }\n\n override fun isDuplex(): Boolean = delegate.isDuplex()\n\n override fun toString(): String = javaClass.simpleName + \"(\" + delegate.toString() + \")\"\n\n init {\n requireNotNull(delegate) { \"delegate == null\" }\n this.delegate = delegate\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingRequestBody.kt","line":26,"symbol":"delegate","kind":"function","lang":"kotlin","code":"fun delegate(): RequestBody = delegate"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingRequestBody.kt","line":28,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = delegate.contentType()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingRequestBody.kt","line":30,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun contentLength(): Long = delegate.contentLength()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingRequestBody.kt","line":33,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n delegate.writeTo(sink)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingRequestBody.kt","line":38,"symbol":"isDuplex","kind":"function","lang":"kotlin","code":"override fun isDuplex(): Boolean = delegate.isDuplex()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingRequestBody.kt","line":40,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = javaClass.simpleName + \"(\" + delegate.toString() + \")\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingResponseBody.kt","line":20,"symbol":"ForwardingResponseBody","kind":"class","lang":"kotlin","code":"open class ForwardingResponseBody(\n delegate: ResponseBody?,\n) : ResponseBody() {\n private val delegate: ResponseBody\n\n fun delegate(): ResponseBody = delegate\n\n override fun contentType(): MediaType? = delegate.contentType()\n\n override fun contentLength(): Long = delegate.contentLength()\n\n override fun source(): BufferedSource = delegate.source()\n\n override fun toString(): String = javaClass.simpleName + \"(\" + delegate.toString() + \")\"\n\n init {\n requireNotNull(delegate) { \"delegate == null\" }\n this.delegate = delegate\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingResponseBody.kt","line":25,"symbol":"delegate","kind":"function","lang":"kotlin","code":"fun delegate(): ResponseBody = delegate"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingResponseBody.kt","line":27,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = delegate.contentType()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingResponseBody.kt","line":29,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"override fun contentLength(): Long = delegate.contentLength()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingResponseBody.kt","line":31,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource = delegate.source()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/ForwardingResponseBody.kt","line":33,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = javaClass.simpleName + \"(\" + delegate.toString() + \")\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":22,"symbol":"JsseDebugLogging","kind":"object","lang":"kotlin","code":"object JsseDebugLogging {\n data class JsseDebugMessage(\n val message: String,\n val param: String?,\n ) {\n enum class Type {\n Handshake,\n Plaintext,\n Encrypted,\n Setup,\n Unknown,\n }\n\n val type: Type\n get() =\n when {\n message == \"adding as trusted certificates\" -> Type.Setup\n message == \"Raw read\" || message == \"Raw write\" -> Type.Encrypted\n message == \"Plaintext before ENCRYPTION\" || message == \"Plaintext after DECRYPTION\" -> Type.Plaintext\n message.startsWith(\"System property \") -> Type.Setup\n message.startsWith(\"Reload \") -> Type.Setup\n message == \"No session to resume.\" -> Type.Handshake\n message.startsWith(\"Consuming \") -> Type.Handshake\n message.startsWith(\"Produced \") -> Type.Handshake\n message.startsWith(\"Negotiated \") -> Type.Handshake\n message.startsWith(\"Found resumable session\") -> Type.Handshake\n message.startsWith(\"Resuming session\") -> Type.Handshake\n message.startsWith(\"Using PSK to derive early secret\") -> Type.Handshake\n else -> Type.Unknown\n }\n\n override fun toString(): String =\n if "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":23,"symbol":"JsseDebugMessage","kind":"class","lang":"kotlin","code":"data class JsseDebugMessage(\n val message: String,\n val param: String?,\n ) {\n enum class Type {\n Handshake,\n Plaintext,\n Encrypted,\n Setup,\n Unknown,\n }\n\n val type: Type\n get() =\n when {\n message == \"adding as trusted certificates\" -> Type.Setup\n message == \"Raw read\" || message == \"Raw write\" -> Type.Encrypted\n message == \"Plaintext before ENCRYPTION\" || message == \"Plaintext after DECRYPTION\" -> Type.Plaintext\n message.startsWith(\"System property \") -> Type.Setup\n message.startsWith(\"Reload \") -> Type.Setup\n message == \"No session to resume.\" -> Type.Handshake\n message.startsWith(\"Consuming \") -> Type.Handshake\n message.startsWith(\"Produced \") -> Type.Handshake\n message.startsWith(\"Negotiated \") -> Type.Handshake\n message.startsWith(\"Found resumable session\") -> Type.Handshake\n message.startsWith(\"Resuming session\") -> Type.Handshake\n message.startsWith(\"Using PSK to derive early secret\") -> Type.Handshake\n else -> Type.Unknown\n }\n\n override fun toString(): String =\n if (param != null) {\n me"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":27,"symbol":"Type","kind":"enum","lang":"kotlin","code":"enum class Type {\n Handshake,\n Plaintext,\n Encrypted,\n Setup,\n Unknown,\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":28,"symbol":"Handshake","kind":"enum_member","lang":"kotlin","code":"Handshake"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":29,"symbol":"Plaintext","kind":"enum_member","lang":"kotlin","code":"Plaintext"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":30,"symbol":"Encrypted","kind":"enum_member","lang":"kotlin","code":"Encrypted"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":31,"symbol":"Setup","kind":"enum_member","lang":"kotlin","code":"Setup"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":32,"symbol":"Unknown","kind":"enum_member","lang":"kotlin","code":"Unknown"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":53,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String =\n if (param != null) {\n message + \"\\n\" + param\n } else {\n message\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":61,"symbol":"quietDebug","kind":"function","lang":"kotlin","code":"private fun quietDebug(message: JsseDebugMessage) {\n if (message.message.startsWith(\"Ignore\")) {\n return\n }\n\n when (message.type) {\n JsseDebugMessage.Type.Setup, JsseDebugMessage.Type.Encrypted, JsseDebugMessage.Type.Plaintext -> {\n println(message.message + \" (skipped output)\")\n }\n\n else -> {\n println(message)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":77,"symbol":"enableJsseDebugLogging","kind":"function","lang":"kotlin","code":"fun enableJsseDebugLogging(debugHandler: (JsseDebugMessage) -> Unit = this::quietDebug): Closeable {\n System.setProperty(\"javax.net.debug\", \"\")\n return OkHttpDebugLogging.enable(\n \"javax.net.ssl\",\n object : Handler() {\n override fun publish(record: LogRecord) {\n val param = record.parameters?.firstOrNull() as? String\n debugHandler(JsseDebugMessage(record.message, param))\n }\n\n override fun flush() {\n }\n\n override fun close() {\n }\n },\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":82,"symbol":"publish","kind":"function","lang":"kotlin","code":"override fun publish(record: LogRecord) {\n val param = record.parameters?.firstOrNull() as? String\n debugHandler(JsseDebugMessage(record.message, param))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":87,"symbol":"flush","kind":"function","lang":"kotlin","code":"override fun flush() {\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/JsseDebugLogging.kt","line":90,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":55,"symbol":"OkHttpClientTestRule","kind":"class","lang":"kotlin","doc":"Apply this rule to all tests. It adds additional checks for leaked resources and uncaught exceptions. Use [newClient] as a factory for a OkHttpClient instances. These instances are specifically configured for testing.","code":"class OkHttpClientTestRule :\n BeforeEachCallback,\n AfterEachCallback {\n private val clientEventsList = mutableListOf()\n private var testClient: OkHttpClient? = null\n private var uncaughtException: Throwable? = null\n private lateinit var testName: String\n private var defaultUncaughtExceptionHandler: Thread.UncaughtExceptionHandler? = null\n private var taskQueuesWereIdle: Boolean = false\n private val connectionListener = RecordingConnectionListener()\n\n var logger: Logger? = null\n\n var recordEvents = true\n var recordTaskRunner = false\n var recordFrames = false\n var recordSslDebug = false\n\n private val sslExcludeFilter =\n Regex(\n buildString {\n append(\"^(?:\")\n append(\n listOf(\n \"Inaccessible trust store\",\n \"trustStore is\",\n \"Reload the trust store\",\n \"Reload trust certs\",\n \"Reloaded\",\n \"adding as trusted certificates\",\n \"Ignore disabled cipher suite\",\n \"Ignore unsupported cipher suite\",\n ).joinToString(separator = \"|\"),\n )\n append(\").*\")\n },\n )\n\n private val testLogHandler =\n object : Handler() {\n override "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":95,"symbol":"publish","kind":"function","lang":"kotlin","code":"override fun publish(record: LogRecord) {\n val recorded =\n when (record.loggerName) {\n TaskRunner::class.java.name -> recordTaskRunner\n Http2::class.java.name -> recordFrames\n \"javax.net.ssl\" -> recordSslDebug && !sslExcludeFilter.matches(record.message)\n else -> false\n }\n\n if (recorded) {\n synchronized(clientEventsList) {\n clientEventsList.add(record.message)\n\n if (record.loggerName == \"javax.net.ssl\") {\n val parameters = record.parameters\n\n if (parameters != null) {\n clientEventsList.add(parameters.first().toString())\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":119,"symbol":"flush","kind":"function","lang":"kotlin","code":"override fun flush() {\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":122,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":128,"symbol":"applyLogger","kind":"function","lang":"kotlin","code":"private fun applyLogger(fn: Logger.() -> Unit) {\n Logger.getLogger(OkHttpClient::class.java.`package`.name).fn()\n Logger.getLogger(OkHttpClient::class.java.name).fn()\n Logger.getLogger(Http2::class.java.name).fn()\n Logger.getLogger(TaskRunner::class.java.name).fn()\n Logger.getLogger(\"javax.net.ssl\").fn()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":136,"symbol":"wrap","kind":"function","lang":"kotlin","code":"fun wrap(eventListener: EventListener) =\n EventListener.Factory {\n ClientRuleEventListener(::addEvent) + eventListener\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":141,"symbol":"wrap","kind":"function","lang":"kotlin","code":"fun wrap(eventRecorder: EventRecorder) = wrap(eventRecorder.eventListener)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":143,"symbol":"wrap","kind":"function","lang":"kotlin","code":"fun wrap(eventListenerFactory: EventListener.Factory) =\n EventListener.Factory { call ->\n ClientRuleEventListener(::addEvent) + eventListenerFactory.create(call)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":157,"symbol":"newClient","kind":"function","lang":"kotlin","doc":"The returned client installs a default event listener that gathers debug information. This will be logged if the test fails. This client is also configured to be slightly more deterministic, returning a single IP address for all hosts, regardless of the actual number of IP addresses reported by DNS.","code":"fun newClient(): OkHttpClient {\n var client = testClient\n if (client == null) {\n client =\n initialClientBuilder()\n .dns(SINGLE_INET_ADDRESS_DNS) // Prevent unexpected fallback addresses.\n .eventListenerFactory { ClientRuleEventListener(logger = ::addEvent) }\n .build()\n connectionListener.forbidLock(RealConnectionPool.get(client.connectionPool))\n connectionListener.forbidLock(client.dispatcher)\n testClient = client\n }\n return client\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":172,"symbol":"initialClientBuilder","kind":"function","lang":"kotlin","code":"private fun initialClientBuilder(): OkHttpClient.Builder =\n if (isLoom()) {\n val backend = TaskRunner.RealBackend(loomThreadFactory())\n val taskRunner = TaskRunner(backend)\n\n OkHttpClient\n .Builder()\n .connectionPool(\n buildConnectionPool(\n connectionListener = connectionListener,\n taskRunner = taskRunner,\n ),\n ).dispatcher(Dispatcher(backend.executor))\n .taskRunnerInternal(taskRunner)\n } else {\n OkHttpClient\n .Builder()\n .connectionPool(ConnectionPool(connectionListener = connectionListener))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":192,"symbol":"loomThreadFactory","kind":"function","lang":"kotlin","code":"private fun loomThreadFactory(): ThreadFactory {\n val ofVirtual = Thread::class.java.getMethod(\"ofVirtual\").invoke(null)\n\n return Class\n .forName(\"java.lang.Thread\\$Builder\")\n .getMethod(\"factory\")\n .invoke(ofVirtual) as ThreadFactory\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":201,"symbol":"isLoom","kind":"function","lang":"kotlin","code":"private fun isLoom(): Boolean = getPlatformSystemProperty() == LOOM_PROPERTY"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":203,"symbol":"newClientBuilder","kind":"function","lang":"kotlin","code":"fun newClientBuilder(): OkHttpClient.Builder = newClient().newBuilder()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":205,"symbol":"addEvent","kind":"function","lang":"kotlin","code":"@Synchronized private fun addEvent(event: String) {\n if (recordEvents) {\n logger?.info(event)\n\n synchronized(clientEventsList) {\n clientEventsList.add(event)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":215,"symbol":"initUncaughtException","kind":"function","lang":"kotlin","code":"@Synchronized private fun initUncaughtException(throwable: Throwable) {\n if (uncaughtException == null) {\n uncaughtException = throwable\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":221,"symbol":"takeUncaughtException","kind":"function","lang":"kotlin","code":"@Synchronized fun takeUncaughtException(): Throwable? =\n uncaughtException\n .also { uncaughtException = null }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":225,"symbol":"ensureAllConnectionsReleased","kind":"function","lang":"kotlin","code":"fun ensureAllConnectionsReleased() {\n testClient?.let {\n val connectionPool = it.connectionPool\n\n connectionPool.evictAll()\n if (connectionPool.connectionCount() > 0) {\n // Minimise test flakiness due to possible race conditions with connections closing.\n // Some number of tests will report here, but not fail due to this delay.\n println(\"Delaying to avoid flakes\")\n Thread.sleep(500L)\n println(\"After delay: \" + connectionPool.connectionCount())\n }\n\n connectionPool.evictAll()\n assertEquals(0, connectionPool.connectionCount()) {\n \"Still ${connectionPool.connectionCount()} connections open\"\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":245,"symbol":"ensureAllTaskQueuesIdle","kind":"function","lang":"kotlin","code":"private fun ensureAllTaskQueuesIdle() {\n val entryTime = System.nanoTime()\n\n for (queue in TaskRunner.INSTANCE.activeQueues()) {\n // We wait at most 1 second, so we don't ever turn multiple lost threads into\n // a test timeout failure.\n val waitTime = (entryTime + 1_000_000_000L - System.nanoTime())\n if (!queue.idleLatch().await(waitTime, TimeUnit.NANOSECONDS)) {\n TaskRunner.INSTANCE.withLock {\n TaskRunner.INSTANCE.cancelAll()\n }\n fail(\"Queue still active after 1000 ms\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":261,"symbol":"beforeEach","kind":"function","lang":"kotlin","code":"override fun beforeEach(context: ExtensionContext) {\n testName = context.displayName\n\n beforeEach()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":267,"symbol":"beforeEach","kind":"function","lang":"kotlin","code":"private fun beforeEach() {\n defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()\n Thread.setDefaultUncaughtExceptionHandler { _, throwable ->\n initUncaughtException(throwable)\n }\n\n taskQueuesWereIdle = TaskRunner.INSTANCE.activeQueues().isEmpty()\n\n applyLogger {\n addHandler(testLogHandler)\n level = Level.FINEST\n useParentHandlers = false\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":282,"symbol":"afterEach","kind":"function","lang":"kotlin","code":"@SuppressLint(\"NewApi\")\n override fun afterEach(context: ExtensionContext) {\n val failure = context.executionException.orElseGet { null }\n\n if (uncaughtException != null) {\n throw failure + AssertionError(\"uncaught exception thrown during test\", uncaughtException)\n }\n\n if (context.isFlaky()) {\n logEvents()\n }\n\n LogManager.getLogManager().reset()\n\n var result: Throwable? = failure\n Thread.setDefaultUncaughtExceptionHandler(defaultUncaughtExceptionHandler)\n try {\n ensureAllConnectionsReleased()\n releaseClient()\n } catch (ae: AssertionError) {\n result += ae\n }\n\n try {\n if (taskQueuesWereIdle) {\n ensureAllTaskQueuesIdle()\n }\n } catch (ae: AssertionError) {\n result += ae\n }\n\n if (result != null) throw result\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":316,"symbol":"releaseClient","kind":"function","lang":"kotlin","code":"private fun releaseClient() {\n testClient?.dispatcher?.executorService?.shutdown()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":320,"symbol":"isFlaky","kind":"function","lang":"kotlin","code":"@SuppressLint(\"NewApi\")\n private fun ExtensionContext.isFlaky(): Boolean =\n (testMethod.orElseGet { null }?.isAnnotationPresent(Flaky::class.java) == true) ||\n (testClass.orElseGet { null }?.isAnnotationPresent(Flaky::class.java) == true)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":325,"symbol":"logEvents","kind":"function","lang":"kotlin","code":"@Synchronized private fun logEvents() {\n // Will be ineffective if test overrides the listener\n synchronized(clientEventsList) {\n println(\"$testName Events (${clientEventsList.size})\")\n\n for (e in clientEventsList) {\n println(e)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":336,"symbol":"recordedConnectionEventTypes","kind":"function","lang":"kotlin","code":"fun recordedConnectionEventTypes(): List = connectionListener.recordedEventTypes()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpClientTestRule.kt","line":349,"symbol":"plus","kind":"function","lang":"kotlin","code":"private operator fun Throwable?.plus(throwable: Throwable): Throwable {\n if (this != null) {\n addSuppressed(throwable)\n return this\n }\n return throwable\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpDebugLogging.kt","line":30,"symbol":"OkHttpDebugLogging","kind":"object","lang":"kotlin","code":"object OkHttpDebugLogging {\n // Keep references to loggers to prevent their configuration from being GC'd.\n private val configuredLoggers = CopyOnWriteArraySet()\n\n fun enableHttp2() = enable(Http2::class)\n\n fun enableTaskRunner() = enable(TaskRunner::class)\n\n fun logHandler() =\n ConsoleHandler().apply {\n level = Level.FINE\n formatter =\n object : SimpleFormatter() {\n override fun format(record: LogRecord) = String.format(\"[%1\\$tF %1\\$tT] %2\\$s %n\", record.millis, record.message)\n }\n }\n\n fun enable(\n loggerClass: String,\n handler: Handler = logHandler(),\n ): Closeable {\n val logger = Logger.getLogger(loggerClass)\n if (configuredLoggers.add(logger)) {\n logger.addHandler(handler)\n logger.level = Level.FINEST\n }\n return Closeable {\n logger.removeHandler(handler)\n }\n }\n\n fun enable(loggerClass: KClass<*>) = enable(loggerClass.java.name)\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpDebugLogging.kt","line":34,"symbol":"enableHttp2","kind":"function","lang":"kotlin","code":"fun enableHttp2() = enable(Http2::class)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpDebugLogging.kt","line":36,"symbol":"enableTaskRunner","kind":"function","lang":"kotlin","code":"fun enableTaskRunner() = enable(TaskRunner::class)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpDebugLogging.kt","line":38,"symbol":"logHandler","kind":"function","lang":"kotlin","code":"fun logHandler() =\n ConsoleHandler().apply {\n level = Level.FINE\n formatter =\n object : SimpleFormatter() {\n override fun format(record: LogRecord) = String.format(\"[%1\\$tF %1\\$tT] %2\\$s %n\", record.millis, record.message)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpDebugLogging.kt","line":43,"symbol":"format","kind":"function","lang":"kotlin","code":"override fun format(record: LogRecord) = String.format(\"[%1\\$tF %1\\$tT] %2\\$s %n\", record.millis, record.message)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpDebugLogging.kt","line":47,"symbol":"enable","kind":"function","lang":"kotlin","code":"fun enable(\n loggerClass: String,\n handler: Handler = logHandler(),\n ): Closeable {\n val logger = Logger.getLogger(loggerClass)\n if (configuredLoggers.add(logger)) {\n logger.addHandler(handler)\n logger.level = Level.FINEST\n }\n return Closeable {\n logger.removeHandler(handler)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/OkHttpDebugLogging.kt","line":61,"symbol":"enable","kind":"function","lang":"kotlin","code":"fun enable(loggerClass: KClass<*>) = enable(loggerClass.java.name)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":37,"symbol":"RecordingConnectionListener","kind":"class","lang":"kotlin","code":"internal open class RecordingConnectionListener(\n /**\n * An override to ignore the normal order that is enforced.\n * EventListeners added by Interceptors will not see all events.\n */\n private val enforceOrder: Boolean = true,\n) : ConnectionListener() {\n val eventSequence = LinkedBlockingQueue()\n\n private val forbiddenLocks = mutableSetOf()\n\n /** The timestamp of the last taken event, used to measure elapsed time between events. */\n private var lastTimestampNs: Long? = null\n\n /** Confirm that the thread does not hold a lock on `lock` during the callback. */\n fun forbidLock(lock: Any) {\n forbiddenLocks.add(lock)\n }\n\n /**\n * Removes recorded events up to (and including) an event is found whose class equals [eventClass]\n * and returns it.\n */\n fun removeUpToEvent(eventClass: Class): T {\n val fullEventSequence = eventSequence.toList()\n try {\n while (true) {\n val event = takeEvent()\n if (eventClass.isInstance(event)) {\n return eventClass.cast(event)\n }\n }\n } catch (e: NoSuchElementException) {\n throw AssertionError(\"full event sequence: $fullEventSequence\", e)\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":52,"symbol":"forbidLock","kind":"function","lang":"kotlin","doc":"Confirm that the thread does not hold a lock on `lock` during the callback.","code":"fun forbidLock(lock: Any) {\n forbiddenLocks.add(lock)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":60,"symbol":"removeUpToEvent","kind":"function","lang":"kotlin","doc":"Removes recorded events up to (and including) an event is found whose class equals [eventClass] and returns it.","code":"fun removeUpToEvent(eventClass: Class): T {\n val fullEventSequence = eventSequence.toList()\n try {\n while (true) {\n val event = takeEvent()\n if (eventClass.isInstance(event)) {\n return eventClass.cast(event)\n }\n }\n } catch (e: NoSuchElementException) {\n throw AssertionError(\"full event sequence: $fullEventSequence\", e)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":82,"symbol":"takeEvent","kind":"function","lang":"kotlin","doc":"@param eventClass a class to assert that the returned event is an instance of, or null to take any event class. @param elapsedMs the time in milliseconds elapsed since the immediately-preceding event, or -1L to take any duration.","code":"fun takeEvent(\n eventClass: Class? = null,\n elapsedMs: Long = -1L,\n ): ConnectionEvent {\n val result = eventSequence.take()\n val actualElapsedNs = result.timestampNs - (lastTimestampNs ?: result.timestampNs)\n lastTimestampNs = result.timestampNs\n\n if (eventClass != null) {\n assertThat(result).isInstanceOf(eventClass)\n }\n\n if (elapsedMs != -1L) {\n assertThat(\n TimeUnit.NANOSECONDS\n .toMillis(actualElapsedNs)\n .toDouble(),\n ).isCloseTo(elapsedMs.toDouble(), 100.0)\n }\n\n return result\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":105,"symbol":"recordedEventTypes","kind":"function","lang":"kotlin","code":"fun recordedEventTypes() = eventSequence.map { it.name }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":107,"symbol":"clearAllEvents","kind":"function","lang":"kotlin","code":"fun clearAllEvents() {\n while (eventSequence.isNotEmpty()) {\n takeEvent()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":113,"symbol":"logEvent","kind":"function","lang":"kotlin","code":"private fun logEvent(e: ConnectionEvent) {\n if (e.connection != null) {\n assertThat(Thread.holdsLock(e.connection), \"Called with lock $${e.connection}\")\n .isFalse()\n }\n for (lock in forbiddenLocks) {\n assertThat(Thread.holdsLock(lock), \"Called with lock $lock\")\n .isFalse()\n }\n\n if (enforceOrder) {\n checkForStartEvent(e)\n }\n\n eventSequence.offer(e)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":130,"symbol":"checkForStartEvent","kind":"function","lang":"kotlin","code":"private fun checkForStartEvent(e: ConnectionEvent) {\n if (eventSequence.isEmpty()) {\n assertThat(e).isInstanceOf(ConnectionEvent.ConnectStart::class.java)\n } else {\n eventSequence.forEach loop@{\n when (e.closes(it)) {\n null -> return\n\n // no open event\n true -> return\n\n // found open event\n false -> return@loop // this is not the open event so continue\n }\n }\n Assertions.fail(\"event $e without matching start event\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":149,"symbol":"connectStart","kind":"function","lang":"kotlin","code":"override fun connectStart(\n route: Route,\n call: Call,\n ) = logEvent(ConnectionEvent.ConnectStart(System.nanoTime(), route, call))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":154,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n route: Route,\n call: Call,\n failure: IOException,\n ) = logEvent(\n ConnectionEvent.ConnectFailed(System.nanoTime(), route, call, failure),\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":162,"symbol":"connectEnd","kind":"function","lang":"kotlin","code":"override fun connectEnd(\n connection: Connection,\n route: Route,\n call: Call,\n ) {\n logEvent(ConnectionEvent.ConnectEnd(System.nanoTime(), connection, route, call))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":170,"symbol":"connectionClosed","kind":"function","lang":"kotlin","code":"override fun connectionClosed(connection: Connection) = logEvent(ConnectionEvent.ConnectionClosed(System.nanoTime(), connection))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":172,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n connection: Connection,\n call: Call,\n ) {\n logEvent(ConnectionEvent.ConnectionAcquired(System.nanoTime(), connection, call))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":179,"symbol":"connectionReleased","kind":"function","lang":"kotlin","code":"override fun connectionReleased(\n connection: Connection,\n call: Call,\n ) {\n if (eventSequence.find { it is ConnectionEvent.ConnectStart && it.connection == connection } != null && connection is RealConnection) {\n if (connection.noNewExchanges) {\n assertThat(eventSequence).matchesPredicate { deque ->\n deque.any { it is NoNewExchanges && it.connection == connection }\n }\n }\n }\n\n logEvent(ConnectionEvent.ConnectionReleased(System.nanoTime(), connection, call))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingConnectionListener.kt","line":194,"symbol":"noNewExchanges","kind":"function","lang":"kotlin","code":"override fun noNewExchanges(connection: Connection) = logEvent(NoNewExchanges(System.nanoTime(), connection))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingCookieJar.kt","line":23,"symbol":"RecordingCookieJar","kind":"class","lang":"kotlin","code":"class RecordingCookieJar : CookieJar {\n private val requestCookies: Deque> = ArrayDeque()\n private val responseCookies: Deque> = ArrayDeque()\n\n fun enqueueRequestCookies(vararg cookies: Cookie) {\n requestCookies.add(cookies.toList())\n }\n\n fun takeResponseCookies(): List = responseCookies.removeFirst()\n\n fun assertResponseCookies(vararg cookies: String?) {\n assertThat(takeResponseCookies().map(Cookie::toString)).containsExactly(*cookies)\n }\n\n override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) {\n responseCookies.add(cookies)\n }\n\n override fun loadForRequest(url: HttpUrl): List = if (requestCookies.isEmpty()) emptyList() else requestCookies.removeFirst()\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingCookieJar.kt","line":27,"symbol":"enqueueRequestCookies","kind":"function","lang":"kotlin","code":"fun enqueueRequestCookies(vararg cookies: Cookie) {\n requestCookies.add(cookies.toList())\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingCookieJar.kt","line":31,"symbol":"takeResponseCookies","kind":"function","lang":"kotlin","code":"fun takeResponseCookies(): List = responseCookies.removeFirst()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingCookieJar.kt","line":33,"symbol":"assertResponseCookies","kind":"function","lang":"kotlin","code":"fun assertResponseCookies(vararg cookies: String?) {\n assertThat(takeResponseCookies().map(Cookie::toString)).containsExactly(*cookies)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingCookieJar.kt","line":37,"symbol":"saveFromResponse","kind":"function","lang":"kotlin","code":"override fun saveFromResponse(\n url: HttpUrl,\n cookies: List,\n ) {\n responseCookies.add(cookies)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingCookieJar.kt","line":44,"symbol":"loadForRequest","kind":"function","lang":"kotlin","code":"override fun loadForRequest(url: HttpUrl): List = if (requestCookies.isEmpty()) emptyList() else requestCookies.removeFirst()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingHostnameVerifier.kt","line":21,"symbol":"RecordingHostnameVerifier","kind":"class","lang":"kotlin","code":"class RecordingHostnameVerifier : HostnameVerifier {\n @JvmField\n val calls: MutableList = mutableListOf()\n\n @Synchronized override fun verify(\n hostname: String,\n session: SSLSession,\n ): Boolean {\n calls.add(\"verify $hostname\")\n return true\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/RecordingHostnameVerifier.kt","line":25,"symbol":"verify","kind":"function","lang":"kotlin","code":"@Synchronized override fun verify(\n hostname: String,\n session: SSLSession,\n ): Boolean {\n calls.add(\"verify $hostname\")\n return true\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/SimpleProvider.kt","line":23,"symbol":"SimpleProvider","kind":"class","lang":"kotlin","code":"abstract class SimpleProvider : ArgumentsProvider {\n @Suppress(\"OVERRIDE_DEPRECATION\")\n override fun provideArguments(context: ExtensionContext) = arguments().map { Arguments.of(it) }.stream()\n\n @Throws(Exception::class)\n abstract fun arguments(): List\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/SimpleProvider.kt","line":24,"symbol":"provideArguments","kind":"function","lang":"kotlin","code":"@Suppress(\"OVERRIDE_DEPRECATION\")\n override fun provideArguments(context: ExtensionContext) = arguments().map { Arguments.of(it) }.stream()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/SimpleProvider.kt","line":27,"symbol":"arguments","kind":"function","lang":"kotlin","code":"@Throws(Exception::class)\n abstract fun arguments(): List"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/SpecificHostSocketFactory.kt","line":28,"symbol":"SpecificHostSocketFactory","kind":"class","lang":"kotlin","doc":"A [SocketFactory] that redirects connections to [defaultAddress] or specific overridden address via [set].","code":"class SpecificHostSocketFactory(\n val defaultAddress: InetSocketAddress?,\n) : DelegatingSocketFactory(getDefault()) {\n private val hostMapping = mutableMapOf()\n\n /** Sets the [real] address for [requested]. */\n operator fun set(\n requested: InetAddress,\n real: InetSocketAddress,\n ) {\n hostMapping[requested] = real\n }\n\n override fun createSocket(): Socket =\n object : Socket() {\n override fun connect(\n endpoint: SocketAddress?,\n timeout: Int,\n ) {\n val requested = (endpoint as InetSocketAddress)\n val inetSocketAddress = hostMapping[requested.address] ?: defaultAddress ?: requested\n Platform.get().log(\"Socket connection to: $inetSocketAddress was: $requested\")\n super.connect(inetSocketAddress, timeout)\n }\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/SpecificHostSocketFactory.kt","line":34,"symbol":"set","kind":"function","lang":"kotlin","doc":"Sets the [real] address for [requested].","code":"operator fun set(\n requested: InetAddress,\n real: InetSocketAddress,\n ) {\n hostMapping[requested] = real\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/SpecificHostSocketFactory.kt","line":41,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(): Socket =\n object : Socket() {\n override fun connect(\n endpoint: SocketAddress?,\n timeout: Int,\n ) {\n val requested = (endpoint as InetSocketAddress)\n val inetSocketAddress = hostMapping[requested.address] ?: defaultAddress ?: requested\n Platform.get().log(\"Socket connection to: $inetSocketAddress was: $requested\")\n super.connect(inetSocketAddress, timeout)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/SpecificHostSocketFactory.kt","line":43,"symbol":"connect","kind":"function","lang":"kotlin","code":"override fun connect(\n endpoint: SocketAddress?,\n timeout: Int,\n ) {\n val requested = (endpoint as InetSocketAddress)\n val inetSocketAddress = hostMapping[requested.address] ?: defaultAddress ?: requested\n Platform.get().log(\"Socket connection to: $inetSocketAddress was: $requested\")\n super.connect(inetSocketAddress, timeout)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilCommon.kt","line":25,"symbol":"String","kind":"function","lang":"kotlin","code":"fun String(vararg codePoints: Int): String {\n val buffer = Buffer()\n for (codePoint in codePoints) {\n buffer.writeUtf8CodePoint(codePoint)\n }\n return buffer.readUtf8()\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":30,"symbol":"TestUtil","kind":"object","lang":"kotlin","code":"object TestUtil {\n @JvmField\n val UNREACHABLE_ADDRESS_IPV4 = InetSocketAddress(\"198.51.100.1\", 8080)\n val UNREACHABLE_ADDRESS_IPV6 = InetSocketAddress(\"::ffff:198.51.100.1\", 8080)\n\n /** See `org.graalvm.nativeimage.ImageInfo`. */\n @JvmStatic val isGraalVmImage = System.getProperty(\"org.graalvm.nativeimage.imagecode\") != null\n\n @JvmStatic\n fun headerEntries(vararg elements: String?): List
= List(elements.size / 2) { Header(elements[it * 2]!!, elements[it * 2 + 1]!!) }\n\n @JvmStatic\n fun repeat(\n c: Char,\n count: Int,\n ): String {\n val array = CharArray(count)\n Arrays.fill(array, c)\n return String(array)\n }\n\n /**\n * Okio buffers are internally implemented as a linked list of arrays. Usually this implementation\n * detail is invisible to the caller, but subtle use of certain APIs may depend on these internal\n * structures.\n *\n * We make such subtle calls in [okhttp3.internal.ws.MessageInflater] because we try to read a\n * compressed stream that is terminated in a web socket frame even though the DEFLATE stream is\n * not terminated.\n *\n * Use this method to create a degenerate Okio Buffer where each byte is in a separate segment of\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":38,"symbol":"headerEntries","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun headerEntries(vararg elements: String?): List
= List(elements.size / 2) { Header(elements[it * 2]!!, elements[it * 2 + 1]!!) }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":41,"symbol":"repeat","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun repeat(\n c: Char,\n count: Int,\n ): String {\n val array = CharArray(count)\n Arrays.fill(array, c)\n return String(array)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":63,"symbol":"fragmentBuffer","kind":"function","lang":"kotlin","doc":"compressed stream that is terminated in a web socket frame even though the DEFLATE stream is not terminated. Use this method to create a degenerate Okio Buffer where each byte is in a separate segment of the internal list.","code":"@JvmStatic\n fun fragmentBuffer(buffer: Buffer): Buffer {\n // Write each byte into a new buffer, then clone it so that the segments are shared.\n // Shared segments cannot be compacted so we'll get a long chain of short segments.\n val result = Buffer()\n while (!buffer.exhausted()) {\n val box = Buffer()\n box.write(buffer, 1)\n result.write(box.copy(), 1)\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":76,"symbol":"isDescendentOf","kind":"function","lang":"kotlin","code":"tailrec fun File.isDescendentOf(directory: File): Boolean {\n val parentFile = parentFile ?: return false\n if (parentFile == directory) return true\n return parentFile.isDescendentOf(directory)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":87,"symbol":"awaitGarbageCollection","kind":"function","lang":"kotlin","doc":"See FinalizationTester for discussion on how to best trigger GC in tests. https://android.googlesource.com/platform/libcore/+/master/support/src/test/java/libcore/ java/lang/ref/FinalizationTester.java","code":"@Throws(Exception::class)\n @JvmStatic\n fun awaitGarbageCollection() {\n Runtime.getRuntime().gc()\n Thread.sleep(100)\n System.runFinalization()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":95,"symbol":"assumeNetwork","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun assumeNetwork() {\n try {\n InetAddress.getByName(\"www.google.com\")\n } catch (uhe: UnknownHostException) {\n assumeTrue(false, \"requires network\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":104,"symbol":"assumeNotWindows","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun assumeNotWindows() {\n assumeFalse(windows, \"This test fails on Windows.\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":119,"symbol":"assertSuppressed","kind":"function","lang":"kotlin","doc":"Make assertions about the suppressed exceptions on this. Prefer this over making direct calls so tests pass on GraalVM, where suppressed exceptions are silently discarded. https://github.com/oracle/graal/issues/3008","code":"@JvmStatic\n fun Throwable.assertSuppressed(block: (List<@JvmSuppressWildcards Throwable>) -> Unit) {\n if (isGraalVmImage) return\n block(suppressed.toList())\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":125,"symbol":"threadFactory","kind":"function","lang":"kotlin","code":"@JvmStatic\n fun threadFactory(name: String): ThreadFactory =\n object : ThreadFactory {\n private var nextId = 1\n\n override fun newThread(runnable: Runnable): Thread = Thread(runnable, \"$name-${nextId++}\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":130,"symbol":"newThread","kind":"function","lang":"kotlin","code":"override fun newThread(runnable: Runnable): Thread = Thread(runnable, \"$name-${nextId++}\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestUtilJvm.kt","line":134,"symbol":"getEnv","kind":"function","lang":"kotlin","code":"fun getEnv(name: String) = System.getenv(name)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":57,"symbol":"TestValueFactory","kind":"class","lang":"kotlin","doc":"it easy to get sample values to use in such tests. This class is pretty fast and loose with default values: it attempts to provide values that are well-formed, but doesn't guarantee values are internally consistent. Callers must take care to configure the factory when sample values impact the correctness of the test.","code":"class TestValueFactory : Closeable {\n var taskFaker: TaskFaker = TaskFaker()\n var taskRunner: TaskRunner = taskFaker.taskRunner\n var dns: Dns = Dns.SYSTEM\n var proxy: Proxy = Proxy.NO_PROXY\n var proxySelector: ProxySelector = RecordingProxySelector()\n var proxyAuthenticator: Authenticator = RecordingOkAuthenticator(\"password\", null)\n var connectionSpecs: List =\n listOf(\n ConnectionSpec.MODERN_TLS,\n ConnectionSpec.COMPATIBLE_TLS,\n ConnectionSpec.CLEARTEXT,\n )\n var protocols: List =\n listOf(\n Protocol.HTTP_1_1,\n )\n var handshakeCertificates: HandshakeCertificates = localhost()\n var sslSocketFactory: SSLSocketFactory? = handshakeCertificates.sslSocketFactory()\n var hostnameVerifier: HostnameVerifier? = HttpsURLConnection.getDefaultHostnameVerifier()\n var uriHost: String = \"example.com\"\n var uriPort: Int = 1\n\n fun newConnection(\n pool: RealConnectionPool,\n route: Route,\n idleAtNanos: Long = Long.MAX_VALUE,\n taskRunner: TaskRunner = this.taskRunner,\n ): RealConnection {\n val result =\n RealConnection.newTestConnection(\n taskRunner = taskRunner,\n connectionPool = pool,\n route "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":80,"symbol":"newConnection","kind":"function","lang":"kotlin","code":"fun newConnection(\n pool: RealConnectionPool,\n route: Route,\n idleAtNanos: Long = Long.MAX_VALUE,\n taskRunner: TaskRunner = this.taskRunner,\n ): RealConnection {\n val result =\n RealConnection.newTestConnection(\n taskRunner = taskRunner,\n connectionPool = pool,\n route = route,\n socket = Socket(),\n idleAtNs = idleAtNanos,\n )\n result.withLock { pool.put(result) }\n return result\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":98,"symbol":"newConnectionPool","kind":"function","lang":"kotlin","code":"fun newConnectionPool(\n taskRunner: TaskRunner = this.taskRunner,\n maxIdleConnections: Int = Int.MAX_VALUE,\n ): RealConnectionPool =\n RealConnectionPool(\n taskRunner = taskRunner,\n maxIdleConnections = maxIdleConnections,\n keepAliveDuration = 100L,\n timeUnit = TimeUnit.NANOSECONDS,\n connectionListener = ConnectionListener.NONE,\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":111,"symbol":"newAddress","kind":"function","lang":"kotlin","doc":"Returns an address that's without an SSL socket factory or hostname verifier.","code":"fun newAddress(\n uriHost: String = this.uriHost,\n uriPort: Int = this.uriPort,\n proxy: Proxy? = null,\n proxySelector: ProxySelector = this.proxySelector,\n ): Address =\n Address(\n uriHost = uriHost,\n uriPort = uriPort,\n dns = dns,\n socketFactory = Platform.get().socketFactory,\n sslSocketFactory = null,\n hostnameVerifier = null,\n certificatePinner = null,\n proxyAuthenticator = proxyAuthenticator,\n proxy = proxy,\n protocols = protocols,\n connectionSpecs = connectionSpecs,\n proxySelector = proxySelector,\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":132,"symbol":"newHttpsAddress","kind":"function","lang":"kotlin","code":"fun newHttpsAddress(\n uriHost: String = this.uriHost,\n uriPort: Int = this.uriPort,\n proxy: Proxy? = null,\n proxySelector: ProxySelector = this.proxySelector,\n sslSocketFactory: SSLSocketFactory? = this.sslSocketFactory,\n hostnameVerifier: HostnameVerifier? = this.hostnameVerifier,\n ): Address =\n Address(\n uriHost = uriHost,\n uriPort = uriPort,\n dns = dns,\n socketFactory = Platform.get().socketFactory,\n sslSocketFactory = sslSocketFactory,\n hostnameVerifier = hostnameVerifier,\n certificatePinner = null,\n proxyAuthenticator = proxyAuthenticator,\n proxy = proxy,\n protocols = protocols,\n connectionSpecs = connectionSpecs,\n proxySelector = proxySelector,\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":155,"symbol":"newRoute","kind":"function","lang":"kotlin","code":"fun newRoute(\n address: Address = newAddress(),\n proxy: Proxy = this.proxy,\n socketAddress: InetSocketAddress = InetSocketAddress.createUnresolved(uriHost, uriPort),\n ): Route =\n Route(\n address = address,\n proxy = proxy,\n socketAddress = socketAddress,\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":166,"symbol":"newChain","kind":"function","lang":"kotlin","code":"fun newChain(call: RealCall): RealInterceptorChain =\n RealInterceptorChain(\n call = call,\n interceptors = listOf(),\n index = 0,\n exchange = null,\n request = call.request(),\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":175,"symbol":"newRoutePlanner","kind":"function","lang":"kotlin","code":"fun newRoutePlanner(\n client: OkHttpClient,\n address: Address = newAddress(),\n ): RealRoutePlanner {\n val call = RealCall(client, Request(address.url), forWebSocket = false)\n val chain = newChain(call)\n return RealRoutePlanner(\n taskRunner = client.taskRunner,\n connectionPool = client.connectionPool.delegate,\n readTimeoutMillis = client.readTimeoutMillis,\n writeTimeoutMillis = client.writeTimeoutMillis,\n socketConnectTimeoutMillis = chain.connectTimeoutMillis,\n socketReadTimeoutMillis = chain.readTimeoutMillis,\n pingIntervalMillis = client.pingIntervalMillis,\n retryOnConnectionFailure = client.retryOnConnectionFailure,\n fastFallback = client.fastFallback,\n address = address,\n routeDatabase = client.routeDatabase,\n call = call,\n request = call.request(),\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/TestValueFactory.kt","line":198,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n taskFaker.close()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseRequestInterceptor.kt","line":27,"symbol":"UppercaseRequestInterceptor","kind":"class","lang":"kotlin","doc":"Rewrites the request body sent to the server to be all uppercase.","code":"class UppercaseRequestInterceptor : Interceptor {\n @Throws(IOException::class)\n override fun intercept(chain: Chain): Response = chain.proceed(uppercaseRequest(chain.request()))\n\n /** Returns a request that transforms `request` to be all uppercase. */\n private fun uppercaseRequest(request: Request): Request {\n val uppercaseBody: RequestBody =\n object : ForwardingRequestBody(request.body) {\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n delegate().writeTo(uppercaseSink(sink).buffer())\n }\n }\n return request\n .newBuilder()\n .method(request.method, uppercaseBody)\n .build()\n }\n\n private fun uppercaseSink(sink: Sink): Sink =\n object : ForwardingSink(sink) {\n @Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n val bytes = source.readByteString(byteCount)\n delegate.write(\n Buffer()\n .write(bytes.toAsciiUppercase()),\n byteCount,\n )\n }\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseRequestInterceptor.kt","line":28,"symbol":"intercept","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun intercept(chain: Chain): Response = chain.proceed(uppercaseRequest(chain.request()))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseRequestInterceptor.kt","line":32,"symbol":"uppercaseRequest","kind":"function","lang":"kotlin","doc":"Returns a request that transforms `request` to be all uppercase.","code":"private fun uppercaseRequest(request: Request): Request {\n val uppercaseBody: RequestBody =\n object : ForwardingRequestBody(request.body) {\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n delegate().writeTo(uppercaseSink(sink).buffer())\n }\n }\n return request\n .newBuilder()\n .method(request.method, uppercaseBody)\n .build()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseRequestInterceptor.kt","line":35,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n delegate().writeTo(uppercaseSink(sink).buffer())\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseRequestInterceptor.kt","line":46,"symbol":"uppercaseSink","kind":"function","lang":"kotlin","code":"private fun uppercaseSink(sink: Sink): Sink =\n object : ForwardingSink(sink) {\n @Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n val bytes = source.readByteString(byteCount)\n delegate.write(\n Buffer()\n .write(bytes.toAsciiUppercase()),\n byteCount,\n )\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseRequestInterceptor.kt","line":48,"symbol":"write","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n val bytes = source.readByteString(byteCount)\n delegate.write(\n Buffer()\n .write(bytes.toAsciiUppercase()),\n byteCount,\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseResponseInterceptor.kt","line":26,"symbol":"UppercaseResponseInterceptor","kind":"class","lang":"kotlin","doc":"Rewrites the response body returned from the server to be all uppercase.","code":"class UppercaseResponseInterceptor : Interceptor {\n @Throws(IOException::class)\n override fun intercept(chain: Chain): Response = uppercaseResponse(chain.proceed(chain.request()))\n\n private fun uppercaseResponse(response: Response): Response {\n val uppercaseBody: ResponseBody =\n object : ForwardingResponseBody(response.body) {\n override fun source(): BufferedSource = uppercaseSource(delegate().source()).buffer()\n }\n return response\n .newBuilder()\n .body(uppercaseBody)\n .build()\n }\n\n private fun uppercaseSource(source: BufferedSource): ForwardingSource {\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val buffer = Buffer()\n val read = delegate.read(buffer, byteCount)\n if (read != -1L) {\n sink.write(buffer.readByteString().toAsciiUppercase())\n }\n return read\n }\n }\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseResponseInterceptor.kt","line":27,"symbol":"intercept","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun intercept(chain: Chain): Response = uppercaseResponse(chain.proceed(chain.request()))"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseResponseInterceptor.kt","line":30,"symbol":"uppercaseResponse","kind":"function","lang":"kotlin","code":"private fun uppercaseResponse(response: Response): Response {\n val uppercaseBody: ResponseBody =\n object : ForwardingResponseBody(response.body) {\n override fun source(): BufferedSource = uppercaseSource(delegate().source()).buffer()\n }\n return response\n .newBuilder()\n .body(uppercaseBody)\n .build()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseResponseInterceptor.kt","line":33,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(): BufferedSource = uppercaseSource(delegate().source()).buffer()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseResponseInterceptor.kt","line":41,"symbol":"uppercaseSource","kind":"function","lang":"kotlin","code":"private fun uppercaseSource(source: BufferedSource): ForwardingSource {\n return object : ForwardingSource(source) {\n @Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val buffer = Buffer()\n val read = delegate.read(buffer, byteCount)\n if (read != -1L) {\n sink.write(buffer.readByteString().toAsciiUppercase())\n }\n return read\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/UppercaseResponseInterceptor.kt","line":43,"symbol":"read","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val buffer = Buffer()\n val read = delegate.read(buffer, byteCount)\n if (read != -1L) {\n sink.write(buffer.readByteString().toAsciiUppercase())\n }\n return read\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/RecordingOkAuthenticator.kt","line":24,"symbol":"RecordingOkAuthenticator","kind":"class","lang":"kotlin","code":"class RecordingOkAuthenticator(\n val credential: String?,\n val scheme: String?,\n) : Authenticator {\n val responses = mutableListOf()\n val routes = mutableListOf()\n\n fun onlyResponse() = responses.single()\n\n fun onlyRoute() = routes.single()\n\n @Throws(IOException::class)\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? {\n if (route == null) throw NullPointerException(\"route == null\")\n responses += response\n routes += route\n if (!schemeMatches(response) || credential == null) return null\n val header =\n when (response.code) {\n 407 -> \"Proxy-Authorization\"\n else -> \"Authorization\"\n }\n return response.request\n .newBuilder()\n .addHeader(header, credential)\n .build()\n }\n\n private fun schemeMatches(response: Response): Boolean {\n if (scheme == null) return true\n return response.challenges().any { it.scheme.equals(scheme, ignoreCase = true) }\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/RecordingOkAuthenticator.kt","line":31,"symbol":"onlyResponse","kind":"function","lang":"kotlin","code":"fun onlyResponse() = responses.single()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/RecordingOkAuthenticator.kt","line":33,"symbol":"onlyRoute","kind":"function","lang":"kotlin","code":"fun onlyRoute() = routes.single()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/RecordingOkAuthenticator.kt","line":35,"symbol":"authenticate","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? {\n if (route == null) throw NullPointerException(\"route == null\")\n responses += response\n routes += route\n if (!schemeMatches(response) || credential == null) return null\n val header =\n when (response.code) {\n 407 -> \"Proxy-Authorization\"\n else -> \"Authorization\"\n }\n return response.request\n .newBuilder()\n .addHeader(header, credential)\n .build()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/RecordingOkAuthenticator.kt","line":55,"symbol":"schemeMatches","kind":"function","lang":"kotlin","code":"private fun schemeMatches(response: Response): Boolean {\n if (scheme == null) return true\n return response.challenges().any { it.scheme.equals(scheme, ignoreCase = true) }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":53,"symbol":"TaskFaker","kind":"class","lang":"kotlin","doc":"Task threads release their execution privilege in these ways: * By yielding in [TaskRunner.Backend.coordinatorWait]. * By yielding in [BlockingQueue.poll]. * By completing.","code":"class TaskFaker : Closeable {\n val logger = Logger.getLogger(\"TaskFaker.\" + instance++)\n\n /** Though this executor service may hold many threads, they are not executed concurrently. */\n private val tasksExecutor = Executors.newCachedThreadPool(threadFactory(\"TaskFaker\"))\n\n /**\n * True if this task faker has ever had multiple tasks scheduled to run concurrently. Guarded by\n * `this`.\n */\n var isParallel = false\n\n /** Number of calls to [TaskRunner.Backend.execute]. Guarded by `this`. */\n var executeCallCount = 0\n\n /** Guarded by [taskRunner]. */\n var nanoTime = 0L\n private set\n\n /** Backlog of tasks to run. Only one task runs at a time. Guarded by `this`. */\n private val serialTaskQueue = ArrayDeque()\n\n /** The task that's currently executing. Guarded by `this`. */\n private var currentTask: SerialTask = TestThreadSerialTask\n\n /** The coordinator task if it's waiting, and how it will resume. Guarded by `this`. */\n private var waitingCoordinatorTask: SerialTask? = null\n private var waitingCoordinatorInterrupted = false\n private var waitingCoordinatorNotified = false\n\n /** How many times a new task has been started. Guarded by `this`. */\n private"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":92,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read() = nanoTime"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":99,"symbol":"execute","kind":"function","lang":"kotlin","code":"override fun execute(\n taskRunner: TaskRunner,\n runnable: Runnable,\n ) {\n taskRunner.assertLockHeld()\n\n val queuedTask = RunnableSerialTask(runnable)\n serialTaskQueue += queuedTask\n executeCallCount++\n isParallel = serialTaskQueue.size > 1\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":111,"symbol":"nanoTime","kind":"function","lang":"kotlin","code":"override fun nanoTime() = nanoTime"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":113,"symbol":"coordinatorNotify","kind":"function","lang":"kotlin","code":"override fun coordinatorNotify(taskRunner: TaskRunner) {\n taskRunner.assertLockHeld()\n check(waitingCoordinatorTask != null)\n\n // Queue a task to resume the waiting coordinator.\n serialTaskQueue +=\n object : SerialTask {\n override fun start() {\n taskRunner.assertLockHeld()\n val coordinatorTask = waitingCoordinatorTask\n if (coordinatorTask != null) {\n waitingCoordinatorNotified = true\n currentTask = coordinatorTask\n taskRunner.notifyAll()\n } else {\n startNextTask()\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":120,"symbol":"start","kind":"function","lang":"kotlin","code":"override fun start() {\n taskRunner.assertLockHeld()\n val coordinatorTask = waitingCoordinatorTask\n if (coordinatorTask != null) {\n waitingCoordinatorNotified = true\n currentTask = coordinatorTask\n taskRunner.notifyAll()\n } else {\n startNextTask()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":134,"symbol":"coordinatorWait","kind":"function","lang":"kotlin","code":"override fun coordinatorWait(\n taskRunner: TaskRunner,\n nanos: Long,\n ) {\n taskRunner.assertLockHeld()\n check(waitingCoordinatorTask == null)\n if (nanos == 0L) return\n\n // Yield until notified, interrupted, or the duration elapses.\n val waitUntil = nanoTime + nanos\n val self = currentTask\n waitingCoordinatorTask = self\n waitingCoordinatorNotified = false\n waitingCoordinatorInterrupted = false\n yieldUntil {\n waitingCoordinatorNotified || waitingCoordinatorInterrupted || nanoTime >= waitUntil\n }\n\n waitingCoordinatorTask = null\n waitingCoordinatorNotified = false\n if (waitingCoordinatorInterrupted) {\n waitingCoordinatorInterrupted = false\n throw InterruptedException()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":160,"symbol":"decorate","kind":"function","lang":"kotlin","code":"override fun decorate(queue: BlockingQueue) = TaskFakerBlockingQueue(queue)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":166,"symbol":"runTasks","kind":"function","lang":"kotlin","doc":"Runs all tasks that are ready. Used by the test thread only.","code":"fun runTasks() {\n advanceUntil(nanoTime)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":171,"symbol":"advanceUntil","kind":"function","lang":"kotlin","doc":"Advance the simulated clock, then runs tasks that are ready. Used by the test thread only.","code":"fun advanceUntil(newTime: Long) {\n taskRunner.assertLockNotHeld()\n\n taskRunner.withLock {\n check(currentTask == TestThreadSerialTask)\n nanoTime = newTime\n yieldUntil(ResumePriority.AfterOtherTasks)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":182,"symbol":"assertNoMoreTasks","kind":"function","lang":"kotlin","doc":"Confirm all tasks have completed. Used by the test thread only.","code":"fun assertNoMoreTasks() {\n taskRunner.assertLockNotHeld()\n\n taskRunner.withLock {\n assertThat(activeThreads).isEqualTo(0)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":191,"symbol":"interruptCoordinatorThread","kind":"function","lang":"kotlin","doc":"Unblock a waiting task thread. Used by the test thread only.","code":"fun interruptCoordinatorThread() {\n taskRunner.assertLockNotHeld()\n require(currentTask == TestThreadSerialTask)\n\n // Queue a task to interrupt the waiting coordinator.\n serialTaskQueue +=\n object : SerialTask {\n override fun start() {\n taskRunner.assertLockHeld()\n waitingCoordinatorInterrupted = true\n val coordinatorTask = waitingCoordinatorTask ?: error(\"no coordinator waiting\")\n currentTask = coordinatorTask\n taskRunner.notifyAll()\n }\n }\n\n // Let the coordinator process its interruption.\n runTasks()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":198,"symbol":"start","kind":"function","lang":"kotlin","code":"override fun start() {\n taskRunner.assertLockHeld()\n waitingCoordinatorInterrupted = true\n val coordinatorTask = waitingCoordinatorTask ?: error(\"no coordinator waiting\")\n currentTask = coordinatorTask\n taskRunner.notifyAll()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":212,"symbol":"runNextTask","kind":"function","lang":"kotlin","doc":"Ask a single task to proceed. Used by the test thread only.","code":"fun runNextTask() {\n taskRunner.assertLockNotHeld()\n\n taskRunner.withLock {\n val contextSwitchCountBefore = contextSwitchCount\n yieldUntil(ResumePriority.BeforeOtherTasks) {\n contextSwitchCount > contextSwitchCountBefore\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":224,"symbol":"sleep","kind":"function","lang":"kotlin","doc":"Sleep until [durationNanos] elapses. For use by the task threads.","code":"fun sleep(durationNanos: Long) {\n taskRunner.withLock {\n val sleepUntil = nanoTime + durationNanos\n yieldUntil { nanoTime >= sleepUntil }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":235,"symbol":"yield","kind":"function","lang":"kotlin","doc":"Artificially stall until manually resumed by the test thread with [runTasks]. Use this to simulate races in tasks that doesn't have a deterministic sequence.","code":"fun yield() {\n taskRunner.assertLockNotHeld()\n taskRunner.withLock {\n yieldUntil()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":243,"symbol":"yieldUntil","kind":"function","lang":"kotlin","doc":"Process the queue until [condition] returns true.","code":"private tailrec fun yieldUntil(\n strategy: ResumePriority = ResumePriority.AfterEnqueuedTasks,\n condition: () -> Boolean = { true },\n ) {\n taskRunner.assertLockHeld()\n val self = currentTask\n\n val yieldCompleteTask =\n object : SerialTask {\n override fun isReady() = condition()\n\n override fun start() {\n taskRunner.assertLockHeld()\n currentTask = self\n taskRunner.notifyAll()\n }\n }\n\n if (strategy == ResumePriority.BeforeOtherTasks) {\n serialTaskQueue.addFirst(yieldCompleteTask)\n } else {\n serialTaskQueue.addLast(yieldCompleteTask)\n }\n\n val startedTask = startNextTask()\n val otherTasksStarted = startedTask != yieldCompleteTask\n\n try {\n while (currentTask != self) {\n taskRunner.wait()\n }\n } finally {\n serialTaskQueue.remove(yieldCompleteTask)\n }\n\n // If we're yielding until we're exhausted and a task run, keep going until a task doesn't run.\n if (strategy == ResumePriority.AfterOtherTasks && otherTasksStarted) {\n return yieldUntil(strategy, condition)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":252,"symbol":"isReady","kind":"function","lang":"kotlin","code":"override fun isReady() = condition()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":254,"symbol":"start","kind":"function","lang":"kotlin","code":"override fun start() {\n taskRunner.assertLockHeld()\n currentTask = self\n taskRunner.notifyAll()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":284,"symbol":"ResumePriority","kind":"enum","lang":"kotlin","code":"private enum class ResumePriority {\n /** Resumes as soon as the condition is satisfied. */\n BeforeOtherTasks,\n\n /** Resumes after the already-enqueued tasks. */\n AfterEnqueuedTasks,\n\n /** Resumes after all other tasks, including tasks enqueued while yielding. */\n AfterOtherTasks,\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":286,"symbol":"BeforeOtherTasks","kind":"enum_member","lang":"kotlin","doc":"Resumes as soon as the condition is satisfied.","code":"BeforeOtherTasks"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":289,"symbol":"AfterEnqueuedTasks","kind":"enum_member","lang":"kotlin","doc":"Resumes after the already-enqueued tasks.","code":"AfterEnqueuedTasks"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":292,"symbol":"AfterOtherTasks","kind":"enum_member","lang":"kotlin","doc":"Resumes after all other tasks, including tasks enqueued while yielding.","code":"AfterOtherTasks"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":296,"symbol":"startNextTask","kind":"function","lang":"kotlin","doc":"Returns the task that was started, or null if there were no tasks to start.","code":"private fun startNextTask(): SerialTask? {\n taskRunner.assertLockHeld()\n\n val index = serialTaskQueue.indexOfFirst { it.isReady() }\n if (index == -1) return null\n\n val nextTask = serialTaskQueue.removeAt(index)\n currentTask = nextTask\n contextSwitchCount++\n nextTask.start()\n return nextTask\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":309,"symbol":"SerialTask","kind":"interface","lang":"kotlin","code":"private interface SerialTask {\n /** Returns true if this task is ready to start. */\n fun isReady() = true\n\n /** Do this task's work, and then start another, such as by calling [startNextTask]. */\n fun start()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":311,"symbol":"isReady","kind":"function","lang":"kotlin","doc":"Returns true if this task is ready to start.","code":"fun isReady() = true"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":314,"symbol":"start","kind":"function","lang":"kotlin","doc":"Do this task's work, and then start another, such as by calling [startNextTask].","code":"fun start()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":317,"symbol":"TestThreadSerialTask","kind":"object","lang":"kotlin","code":"private object TestThreadSerialTask : SerialTask {\n override fun start() = error(\"unexpected call\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":318,"symbol":"start","kind":"function","lang":"kotlin","code":"override fun start() = error(\"unexpected call\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":321,"symbol":"RunnableSerialTask","kind":"class","lang":"kotlin","code":"inner class RunnableSerialTask(\n private val runnable: Runnable,\n ) : SerialTask {\n override fun start() {\n taskRunner.assertLockHeld()\n require(currentTask == this)\n activeThreads++\n\n tasksExecutor.execute {\n taskRunner.assertLockNotHeld()\n require(currentTask == this)\n try {\n runnable.run()\n require(currentTask == this) { \"unexpected current task: $currentTask\" }\n } finally {\n taskRunner.withLock {\n activeThreads--\n startNextTask()\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":324,"symbol":"start","kind":"function","lang":"kotlin","code":"override fun start() {\n taskRunner.assertLockHeld()\n require(currentTask == this)\n activeThreads++\n\n tasksExecutor.execute {\n taskRunner.assertLockNotHeld()\n require(currentTask == this)\n try {\n runnable.run()\n require(currentTask == this) { \"unexpected current task: $currentTask\" }\n } finally {\n taskRunner.withLock {\n activeThreads--\n startNextTask()\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":349,"symbol":"TaskFakerBlockingQueue","kind":"class","lang":"kotlin","doc":"This blocking queue hooks into a fake clock rather than using regular JVM timing for functions like [poll]. It is only usable within task faker tasks.","code":"private inner class TaskFakerBlockingQueue(\n val delegate: BlockingQueue,\n ) : AbstractQueue(),\n BlockingQueue {\n override val size: Int = delegate.size\n\n private var editCount = 0\n\n override fun poll(): T = delegate.poll()\n\n override fun poll(\n timeout: Long,\n unit: TimeUnit,\n ): T? {\n return taskRunner.withLock {\n val waitUntil = nanoTime + unit.toNanos(timeout)\n while (true) {\n val result = poll()\n if (result != null) return@withLock result\n if (nanoTime >= waitUntil) return@withLock null\n val editCountBefore = editCount\n yieldUntil { nanoTime >= waitUntil || editCount > editCountBefore }\n }\n // TODO report compiler bug\n TODO(\"Can't get here\")\n }\n }\n\n override fun put(element: T) {\n taskRunner.withLock {\n delegate.put(element)\n editCount++\n }\n }\n\n override fun iterator() = error(\"unsupported\")\n\n override fun offer(e: T) = error(\"unsupported\")\n\n override fun peek(): T = error(\"unsupported\")\n\n override fun offer(\n element: T,\n timeout: Long,\n unit: TimeUnit,\n ) = error(\"unsupported\")\n\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":357,"symbol":"poll","kind":"function","lang":"kotlin","code":"override fun poll(): T = delegate.poll()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":359,"symbol":"poll","kind":"function","lang":"kotlin","code":"override fun poll(\n timeout: Long,\n unit: TimeUnit,\n ): T? {\n return taskRunner.withLock {\n val waitUntil = nanoTime + unit.toNanos(timeout)\n while (true) {\n val result = poll()\n if (result != null) return@withLock result\n if (nanoTime >= waitUntil) return@withLock null\n val editCountBefore = editCount\n yieldUntil { nanoTime >= waitUntil || editCount > editCountBefore }\n }\n // TODO report compiler bug\n TODO(\"Can't get here\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":377,"symbol":"put","kind":"function","lang":"kotlin","code":"override fun put(element: T) {\n taskRunner.withLock {\n delegate.put(element)\n editCount++\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":384,"symbol":"iterator","kind":"function","lang":"kotlin","code":"override fun iterator() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":386,"symbol":"offer","kind":"function","lang":"kotlin","code":"override fun offer(e: T) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":388,"symbol":"peek","kind":"function","lang":"kotlin","code":"override fun peek(): T = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":390,"symbol":"offer","kind":"function","lang":"kotlin","code":"override fun offer(\n element: T,\n timeout: Long,\n unit: TimeUnit,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":396,"symbol":"take","kind":"function","lang":"kotlin","code":"override fun take() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":398,"symbol":"remainingCapacity","kind":"function","lang":"kotlin","code":"override fun remainingCapacity() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":400,"symbol":"drainTo","kind":"function","lang":"kotlin","code":"override fun drainTo(sink: MutableCollection) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":402,"symbol":"drainTo","kind":"function","lang":"kotlin","code":"override fun drainTo(\n sink: MutableCollection,\n maxElements: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":409,"symbol":"isIdle","kind":"function","lang":"kotlin","doc":"Returns true if no tasks have been scheduled. This runs the coordinator for confirmation.","code":"fun isIdle() = taskRunner.activeQueues().isEmpty()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskFaker.kt","line":411,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n tasksExecutor.shutdownNow()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/concurrent/TaskRunnerTesting.kt","line":21,"symbol":"schedule","kind":"function","lang":"kotlin","code":"fun TaskRunner.schedule(\n name: String,\n delay: Duration = 0.milliseconds,\n block: () -> Unit,\n) {\n newQueue().schedule(name, delay.inWholeNanoseconds) {\n block()\n -1L\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":27,"symbol":"DnsEvent","kind":"interface","lang":"kotlin","code":"sealed interface DnsEvent {\n data class Records(\n val last: Boolean,\n val records: List,\n ) : DnsEvent\n\n data class Failure(\n val e: IOException,\n ) : DnsEvent\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":38,"symbol":"toEventsQueue","kind":"function","lang":"kotlin","code":"fun Dns.Call.toEventsQueue(): BlockingQueue {\n val result = LinkedBlockingDeque()\n\n enqueue(\n object : Dns.Callback {\n override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n result.put(DnsEvent.Records(last, records))\n }\n\n override fun onFailure(\n call: Dns.Call,\n e: IOException,\n ) {\n result.put(DnsEvent.Failure(e))\n }\n },\n )\n\n return result\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":43,"symbol":"onRecords","kind":"function","lang":"kotlin","code":"override fun onRecords(\n call: Dns.Call,\n last: Boolean,\n records: List,\n ) {\n result.put(DnsEvent.Records(last, records))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":51,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Dns.Call,\n e: IOException,\n ) {\n result.put(DnsEvent.Failure(e))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":67,"symbol":"invoke","kind":"function","lang":"kotlin","doc":"Use Burst to call either the blocking API or the non-blocking API, both with a signature that resembles the [InetAddress.getAllByName] API.","code":"operator fun DnsOverHttps.invoke(\n entryPoint: EntryPoint,\n hostname: String,\n): List =\n when (entryPoint) {\n EntryPoint.Lookup -> {\n lookup(hostname)\n }\n\n EntryPoint.NewCall -> {\n buildList {\n val dnsEvents = newCall(Dns.Request(hostname)).toEventsQueue()\n while (true) {\n when (val dnsEvent = dnsEvents.take()) {\n is DnsEvent.Failure -> {\n throw dnsEvent.e\n }\n\n is DnsEvent.Records -> {\n addAll(\n dnsEvent.records\n .filterIsInstance()\n .map { it.address },\n )\n\n if (dnsEvent.last) {\n if (isEmpty()) throw UnknownHostException(\"no results\")\n break\n }\n }\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":108,"symbol":"forceEntryPoint","kind":"function","lang":"kotlin","doc":"Force this instance to use the lookup API or ([LookupDnsCall]), or the call API (and definitely not [LookupDnsCall]). This is for tests that want to defeat OkHttp's implementation detection, so we can exercise all code paths.","code":"fun Dns.forceEntryPoint(entryPoint: EntryPoint): Dns {\n return when (entryPoint) {\n EntryPoint.Lookup -> {\n object : Dns by this {\n override fun newCall(request: Dns.Request) = LookupDnsCall(TaskRunner.INSTANCE, this, request)\n }\n }\n\n EntryPoint.NewCall -> {\n object : Dns by this {\n override fun newCall(request: Dns.Request): Dns.Call {\n val result = this@forceEntryPoint.newCall(request)\n check(result !is LookupDnsCall) {\n \"unexpected call implementation on ${this@forceEntryPoint}\"\n }\n return result\n }\n }\n }\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":112,"symbol":"newCall","kind":"function","lang":"kotlin","code":"override fun newCall(request: Dns.Request) = LookupDnsCall(TaskRunner.INSTANCE, this, request)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":118,"symbol":"newCall","kind":"function","lang":"kotlin","code":"override fun newCall(request: Dns.Request): Dns.Call {\n val result = this@forceEntryPoint.newCall(request)\n check(result !is LookupDnsCall) {\n \"unexpected call implementation on ${this@forceEntryPoint}\"\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":130,"symbol":"EntryPoint","kind":"enum","lang":"kotlin","code":"enum class EntryPoint {\n Lookup,\n NewCall,\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":131,"symbol":"Lookup","kind":"enum_member","lang":"kotlin","code":"Lookup"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/dns/DnsTesting.kt","line":132,"symbol":"NewCall","kind":"enum_member","lang":"kotlin","code":"NewCall"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/AsyncRequestBody.kt","line":27,"symbol":"AsyncRequestBody","kind":"class","lang":"kotlin","doc":"A duplex request body that keeps the provided sinks so they can be written to later.","code":"class AsyncRequestBody : RequestBody() {\n private val requestBodySinks: BlockingQueue = LinkedBlockingQueue()\n\n override fun contentType(): MediaType? = null\n\n override fun writeTo(sink: BufferedSink) {\n requestBodySinks.add(sink)\n }\n\n override fun isDuplex(): Boolean = true\n\n @Throws(InterruptedException::class)\n fun takeSink(): BufferedSink = requestBodySinks.poll(5, SECONDS) ?: throw AssertionError(\"no sink to take\")\n\n fun assertNoMoreSinks() {\n assertTrue(requestBodySinks.isEmpty())\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/AsyncRequestBody.kt","line":30,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType(): MediaType? = null"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/AsyncRequestBody.kt","line":32,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n requestBodySinks.add(sink)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/AsyncRequestBody.kt","line":36,"symbol":"isDuplex","kind":"function","lang":"kotlin","code":"override fun isDuplex(): Boolean = true"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/AsyncRequestBody.kt","line":38,"symbol":"takeSink","kind":"function","lang":"kotlin","code":"@Throws(InterruptedException::class)\n fun takeSink(): BufferedSink = requestBodySinks.poll(5, SECONDS) ?: throw AssertionError(\"no sink to take\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/AsyncRequestBody.kt","line":41,"symbol":"assertNoMoreSinks","kind":"function","lang":"kotlin","code":"fun assertNoMoreSinks() {\n assertTrue(requestBodySinks.isEmpty())\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":29,"symbol":"Action","kind":"type","lang":"kotlin","code":"private typealias Action = (BufferedSocket) -> Unit"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":35,"symbol":"MockSocketHandler","kind":"class","lang":"kotlin","doc":"A scriptable request/response conversation. Create the script by calling methods like [receiveRequest] in the sequence they are run.","code":"class MockSocketHandler : SocketHandler {\n private val actions = LinkedBlockingQueue()\n private val results = LinkedBlockingQueue>()\n\n fun receiveRequest(expected: String) =\n apply {\n actions += { stream ->\n val actual = stream.source.readUtf8(expected.utf8Size())\n if (actual != expected) throw AssertionError(\"$actual != $expected\")\n }\n }\n\n fun exhaustRequest() =\n apply {\n actions += { stream ->\n if (!stream.source.exhausted()) throw AssertionError(\"expected exhausted\")\n }\n }\n\n fun cancelStream() =\n apply {\n actions += { stream -> stream.cancel() }\n }\n\n fun requestIOException() =\n apply {\n actions += { stream ->\n try {\n stream.source.exhausted()\n throw AssertionError(\"expected IOException\")\n } catch (expected: IOException) {\n }\n }\n }\n\n @JvmOverloads\n fun sendResponse(\n s: String,\n responseSent: CountDownLatch = CountDownLatch(1),\n ) = apply {\n actions += { stream ->\n stream.sink.writeUtf8(s)\n stream.sink.flush()\n responseSent.countDown()\n }\n }\n\n fun exhaustResponse() =\n apply {\n actions += { str"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":39,"symbol":"receiveRequest","kind":"function","lang":"kotlin","code":"fun receiveRequest(expected: String) =\n apply {\n actions += { stream ->\n val actual = stream.source.readUtf8(expected.utf8Size())\n if (actual != expected) throw AssertionError(\"$actual != $expected\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":47,"symbol":"exhaustRequest","kind":"function","lang":"kotlin","code":"fun exhaustRequest() =\n apply {\n actions += { stream ->\n if (!stream.source.exhausted()) throw AssertionError(\"expected exhausted\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":54,"symbol":"cancelStream","kind":"function","lang":"kotlin","code":"fun cancelStream() =\n apply {\n actions += { stream -> stream.cancel() }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":59,"symbol":"requestIOException","kind":"function","lang":"kotlin","code":"fun requestIOException() =\n apply {\n actions += { stream ->\n try {\n stream.source.exhausted()\n throw AssertionError(\"expected IOException\")\n } catch (expected: IOException) {\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":70,"symbol":"sendResponse","kind":"function","lang":"kotlin","code":"@JvmOverloads\n fun sendResponse(\n s: String,\n responseSent: CountDownLatch = CountDownLatch(1),\n ) = apply {\n actions += { stream ->\n stream.sink.writeUtf8(s)\n stream.sink.flush()\n responseSent.countDown()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":82,"symbol":"exhaustResponse","kind":"function","lang":"kotlin","code":"fun exhaustResponse() =\n apply {\n actions += { stream -> stream.sink.close() }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":87,"symbol":"sleep","kind":"function","lang":"kotlin","code":"fun sleep(\n duration: Long,\n unit: TimeUnit,\n ) = apply {\n actions += { Thread.sleep(unit.toMillis(duration)) }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":94,"symbol":"handle","kind":"function","lang":"kotlin","code":"override fun handle(socket: Socket) {\n val task = serviceSocketTask(socket.asBufferedSocket())\n results.add(task)\n task.run()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":101,"symbol":"serviceSocketTask","kind":"function","lang":"kotlin","doc":"Returns a task that processes both request and response from [socket].","code":"private fun serviceSocketTask(socket: BufferedSocket): FutureTask {\n return FutureTask {\n socket.source.use {\n socket.sink.use {\n while (true) {\n val action = actions.poll() ?: break\n action(socket)\n }\n }\n }\n return@FutureTask null\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/duplex/MockSocketHandler.kt","line":116,"symbol":"awaitSuccess","kind":"function","lang":"kotlin","doc":"Returns once all stream actions complete successfully.","code":"fun awaitSuccess() {\n val futureTask =\n results.poll(5, TimeUnit.SECONDS)\n ?: throw AssertionError(\"no onRequest call received\")\n futureTask.get(5, TimeUnit.SECONDS)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/http/RecordingProxySelector.kt","line":29,"symbol":"RecordingProxySelector","kind":"class","lang":"kotlin","code":"class RecordingProxySelector : ProxySelector() {\n @JvmField val proxies = mutableListOf()\n\n val requestedUris = mutableListOf()\n val failures = mutableListOf()\n\n override fun select(uri: URI): List {\n requestedUris.add(uri)\n return proxies\n }\n\n fun assertRequests(vararg expectedUris: URI?) {\n assertThat(requestedUris).containsExactly(*expectedUris)\n requestedUris.clear()\n }\n\n override fun connectFailed(\n uri: URI,\n sa: SocketAddress,\n ioe: IOException,\n ) {\n val socketAddress = sa as InetSocketAddress\n failures.add(format(\"%s %s:%d %s\", uri, socketAddress, socketAddress.port, ioe.message!!))\n }\n\n override fun toString() = \"RecordingProxySelector\"\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/http/RecordingProxySelector.kt","line":35,"symbol":"select","kind":"function","lang":"kotlin","code":"override fun select(uri: URI): List {\n requestedUris.add(uri)\n return proxies\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/http/RecordingProxySelector.kt","line":40,"symbol":"assertRequests","kind":"function","lang":"kotlin","code":"fun assertRequests(vararg expectedUris: URI?) {\n assertThat(requestedUris).containsExactly(*expectedUris)\n requestedUris.clear()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/http/RecordingProxySelector.kt","line":45,"symbol":"connectFailed","kind":"function","lang":"kotlin","code":"override fun connectFailed(\n uri: URI,\n sa: SocketAddress,\n ioe: IOException,\n ) {\n val socketAddress = sa as InetSocketAddress\n failures.add(format(\"%s %s:%d %s\", uri, socketAddress, socketAddress.port, ioe.message!!))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/internal/http/RecordingProxySelector.kt","line":54,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"RecordingProxySelector\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/okio/LoggingFilesystem.kt","line":24,"symbol":"LoggingFilesystem","kind":"class","lang":"kotlin","code":"class LoggingFilesystem(\n fileSystem: FileSystem,\n) : ForwardingFileSystem(fileSystem) {\n fun log(line: String) {\n println(line)\n }\n\n override fun appendingSink(\n file: Path,\n mustExist: Boolean,\n ): Sink {\n log(\"appendingSink($file)\")\n\n return super.appendingSink(file, mustExist)\n }\n\n override fun atomicMove(\n source: Path,\n target: Path,\n ) {\n log(\"atomicMove($source, $target)\")\n\n super.atomicMove(source, target)\n }\n\n override fun createDirectory(\n dir: Path,\n mustCreate: Boolean,\n ) {\n log(\"createDirectory($dir)\")\n\n super.createDirectory(dir, mustCreate)\n }\n\n override fun delete(\n path: Path,\n mustExist: Boolean,\n ) {\n log(\"delete($path)\")\n\n super.delete(path, mustExist)\n }\n\n override fun sink(\n file: Path,\n mustCreate: Boolean,\n ): Sink {\n log(\"sink($file)\")\n\n return super.sink(file, mustCreate)\n }\n\n override fun source(file: Path): Source {\n log(\"source($file)\")\n\n return super.source(file)\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/okio/LoggingFilesystem.kt","line":27,"symbol":"log","kind":"function","lang":"kotlin","code":"fun log(line: String) {\n println(line)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/okio/LoggingFilesystem.kt","line":31,"symbol":"appendingSink","kind":"function","lang":"kotlin","code":"override fun appendingSink(\n file: Path,\n mustExist: Boolean,\n ): Sink {\n log(\"appendingSink($file)\")\n\n return super.appendingSink(file, mustExist)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/okio/LoggingFilesystem.kt","line":40,"symbol":"atomicMove","kind":"function","lang":"kotlin","code":"override fun atomicMove(\n source: Path,\n target: Path,\n ) {\n log(\"atomicMove($source, $target)\")\n\n super.atomicMove(source, target)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/okio/LoggingFilesystem.kt","line":49,"symbol":"createDirectory","kind":"function","lang":"kotlin","code":"override fun createDirectory(\n dir: Path,\n mustCreate: Boolean,\n ) {\n log(\"createDirectory($dir)\")\n\n super.createDirectory(dir, mustCreate)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/okio/LoggingFilesystem.kt","line":58,"symbol":"delete","kind":"function","lang":"kotlin","code":"override fun delete(\n path: Path,\n mustExist: Boolean,\n ) {\n log(\"delete($path)\")\n\n super.delete(path, mustExist)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/okio/LoggingFilesystem.kt","line":67,"symbol":"sink","kind":"function","lang":"kotlin","code":"override fun sink(\n file: Path,\n mustCreate: Boolean,\n ): Sink {\n log(\"sink($file)\")\n\n return super.sink(file, mustCreate)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/okio/LoggingFilesystem.kt","line":76,"symbol":"source","kind":"function","lang":"kotlin","code":"override fun source(file: Path): Source {\n log(\"source($file)\")\n\n return super.source(file)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":28,"symbol":"DelegatingSSLSession","kind":"class","lang":"kotlin","doc":"An [SSLSession] that delegates all calls.","code":"abstract class DelegatingSSLSession(\n protected val delegate: SSLSession?,\n) : SSLSession {\n override fun getId(): ByteArray = delegate!!.id\n\n override fun getSessionContext(): SSLSessionContext = delegate!!.sessionContext\n\n override fun getCreationTime(): Long = delegate!!.creationTime\n\n override fun getLastAccessedTime(): Long = delegate!!.lastAccessedTime\n\n override fun invalidate() {\n delegate!!.invalidate()\n }\n\n override fun isValid(): Boolean = delegate!!.isValid\n\n override fun putValue(\n s: String,\n o: Any,\n ) {\n delegate!!.putValue(s, o)\n }\n\n override fun getValue(s: String): Any = delegate!!.getValue(s)\n\n override fun removeValue(s: String) {\n delegate!!.removeValue(s)\n }\n\n override fun getValueNames(): Array = delegate!!.valueNames\n\n @Throws(SSLPeerUnverifiedException::class)\n override fun getPeerCertificates(): Array? = delegate!!.peerCertificates\n\n override fun getLocalCertificates(): Array? = delegate!!.localCertificates\n\n @Suppress(\"removal\", \"OVERRIDE_DEPRECATION\")\n @Throws(SSLPeerUnverifiedException::class)\n override fun getPeerCertificateChain(): Array = delegate!!.peerCertificat"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":31,"symbol":"getId","kind":"function","lang":"kotlin","code":"override fun getId(): ByteArray = delegate!!.id"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":33,"symbol":"getSessionContext","kind":"function","lang":"kotlin","code":"override fun getSessionContext(): SSLSessionContext = delegate!!.sessionContext"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":35,"symbol":"getCreationTime","kind":"function","lang":"kotlin","code":"override fun getCreationTime(): Long = delegate!!.creationTime"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":37,"symbol":"getLastAccessedTime","kind":"function","lang":"kotlin","code":"override fun getLastAccessedTime(): Long = delegate!!.lastAccessedTime"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":39,"symbol":"invalidate","kind":"function","lang":"kotlin","code":"override fun invalidate() {\n delegate!!.invalidate()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":43,"symbol":"isValid","kind":"function","lang":"kotlin","code":"override fun isValid(): Boolean = delegate!!.isValid"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":45,"symbol":"putValue","kind":"function","lang":"kotlin","code":"override fun putValue(\n s: String,\n o: Any,\n ) {\n delegate!!.putValue(s, o)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":52,"symbol":"getValue","kind":"function","lang":"kotlin","code":"override fun getValue(s: String): Any = delegate!!.getValue(s)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":54,"symbol":"removeValue","kind":"function","lang":"kotlin","code":"override fun removeValue(s: String) {\n delegate!!.removeValue(s)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":58,"symbol":"getValueNames","kind":"function","lang":"kotlin","code":"override fun getValueNames(): Array = delegate!!.valueNames"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":60,"symbol":"getPeerCertificates","kind":"function","lang":"kotlin","code":"@Throws(SSLPeerUnverifiedException::class)\n override fun getPeerCertificates(): Array? = delegate!!.peerCertificates"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":63,"symbol":"getLocalCertificates","kind":"function","lang":"kotlin","code":"override fun getLocalCertificates(): Array? = delegate!!.localCertificates"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":65,"symbol":"getPeerCertificateChain","kind":"function","lang":"kotlin","code":"@Suppress(\"removal\", \"OVERRIDE_DEPRECATION\")\n @Throws(SSLPeerUnverifiedException::class)\n override fun getPeerCertificateChain(): Array = delegate!!.peerCertificateChain"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":69,"symbol":"getPeerPrincipal","kind":"function","lang":"kotlin","code":"@Throws(SSLPeerUnverifiedException::class)\n override fun getPeerPrincipal(): Principal = delegate!!.peerPrincipal"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":72,"symbol":"getLocalPrincipal","kind":"function","lang":"kotlin","code":"override fun getLocalPrincipal(): Principal = delegate!!.localPrincipal"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":74,"symbol":"getCipherSuite","kind":"function","lang":"kotlin","code":"override fun getCipherSuite(): String = delegate!!.cipherSuite"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":76,"symbol":"getProtocol","kind":"function","lang":"kotlin","code":"override fun getProtocol(): String = delegate!!.protocol"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":78,"symbol":"getPeerHost","kind":"function","lang":"kotlin","code":"override fun getPeerHost(): String = delegate!!.peerHost"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":80,"symbol":"getPeerPort","kind":"function","lang":"kotlin","code":"override fun getPeerPort(): Int = delegate!!.peerPort"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":82,"symbol":"getPacketBufferSize","kind":"function","lang":"kotlin","code":"override fun getPacketBufferSize(): Int = delegate!!.packetBufferSize"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSession.kt","line":84,"symbol":"getApplicationBufferSize","kind":"function","lang":"kotlin","code":"override fun getApplicationBufferSize(): Int = delegate!!.applicationBufferSize"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":32,"symbol":"DelegatingSSLSocket","kind":"class","lang":"kotlin","doc":"An [SSLSocket] that delegates all calls.","code":"abstract class DelegatingSSLSocket(\n protected val delegate: SSLSocket?,\n) : SSLSocket() {\n @Throws(IOException::class)\n override fun shutdownInput() {\n delegate!!.shutdownInput()\n }\n\n @Throws(IOException::class)\n override fun shutdownOutput() {\n delegate!!.shutdownOutput()\n }\n\n override fun getSupportedCipherSuites(): Array = delegate!!.supportedCipherSuites\n\n override fun getEnabledCipherSuites(): Array = delegate!!.enabledCipherSuites\n\n override fun setEnabledCipherSuites(suites: Array) {\n delegate!!.enabledCipherSuites = suites\n }\n\n override fun getSupportedProtocols(): Array = delegate!!.supportedProtocols\n\n override fun getEnabledProtocols(): Array = delegate!!.enabledProtocols\n\n override fun setEnabledProtocols(protocols: Array) {\n delegate!!.enabledProtocols = protocols\n }\n\n override fun getSession(): SSLSession = delegate!!.session\n\n override fun addHandshakeCompletedListener(listener: HandshakeCompletedListener) {\n delegate!!.addHandshakeCompletedListener(listener)\n }\n\n override fun removeHandshakeCompletedListener(listener: HandshakeCompletedListener) {\n delegate!!.removeHandshakeComplet"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":35,"symbol":"shutdownInput","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun shutdownInput() {\n delegate!!.shutdownInput()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":40,"symbol":"shutdownOutput","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun shutdownOutput() {\n delegate!!.shutdownOutput()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":45,"symbol":"getSupportedCipherSuites","kind":"function","lang":"kotlin","code":"override fun getSupportedCipherSuites(): Array = delegate!!.supportedCipherSuites"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":47,"symbol":"getEnabledCipherSuites","kind":"function","lang":"kotlin","code":"override fun getEnabledCipherSuites(): Array = delegate!!.enabledCipherSuites"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":49,"symbol":"setEnabledCipherSuites","kind":"function","lang":"kotlin","code":"override fun setEnabledCipherSuites(suites: Array) {\n delegate!!.enabledCipherSuites = suites\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":53,"symbol":"getSupportedProtocols","kind":"function","lang":"kotlin","code":"override fun getSupportedProtocols(): Array = delegate!!.supportedProtocols"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":55,"symbol":"getEnabledProtocols","kind":"function","lang":"kotlin","code":"override fun getEnabledProtocols(): Array = delegate!!.enabledProtocols"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":57,"symbol":"setEnabledProtocols","kind":"function","lang":"kotlin","code":"override fun setEnabledProtocols(protocols: Array) {\n delegate!!.enabledProtocols = protocols\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":61,"symbol":"getSession","kind":"function","lang":"kotlin","code":"override fun getSession(): SSLSession = delegate!!.session"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":63,"symbol":"addHandshakeCompletedListener","kind":"function","lang":"kotlin","code":"override fun addHandshakeCompletedListener(listener: HandshakeCompletedListener) {\n delegate!!.addHandshakeCompletedListener(listener)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":67,"symbol":"removeHandshakeCompletedListener","kind":"function","lang":"kotlin","code":"override fun removeHandshakeCompletedListener(listener: HandshakeCompletedListener) {\n delegate!!.removeHandshakeCompletedListener(listener)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":71,"symbol":"startHandshake","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun startHandshake() {\n delegate!!.startHandshake()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":76,"symbol":"setUseClientMode","kind":"function","lang":"kotlin","code":"override fun setUseClientMode(mode: Boolean) {\n delegate!!.useClientMode = mode\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":80,"symbol":"getUseClientMode","kind":"function","lang":"kotlin","code":"override fun getUseClientMode(): Boolean = delegate!!.useClientMode"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":82,"symbol":"setNeedClientAuth","kind":"function","lang":"kotlin","code":"override fun setNeedClientAuth(need: Boolean) {\n delegate!!.needClientAuth = need\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":86,"symbol":"setWantClientAuth","kind":"function","lang":"kotlin","code":"override fun setWantClientAuth(want: Boolean) {\n delegate!!.wantClientAuth = want\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":90,"symbol":"getNeedClientAuth","kind":"function","lang":"kotlin","code":"override fun getNeedClientAuth(): Boolean = delegate!!.needClientAuth"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":92,"symbol":"getWantClientAuth","kind":"function","lang":"kotlin","code":"override fun getWantClientAuth(): Boolean = delegate!!.wantClientAuth"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":94,"symbol":"setEnableSessionCreation","kind":"function","lang":"kotlin","code":"override fun setEnableSessionCreation(flag: Boolean) {\n delegate!!.enableSessionCreation = flag\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":98,"symbol":"getEnableSessionCreation","kind":"function","lang":"kotlin","code":"override fun getEnableSessionCreation(): Boolean = delegate!!.enableSessionCreation"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":100,"symbol":"getSSLParameters","kind":"function","lang":"kotlin","code":"override fun getSSLParameters(): SSLParameters = delegate!!.sslParameters"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":102,"symbol":"setSSLParameters","kind":"function","lang":"kotlin","code":"override fun setSSLParameters(p: SSLParameters) {\n delegate!!.sslParameters = p\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":106,"symbol":"close","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun close() {\n delegate!!.close()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":111,"symbol":"getInetAddress","kind":"function","lang":"kotlin","code":"override fun getInetAddress(): InetAddress = delegate!!.inetAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":113,"symbol":"getInputStream","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun getInputStream(): InputStream = delegate!!.inputStream"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":116,"symbol":"getKeepAlive","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getKeepAlive(): Boolean = delegate!!.keepAlive"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":119,"symbol":"getLocalAddress","kind":"function","lang":"kotlin","code":"override fun getLocalAddress(): InetAddress = delegate!!.localAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":121,"symbol":"getLocalPort","kind":"function","lang":"kotlin","code":"override fun getLocalPort(): Int = delegate!!.localPort"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":123,"symbol":"getOutputStream","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun getOutputStream(): OutputStream = delegate!!.outputStream"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":126,"symbol":"getPort","kind":"function","lang":"kotlin","code":"override fun getPort(): Int = delegate!!.port"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":128,"symbol":"getSoLinger","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getSoLinger(): Int = delegate!!.soLinger"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":131,"symbol":"getReceiveBufferSize","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getReceiveBufferSize(): Int = delegate!!.receiveBufferSize"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":134,"symbol":"getSendBufferSize","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getSendBufferSize(): Int = delegate!!.sendBufferSize"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":137,"symbol":"getSoTimeout","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getSoTimeout(): Int = delegate!!.soTimeout"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":140,"symbol":"getTcpNoDelay","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getTcpNoDelay(): Boolean = delegate!!.tcpNoDelay"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":143,"symbol":"setKeepAlive","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setKeepAlive(keepAlive: Boolean) {\n delegate!!.keepAlive = keepAlive\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":148,"symbol":"setSendBufferSize","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setSendBufferSize(size: Int) {\n delegate!!.sendBufferSize = size\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":153,"symbol":"setReceiveBufferSize","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setReceiveBufferSize(size: Int) {\n delegate!!.receiveBufferSize = size\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":158,"symbol":"setSoLinger","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setSoLinger(\n on: Boolean,\n timeout: Int,\n ) {\n delegate!!.setSoLinger(on, timeout)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":166,"symbol":"setSoTimeout","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setSoTimeout(timeout: Int) {\n delegate!!.soTimeout = timeout\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":171,"symbol":"setTcpNoDelay","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setTcpNoDelay(on: Boolean) {\n delegate!!.tcpNoDelay = on\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":176,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = delegate!!.toString()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":178,"symbol":"getLocalSocketAddress","kind":"function","lang":"kotlin","code":"override fun getLocalSocketAddress(): SocketAddress = delegate!!.localSocketAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":180,"symbol":"getRemoteSocketAddress","kind":"function","lang":"kotlin","code":"override fun getRemoteSocketAddress(): SocketAddress = delegate!!.remoteSocketAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":182,"symbol":"isBound","kind":"function","lang":"kotlin","code":"override fun isBound(): Boolean = delegate!!.isBound"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":184,"symbol":"isConnected","kind":"function","lang":"kotlin","code":"override fun isConnected(): Boolean = delegate!!.isConnected"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":186,"symbol":"isClosed","kind":"function","lang":"kotlin","code":"override fun isClosed(): Boolean = delegate!!.isClosed"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":188,"symbol":"bind","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun bind(localAddr: SocketAddress) {\n delegate!!.bind(localAddr)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":193,"symbol":"connect","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun connect(remoteAddr: SocketAddress) {\n delegate!!.connect(remoteAddr)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":198,"symbol":"connect","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun connect(\n remoteAddr: SocketAddress,\n timeout: Int,\n ) {\n delegate!!.connect(remoteAddr, timeout)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":206,"symbol":"isInputShutdown","kind":"function","lang":"kotlin","code":"override fun isInputShutdown(): Boolean = delegate!!.isInputShutdown"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":208,"symbol":"isOutputShutdown","kind":"function","lang":"kotlin","code":"override fun isOutputShutdown(): Boolean = delegate!!.isOutputShutdown"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":210,"symbol":"setReuseAddress","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setReuseAddress(reuse: Boolean) {\n delegate!!.reuseAddress = reuse\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":215,"symbol":"getReuseAddress","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getReuseAddress(): Boolean = delegate!!.reuseAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":218,"symbol":"setOOBInline","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setOOBInline(oobinline: Boolean) {\n delegate!!.oobInline = oobinline\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":223,"symbol":"getOOBInline","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getOOBInline(): Boolean = delegate!!.oobInline"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":226,"symbol":"setTrafficClass","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun setTrafficClass(value: Int) {\n delegate!!.trafficClass = value\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":231,"symbol":"getTrafficClass","kind":"function","lang":"kotlin","code":"@Throws(SocketException::class)\n override fun getTrafficClass(): Int = delegate!!.trafficClass"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocket.kt","line":234,"symbol":"sendUrgentData","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun sendUrgentData(value: Int) {\n delegate!!.sendUrgentData(value)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":28,"symbol":"DelegatingSSLSocketFactory","kind":"class","lang":"kotlin","doc":"A [SSLSocketFactory] that delegates calls. Sockets can be configured after creation by overriding [.configureSocket].","code":"open class DelegatingSSLSocketFactory(\n private val delegate: SSLSocketFactory,\n) : SSLSocketFactory() {\n @Throws(IOException::class)\n override fun createSocket(): SSLSocket {\n val sslSocket = delegate.createSocket() as SSLSocket\n return configureSocket(sslSocket)\n }\n\n @Throws(IOException::class)\n override fun createSocket(\n host: String,\n port: Int,\n ): SSLSocket {\n val sslSocket = delegate.createSocket(host, port) as SSLSocket\n return configureSocket(sslSocket)\n }\n\n @Throws(IOException::class)\n override fun createSocket(\n host: String,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): SSLSocket {\n val sslSocket = delegate.createSocket(host, port, localAddress, localPort) as SSLSocket\n return configureSocket(sslSocket)\n }\n\n @Throws(IOException::class)\n override fun createSocket(\n host: InetAddress,\n port: Int,\n ): SSLSocket {\n val sslSocket = delegate.createSocket(host, port) as SSLSocket\n return configureSocket(sslSocket)\n }\n\n @Throws(IOException::class)\n override fun createSocket(\n host: InetAddress,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): SSLSocket {\n val sslSocket "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":31,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(): SSLSocket {\n val sslSocket = delegate.createSocket() as SSLSocket\n return configureSocket(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":37,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n host: String,\n port: Int,\n ): SSLSocket {\n val sslSocket = delegate.createSocket(host, port) as SSLSocket\n return configureSocket(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":46,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n host: String,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): SSLSocket {\n val sslSocket = delegate.createSocket(host, port, localAddress, localPort) as SSLSocket\n return configureSocket(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":57,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n host: InetAddress,\n port: Int,\n ): SSLSocket {\n val sslSocket = delegate.createSocket(host, port) as SSLSocket\n return configureSocket(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":66,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n host: InetAddress,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): SSLSocket {\n val sslSocket = delegate.createSocket(host, port, localAddress, localPort) as SSLSocket\n return configureSocket(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":77,"symbol":"getDefaultCipherSuites","kind":"function","lang":"kotlin","code":"override fun getDefaultCipherSuites(): Array = delegate.defaultCipherSuites"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":79,"symbol":"getSupportedCipherSuites","kind":"function","lang":"kotlin","code":"override fun getSupportedCipherSuites(): Array = delegate.supportedCipherSuites"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":81,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n socket: Socket,\n host: String,\n port: Int,\n autoClose: Boolean,\n ): SSLSocket {\n val sslSocket = delegate.createSocket(socket, host, port, autoClose) as SSLSocket\n return configureSocket(sslSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSSLSocketFactory.kt","line":92,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n protected open fun configureSocket(sslSocket: SSLSocket): SSLSocket {\n // No-op by default.\n return sslSocket\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingServerSocketFactory.kt","line":27,"symbol":"DelegatingServerSocketFactory","kind":"class","lang":"kotlin","doc":"A [ServerSocketFactory] that delegates calls. Sockets can be configured after creation by overriding [.configureServerSocket].","code":"open class DelegatingServerSocketFactory(\n private val delegate: ServerSocketFactory,\n) : ServerSocketFactory() {\n @Throws(IOException::class)\n override fun createServerSocket(): ServerSocket {\n val serverSocket = delegate.createServerSocket()\n return configureServerSocket(serverSocket)\n }\n\n @Throws(IOException::class)\n override fun createServerSocket(port: Int): ServerSocket {\n val serverSocket = delegate.createServerSocket(port)\n return configureServerSocket(serverSocket)\n }\n\n @Throws(IOException::class)\n override fun createServerSocket(\n port: Int,\n backlog: Int,\n ): ServerSocket {\n val serverSocket = delegate.createServerSocket(port, backlog)\n return configureServerSocket(serverSocket)\n }\n\n @Throws(IOException::class)\n override fun createServerSocket(\n port: Int,\n backlog: Int,\n ifAddress: InetAddress,\n ): ServerSocket {\n val serverSocket = delegate.createServerSocket(port, backlog, ifAddress)\n return configureServerSocket(serverSocket)\n }\n\n @Throws(IOException::class)\n protected open fun configureServerSocket(serverSocket: ServerSocket): ServerSocket {\n // No-op by default.\n return serverSocket\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingServerSocketFactory.kt","line":30,"symbol":"createServerSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createServerSocket(): ServerSocket {\n val serverSocket = delegate.createServerSocket()\n return configureServerSocket(serverSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingServerSocketFactory.kt","line":36,"symbol":"createServerSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createServerSocket(port: Int): ServerSocket {\n val serverSocket = delegate.createServerSocket(port)\n return configureServerSocket(serverSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingServerSocketFactory.kt","line":42,"symbol":"createServerSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createServerSocket(\n port: Int,\n backlog: Int,\n ): ServerSocket {\n val serverSocket = delegate.createServerSocket(port, backlog)\n return configureServerSocket(serverSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingServerSocketFactory.kt","line":51,"symbol":"createServerSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createServerSocket(\n port: Int,\n backlog: Int,\n ifAddress: InetAddress,\n ): ServerSocket {\n val serverSocket = delegate.createServerSocket(port, backlog, ifAddress)\n return configureServerSocket(serverSocket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingServerSocketFactory.kt","line":61,"symbol":"configureServerSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n protected open fun configureServerSocket(serverSocket: ServerSocket): ServerSocket {\n // No-op by default.\n return serverSocket\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSocketFactory.kt","line":27,"symbol":"DelegatingSocketFactory","kind":"class","lang":"kotlin","doc":"A [SocketFactory] that delegates calls. Sockets can be configured after creation by overriding [.configureSocket].","code":"open class DelegatingSocketFactory(\n private val delegate: SocketFactory,\n) : SocketFactory() {\n @Throws(IOException::class)\n override fun createSocket(): Socket {\n val socket = delegate.createSocket()\n return configureSocket(socket)\n }\n\n @Throws(IOException::class)\n override fun createSocket(\n host: String,\n port: Int,\n ): Socket {\n val socket = delegate.createSocket(host, port)\n return configureSocket(socket)\n }\n\n @Throws(IOException::class)\n override fun createSocket(\n host: String,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): Socket {\n val socket = delegate.createSocket(host, port, localAddress, localPort)\n return configureSocket(socket)\n }\n\n @Throws(IOException::class)\n override fun createSocket(\n host: InetAddress,\n port: Int,\n ): Socket {\n val socket = delegate.createSocket(host, port)\n return configureSocket(socket)\n }\n\n @Throws(IOException::class)\n override fun createSocket(\n host: InetAddress,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): Socket {\n val socket = delegate.createSocket(host, port, localAddress, localPort)\n return configureSocket(socket)\n }\n\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSocketFactory.kt","line":30,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(): Socket {\n val socket = delegate.createSocket()\n return configureSocket(socket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSocketFactory.kt","line":36,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n host: String,\n port: Int,\n ): Socket {\n val socket = delegate.createSocket(host, port)\n return configureSocket(socket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSocketFactory.kt","line":45,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n host: String,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): Socket {\n val socket = delegate.createSocket(host, port, localAddress, localPort)\n return configureSocket(socket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSocketFactory.kt","line":56,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n host: InetAddress,\n port: Int,\n ): Socket {\n val socket = delegate.createSocket(host, port)\n return configureSocket(socket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSocketFactory.kt","line":65,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun createSocket(\n host: InetAddress,\n port: Int,\n localAddress: InetAddress,\n localPort: Int,\n ): Socket {\n val socket = delegate.createSocket(host, port, localAddress, localPort)\n return configureSocket(socket)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/DelegatingSocketFactory.kt","line":76,"symbol":"configureSocket","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n protected open fun configureSocket(socket: Socket): Socket {\n // No-op by default.\n return socket\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeConnection.kt","line":30,"symbol":"FakeConnection","kind":"class","lang":"kotlin","doc":"This class implements a rendezvous point for [Handshaker.ClientInputs] and [Handshaker.ServerInputs]. When they're both provided, the client caller does a handshake and shares the handshake result.","code":"internal class FakeConnection(\n val clientAddress: InetSocketAddress,\n val serverAddress: InetSocketAddress,\n val clientSocket: Socket,\n val serverSocket: Socket,\n) : Lockable {\n private var closed = false\n private var serverInputs: Handshaker.ServerInputs? = null\n private var handshakeResult: Result? = null\n\n fun handshake(\n handshaker: Handshaker,\n clientInputs: Handshaker.ClientInputs,\n timeout: Timeout,\n ): Handshaker.Result {\n val serverInputs =\n withLock {\n awaitServerInputs(timeout)\n }\n\n // Destroy the unencrypted socket pair; we'll build a new encrypted one to replace it.\n clientSocket.cancel()\n serverSocket.cancel()\n\n val result =\n runCatching {\n handshaker.handshake(clientInputs, serverInputs)\n }\n\n withLock {\n this.handshakeResult = result\n notifyAll()\n }\n\n return result.getOrThrow()\n }\n\n private tailrec fun awaitServerInputs(timeout: Timeout): Handshaker.ServerInputs {\n if (closed) throw SocketException(\"closed\")\n serverInputs?.let { return it }\n timeout.waitUntilNotified(this)\n return awaitServerInputs(timeout)\n }\n\n fun handshake(\n serverInputs: Ha"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeConnection.kt","line":40,"symbol":"handshake","kind":"function","lang":"kotlin","code":"fun handshake(\n handshaker: Handshaker,\n clientInputs: Handshaker.ClientInputs,\n timeout: Timeout,\n ): Handshaker.Result {\n val serverInputs =\n withLock {\n awaitServerInputs(timeout)\n }\n\n // Destroy the unencrypted socket pair; we'll build a new encrypted one to replace it.\n clientSocket.cancel()\n serverSocket.cancel()\n\n val result =\n runCatching {\n handshaker.handshake(clientInputs, serverInputs)\n }\n\n withLock {\n this.handshakeResult = result\n notifyAll()\n }\n\n return result.getOrThrow()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeConnection.kt","line":67,"symbol":"awaitServerInputs","kind":"function","lang":"kotlin","code":"private tailrec fun awaitServerInputs(timeout: Timeout): Handshaker.ServerInputs {\n if (closed) throw SocketException(\"closed\")\n serverInputs?.let { return it }\n timeout.waitUntilNotified(this)\n return awaitServerInputs(timeout)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeConnection.kt","line":74,"symbol":"handshake","kind":"function","lang":"kotlin","code":"fun handshake(\n serverInputs: Handshaker.ServerInputs,\n timeout: Timeout,\n ): Handshaker.Result {\n withLock {\n this.serverInputs = serverInputs\n notifyAll()\n return awaitResult(timeout).getOrThrow()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeConnection.kt","line":85,"symbol":"awaitResult","kind":"function","lang":"kotlin","code":"private tailrec fun awaitResult(timeout: Timeout): Result {\n if (closed) throw SocketException(\"closed\")\n handshakeResult?.let { return it }\n timeout.waitUntilNotified(this)\n return awaitResult(timeout)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeConnection.kt","line":92,"symbol":"close","kind":"function","lang":"kotlin","code":"fun close() {\n withLock {\n closed = true\n notifyAll()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeConnection.kt","line":99,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"$clientAddress<->$serverAddress\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":41,"symbol":"FakeNetwork","kind":"class","lang":"kotlin","doc":"A complete in-memory socket system, suitable for testing OkHttp without using any operating system TCP sockets.","code":"class FakeNetwork {\n private val boundServers = ConcurrentHashMap()\n\n private val nextIpv4Address =\n Buffer().run {\n writeByte(192)\n writeByte(168)\n writeByte(0)\n writeByte(1)\n AtomicInteger(readInt())\n }\n\n private var nextPort = AtomicInteger(5_000)\n\n internal val anyAddress: InetAddress\n get() = InetAddress.getByAddress(byteArrayOf(0, 0, 0, 0))\n\n /** Generate a new unique address. */\n fun nextSocketAddress(): InetSocketAddress {\n val ipv4AddressInt = nextIpv4Address.getAndIncrement()\n val ipv4AddressBytes =\n Buffer()\n .writeInt(ipv4AddressInt)\n .readByteArray()\n return InetSocketAddress(\n InetAddress.getByAddress(ipv4AddressBytes),\n nextPort(),\n )\n }\n\n /** Generate a new unique port. */\n fun nextPort() = nextPort.getAndIncrement()\n\n val serverSocketFactory =\n object : ServerSocketFactory() {\n override fun createServerSocket() = FakeServerSocket(this@FakeNetwork)\n\n override fun createServerSocket(port: Int) = error(\"unsupported\")\n\n override fun createServerSocket(\n port: Int,\n backlog: Int,\n ) = error(\"unsupported\")\n\n override f"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":59,"symbol":"nextSocketAddress","kind":"function","lang":"kotlin","doc":"Generate a new unique address.","code":"fun nextSocketAddress(): InetSocketAddress {\n val ipv4AddressInt = nextIpv4Address.getAndIncrement()\n val ipv4AddressBytes =\n Buffer()\n .writeInt(ipv4AddressInt)\n .readByteArray()\n return InetSocketAddress(\n InetAddress.getByAddress(ipv4AddressBytes),\n nextPort(),\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":72,"symbol":"nextPort","kind":"function","lang":"kotlin","doc":"Generate a new unique port.","code":"fun nextPort() = nextPort.getAndIncrement()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":76,"symbol":"createServerSocket","kind":"function","lang":"kotlin","code":"override fun createServerSocket() = FakeServerSocket(this@FakeNetwork)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":78,"symbol":"createServerSocket","kind":"function","lang":"kotlin","code":"override fun createServerSocket(port: Int) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":80,"symbol":"createServerSocket","kind":"function","lang":"kotlin","code":"override fun createServerSocket(\n port: Int,\n backlog: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":85,"symbol":"createServerSocket","kind":"function","lang":"kotlin","code":"override fun createServerSocket(\n port: Int,\n backlog: Int,\n ifAddress: InetAddress?,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":94,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket() = FakeSocket(this@FakeNetwork)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":96,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: String,\n port: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":101,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: String?,\n port: Int,\n localHost: InetAddress?,\n localPort: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":108,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: InetAddress?,\n port: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":113,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n address: InetAddress?,\n port: Int,\n localAddress: InetAddress?,\n localPort: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":121,"symbol":"connect","kind":"function","lang":"kotlin","code":"internal fun connect(\n attempt: ConnectAttempt,\n connectTimeoutMillis: Long,\n ): FakeConnection {\n val boundServer =\n boundServers[attempt.serverAddress]\n ?: throw ConnectException(\"no server bound\")\n\n val timeout =\n Timeout()\n .deadline(connectTimeoutMillis, TimeUnit.MILLISECONDS)\n boundServer.enqueue(timeout, attempt)\n return attempt.await(timeout)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":137,"symbol":"bind","kind":"function","lang":"kotlin","doc":"Returns non-null if the bind was successful.","code":"internal fun bind(\n endpoint: InetSocketAddress,\n backlog: Int,\n ): BoundServer? {\n val serverAddress =\n when (endpoint.port) {\n 0 -> InetSocketAddress(endpoint.address, nextPort())\n else -> endpoint\n }\n\n val result = BoundServer(serverAddress, backlog)\n val collision = boundServers.putIfAbsent(serverAddress, result)\n if (collision != null) return null\n return result\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":153,"symbol":"cancel","kind":"function","lang":"kotlin","code":"internal fun cancel(server: BoundServer) {\n boundServers.remove(server.serverAddress, server)\n server.close()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":168,"symbol":"ConnectAttempt","kind":"class","lang":"kotlin","doc":"Either the client or the server can asynchronously cancel this attempt while the caller is awaiting its result. This uses `synchronized` to guard [result]. Calls to [await] wait on this lock until a result is sent.","code":"internal class ConnectAttempt(\n val clientAddress: InetSocketAddress,\n val serverAddress: InetSocketAddress,\n) : Lockable {\n private var result: Result? = null\n\n fun cancel(e: SocketException) {\n withLock {\n if (result != null) return\n result = Result.failure(e)\n notifyAll()\n }\n }\n\n fun complete(connection: FakeConnection) {\n withLock {\n if (result != null) return\n result = Result.success(connection)\n notifyAll()\n }\n }\n\n fun await(timeout: Timeout): FakeConnection {\n withLock {\n while (true) {\n val result = result\n if (result != null) return result.getOrThrow()\n\n timeout.waitUntilNotified(this)\n }\n }\n }\n\n override fun toString() = \"Connect@$serverAddress\"\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":174,"symbol":"cancel","kind":"function","lang":"kotlin","code":"fun cancel(e: SocketException) {\n withLock {\n if (result != null) return\n result = Result.failure(e)\n notifyAll()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":182,"symbol":"complete","kind":"function","lang":"kotlin","code":"fun complete(connection: FakeConnection) {\n withLock {\n if (result != null) return\n result = Result.success(connection)\n notifyAll()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":190,"symbol":"await","kind":"function","lang":"kotlin","code":"fun await(timeout: Timeout): FakeConnection {\n withLock {\n while (true) {\n val result = result\n if (result != null) return result.getOrThrow()\n\n timeout.waitUntilNotified(this)\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":201,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"Connect@$serverAddress\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":210,"symbol":"BoundServer","kind":"class","lang":"kotlin","doc":"Matches inbound connection attempts with calls to [accept]. This uses `synchronized` to guard [attempts] and [closed]. Calls to [accept] wait on this lock until a connection attempt is enqueued.","code":"internal class BoundServer(\n val serverAddress: InetSocketAddress,\n val maxBacklogSize: Int,\n) : Lockable {\n private val attempts = ArrayDeque()\n private var closed = false\n\n fun enqueue(\n timeout: Timeout,\n attempt: ConnectAttempt,\n ) {\n withLock {\n while (attempts.size >= maxBacklogSize && !closed) {\n timeout.waitUntilNotified(this) // Wait until there's room in the backlog.\n }\n if (closed) throw ConnectException(\"closed\")\n notifyAll()\n attempts += attempt\n }\n }\n\n fun accept(): FakeConnection {\n val attempt =\n withLock {\n while (attempts.isEmpty() && !closed) {\n wait() // Wait for a connection attempt.\n }\n if (closed) throw SocketException(\"closed\")\n notifyAll()\n attempts.removeFirst()\n }\n\n val (clientSocket, serverSocket) = inMemorySocketPair(maxBufferSize = 1024 * 1024)\n val connection =\n FakeConnection(\n clientAddress = attempt.clientAddress,\n serverAddress = attempt.serverAddress,\n clientSocket = clientSocket.asBufferedSocket(),\n serverSocket = serverSocket.asBufferedSocket(),\n )\n\n attempt.complete(connecti"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":217,"symbol":"enqueue","kind":"function","lang":"kotlin","code":"fun enqueue(\n timeout: Timeout,\n attempt: ConnectAttempt,\n ) {\n withLock {\n while (attempts.size >= maxBacklogSize && !closed) {\n timeout.waitUntilNotified(this) // Wait until there's room in the backlog.\n }\n if (closed) throw ConnectException(\"closed\")\n notifyAll()\n attempts += attempt\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":231,"symbol":"accept","kind":"function","lang":"kotlin","code":"fun accept(): FakeConnection {\n val attempt =\n withLock {\n while (attempts.isEmpty() && !closed) {\n wait() // Wait for a connection attempt.\n }\n if (closed) throw SocketException(\"closed\")\n notifyAll()\n attempts.removeFirst()\n }\n\n val (clientSocket, serverSocket) = inMemorySocketPair(maxBufferSize = 1024 * 1024)\n val connection =\n FakeConnection(\n clientAddress = attempt.clientAddress,\n serverAddress = attempt.serverAddress,\n clientSocket = clientSocket.asBufferedSocket(),\n serverSocket = serverSocket.asBufferedSocket(),\n )\n\n attempt.complete(connection)\n return connection\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":255,"symbol":"close","kind":"function","lang":"kotlin","code":"fun close() {\n val attemptsToCancel =\n withLock {\n notifyAll()\n closed = true\n attempts\n .toList()\n .also { attempts.clear() }\n }\n for (attempt in attemptsToCancel) {\n attempt.cancel(SocketException(\"server closed\"))\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetwork.kt","line":269,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"Server@$serverAddress\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":42,"symbol":"FakeNetworkPlatform","kind":"class","lang":"kotlin","code":"class FakeNetworkPlatform : Platform() {\n val network = FakeNetwork()\n\n var handshaker: Handshaker = InsecureHandshaker()\n\n override val socketFactory: SocketFactory\n get() = network.socketFactory\n\n override val serverSocketFactory: ServerSocketFactory\n get() = network.serverSocketFactory\n\n override fun newSSLContext(): SSLContext {\n @Suppress(\"DEPRECATION\") // Non-deprecated overload requires Java 9+.\n val provider =\n object : Provider(\"FakeNetwork\", 0.0, \"\") {\n }\n return object : SSLContext(FakeSslContextSpi(), provider, \"TLSv1.2\") {\n }\n }\n\n override fun trustManager(sslSocketFactory: SSLSocketFactory) = null\n\n override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n check(sslSocket is FakeSslSocket)\n sslSocket.sslParameters.applicationProtocols = protocols.map { it.toString() }.toTypedArray()\n sslSocket.echConfigList = echConfigList\n }\n\n override fun afterHandshake(sslSocket: SSLSocket) {\n }\n\n override fun getSelectedProtocol(sslSocket: SSLSocket): String? = sslSocket.applicationProtocol\n\n override fun getHands"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":53,"symbol":"newSSLContext","kind":"function","lang":"kotlin","code":"override fun newSSLContext(): SSLContext {\n @Suppress(\"DEPRECATION\") // Non-deprecated overload requires Java 9+.\n val provider =\n object : Provider(\"FakeNetwork\", 0.0, \"\") {\n }\n return object : SSLContext(FakeSslContextSpi(), provider, \"TLSv1.2\") {\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":62,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"override fun trustManager(sslSocketFactory: SSLSocketFactory) = null"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":64,"symbol":"configureTlsExtensions","kind":"function","lang":"kotlin","code":"override fun configureTlsExtensions(\n sslSocket: SSLSocket,\n hostname: String?,\n protocols: List<@JvmSuppressWildcards Protocol>,\n echConfigList: ByteString?,\n ) {\n check(sslSocket is FakeSslSocket)\n sslSocket.sslParameters.applicationProtocols = protocols.map { it.toString() }.toTypedArray()\n sslSocket.echConfigList = echConfigList\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":75,"symbol":"afterHandshake","kind":"function","lang":"kotlin","code":"override fun afterHandshake(sslSocket: SSLSocket) {\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":78,"symbol":"getSelectedProtocol","kind":"function","lang":"kotlin","code":"override fun getSelectedProtocol(sslSocket: SSLSocket): String? = sslSocket.applicationProtocol"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":80,"symbol":"getHandshakeServerNames","kind":"function","lang":"kotlin","code":"override fun getHandshakeServerNames(sslSocket: SSLSocket): List {\n val serverNames = sslSocket.sslParameters.serverNames ?: return listOf()\n return serverNames.map { it.encoded.decodeToString() }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":85,"symbol":"newSslSocketFactory","kind":"function","lang":"kotlin","code":"override fun newSslSocketFactory(trustManager: X509TrustManager): SSLSocketFactory {\n val sslContext = newSSLContext()\n sslContext.init(\n arrayOf(newKeyManager(null, null)),\n arrayOf(trustManager),\n SecureRandom(),\n )\n return sslContext.socketFactory\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":95,"symbol":"echRetryPlan","kind":"function","lang":"kotlin","code":"override fun echRetryPlan(exception: SSLException): EchRetryPlan? =\n when (exception) {\n is EchRejectedException -> {\n EchRetryPlan.getOrNull(\n publicName = exception.publicName,\n configList = exception.nextEchConfigList,\n )\n }\n\n else -> {\n null\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":109,"symbol":"FakeSslContextSpi","kind":"class","lang":"kotlin","code":"private inner class FakeSslContextSpi : SSLContextSpi() {\n private var fakeTls: FakeTls? = null\n\n override fun engineInit(\n keyManagers: Array,\n trustManagers: Array,\n secureRandom: SecureRandom,\n ) {\n check(this.fakeTls == null) { \"already initialized\" }\n\n // FakeNetworkPlatform.handshaker may change after engineInit(), and we want the latest value.\n val forwardingHandshaker =\n object : Handshaker {\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ) = this@FakeNetworkPlatform.handshaker.handshake(client, server)\n }\n\n fakeTls =\n FakeTls(\n handshaker = forwardingHandshaker,\n keyManager = keyManagers.filterIsInstance().single(),\n trustManager = trustManagers.filterIsInstance().single(),\n )\n }\n\n override fun engineGetSocketFactory(): SSLSocketFactory {\n val fakeTls = this.fakeTls ?: error(\"call init() first\")\n return fakeTls.sslSocketFactory\n }\n\n override fun engineGetServerSocketFactory() = error(\"unsupported\")\n\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":112,"symbol":"engineInit","kind":"function","lang":"kotlin","code":"override fun engineInit(\n keyManagers: Array,\n trustManagers: Array,\n secureRandom: SecureRandom,\n ) {\n check(this.fakeTls == null) { \"already initialized\" }\n\n // FakeNetworkPlatform.handshaker may change after engineInit(), and we want the latest value.\n val forwardingHandshaker =\n object : Handshaker {\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ) = this@FakeNetworkPlatform.handshaker.handshake(client, server)\n }\n\n fakeTls =\n FakeTls(\n handshaker = forwardingHandshaker,\n keyManager = keyManagers.filterIsInstance().single(),\n trustManager = trustManagers.filterIsInstance().single(),\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":122,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ) = this@FakeNetworkPlatform.handshaker.handshake(client, server)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":136,"symbol":"engineGetSocketFactory","kind":"function","lang":"kotlin","code":"override fun engineGetSocketFactory(): SSLSocketFactory {\n val fakeTls = this.fakeTls ?: error(\"call init() first\")\n return fakeTls.sslSocketFactory\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":141,"symbol":"engineGetServerSocketFactory","kind":"function","lang":"kotlin","code":"override fun engineGetServerSocketFactory() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":143,"symbol":"engineCreateSSLEngine","kind":"function","lang":"kotlin","code":"override fun engineCreateSSLEngine() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":145,"symbol":"engineCreateSSLEngine","kind":"function","lang":"kotlin","code":"override fun engineCreateSSLEngine(\n host: String,\n port: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":150,"symbol":"engineGetServerSessionContext","kind":"function","lang":"kotlin","code":"override fun engineGetServerSessionContext() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkPlatform.kt","line":152,"symbol":"engineGetClientSessionContext","kind":"function","lang":"kotlin","code":"override fun engineGetClientSessionContext() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkTesting.kt","line":21,"symbol":"socketPair","kind":"function","lang":"kotlin","doc":"Returns a two-element array containing mutually-connected sockets.","code":"internal fun FakeNetwork.socketPair(): Array {\n val (clientOkioSocket, serverOkioSocket) = inMemorySocketPair(maxBufferSize = 1024 * 1024)\n val connection =\n FakeConnection(\n clientAddress = nextSocketAddress(),\n serverAddress = nextSocketAddress(),\n clientSocket = clientOkioSocket,\n serverSocket = serverOkioSocket,\n )\n\n val clientJavaNetSocket =\n FakeSocket(\n network = this,\n initialState =\n FakeSocket.State.Connected(\n connection = connection,\n localAddress = connection.clientAddress,\n remoteAddress = connection.serverAddress,\n socket = connection.clientSocket,\n ),\n )\n\n val serverJavaNetSocket =\n FakeSocket(\n network = this,\n initialState =\n FakeSocket.State.Connected(\n connection = connection,\n localAddress = connection.serverAddress,\n remoteAddress = connection.clientAddress,\n socket = connection.serverSocket,\n ),\n )\n\n return arrayOf(clientJavaNetSocket, serverJavaNetSocket)\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkTesting.kt","line":58,"symbol":"clientSocket","kind":"function","lang":"kotlin","code":"internal fun FakeTls.clientSocket(\n socket: FakeSocket,\n serverHostname: String = \"testing.lysine.dev\",\n serverPort: Int = 443,\n): FakeSslSocket = sslSocketFactory.createSocket(socket, serverHostname, serverPort, true) as FakeSslSocket"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeNetworkTesting.kt","line":64,"symbol":"serverSocket","kind":"function","lang":"kotlin","code":"internal fun FakeTls.serverSocket(\n socket: FakeSocket,\n clientPort: Int = 1024,\n): FakeSslSocket {\n val result = sslSocketFactory.createSocket(socket, null, clientPort, true) as FakeSslSocket\n result.useClientMode = false\n return result\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":28,"symbol":"FakeServerSocket","kind":"class","lang":"kotlin","code":"internal class FakeServerSocket(\n val network: FakeNetwork,\n) : ServerSocket() {\n private val atomicState = AtomicReference(State.New)\n private val state: State\n get() = atomicState.get()\n\n private var reuseAddress = false\n\n override fun bind(\n endpoint: SocketAddress,\n backlog: Int,\n ) {\n check(endpoint is InetSocketAddress)\n\n while (true) {\n val previous = state\n if (previous !is State.New) throw SocketException(\"cannot bind\")\n\n if (!atomicState.compareAndSet(previous, State.Binding)) continue // Lost a race, retry.\n\n val boundServer = network.bind(endpoint, backlog)\n\n if (boundServer == null) {\n check(atomicState.compareAndSet(State.Binding, previous))\n throw SocketException(\"bind collision\")\n }\n\n val next =\n State.Bound(\n boundServer = boundServer,\n )\n check(atomicState.compareAndSet(State.Binding, next))\n break\n }\n }\n\n override fun getInetAddress() = (state.endpoint as? InetSocketAddress)?.address\n\n override fun getLocalPort() = (state.endpoint as? InetSocketAddress)?.port ?: -1\n\n override fun getLocalSocketAddress() = state.endpoint\n\n override fun accept(): So"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":37,"symbol":"bind","kind":"function","lang":"kotlin","code":"override fun bind(\n endpoint: SocketAddress,\n backlog: Int,\n ) {\n check(endpoint is InetSocketAddress)\n\n while (true) {\n val previous = state\n if (previous !is State.New) throw SocketException(\"cannot bind\")\n\n if (!atomicState.compareAndSet(previous, State.Binding)) continue // Lost a race, retry.\n\n val boundServer = network.bind(endpoint, backlog)\n\n if (boundServer == null) {\n check(atomicState.compareAndSet(State.Binding, previous))\n throw SocketException(\"bind collision\")\n }\n\n val next =\n State.Bound(\n boundServer = boundServer,\n )\n check(atomicState.compareAndSet(State.Binding, next))\n break\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":65,"symbol":"getInetAddress","kind":"function","lang":"kotlin","code":"override fun getInetAddress() = (state.endpoint as? InetSocketAddress)?.address"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":67,"symbol":"getLocalPort","kind":"function","lang":"kotlin","code":"override fun getLocalPort() = (state.endpoint as? InetSocketAddress)?.port ?: -1"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":69,"symbol":"getLocalSocketAddress","kind":"function","lang":"kotlin","code":"override fun getLocalSocketAddress() = state.endpoint"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":71,"symbol":"accept","kind":"function","lang":"kotlin","code":"override fun accept(): Socket {\n val boundAddress =\n (state as? State.Bound)?.boundServer\n ?: throw SocketException(\"not bound\")\n\n val connection = boundAddress.accept()\n val socket =\n FakeSocket(\n network = network,\n initialState =\n FakeSocket.State.Connected(\n connection = connection,\n localAddress = connection.serverAddress,\n remoteAddress = connection.clientAddress,\n socket = connection.serverSocket,\n ),\n )\n\n return socket\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":92,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n while (true) {\n val previous = state\n val next = State.Closed(previous)\n if (!atomicState.compareAndSet(previous, next)) continue // Lost a race, retry.\n\n if (previous is State.Bound) {\n network.cancel(previous.boundServer)\n }\n break\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":105,"symbol":"isBound","kind":"function","lang":"kotlin","code":"override fun isBound() = state.bound"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":107,"symbol":"isClosed","kind":"function","lang":"kotlin","code":"override fun isClosed() = state is State.Closed"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":109,"symbol":"setReuseAddress","kind":"function","lang":"kotlin","code":"override fun setReuseAddress(reuseAddress: Boolean) {\n if (state is State.Closed) throw SocketException(\"closed\")\n this.reuseAddress = reuseAddress\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":114,"symbol":"getReuseAddress","kind":"function","lang":"kotlin","code":"override fun getReuseAddress() = reuseAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":116,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"FakeServerSocket\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":118,"symbol":"bind","kind":"function","lang":"kotlin","code":"override fun bind(endpoint: SocketAddress) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":120,"symbol":"getChannel","kind":"function","lang":"kotlin","code":"override fun getChannel() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":122,"symbol":"setSoTimeout","kind":"function","lang":"kotlin","code":"override fun setSoTimeout(timeout: Int) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":124,"symbol":"getSoTimeout","kind":"function","lang":"kotlin","code":"override fun getSoTimeout() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":126,"symbol":"setReceiveBufferSize","kind":"function","lang":"kotlin","code":"override fun setReceiveBufferSize(size: Int) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":128,"symbol":"getReceiveBufferSize","kind":"function","lang":"kotlin","code":"override fun getReceiveBufferSize() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":130,"symbol":"setPerformancePreferences","kind":"function","lang":"kotlin","code":"override fun setPerformancePreferences(\n connectionTime: Int,\n latency: Int,\n bandwidth: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":136,"symbol":"setOption","kind":"function","lang":"kotlin","code":"override fun setOption(\n name: SocketOption,\n value: T?,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":141,"symbol":"getOption","kind":"function","lang":"kotlin","code":"override fun getOption(name: SocketOption) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":143,"symbol":"supportedOptions","kind":"function","lang":"kotlin","code":"override fun supportedOptions() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":145,"symbol":"State","kind":"interface","lang":"kotlin","code":"private sealed interface State {\n val bound: Boolean\n get() = false\n val endpoint: SocketAddress?\n get() = null\n\n object New : State\n\n /** Like [New], but while we're attempting to bind an address. */\n object Binding : State\n\n class Bound(\n val boundServer: BoundServer,\n ) : State {\n override val endpoint: SocketAddress\n get() = boundServer.serverAddress\n override val bound: Boolean\n get() = true\n }\n\n class Closed(\n override val endpoint: SocketAddress?,\n override val bound: Boolean,\n ) : State {\n constructor(previous: State) : this(\n endpoint = previous.endpoint,\n bound = previous.bound,\n )\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":151,"symbol":"New","kind":"object","lang":"kotlin","code":"object New : State"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":154,"symbol":"Binding","kind":"object","lang":"kotlin","doc":"Like [New], but while we're attempting to bind an address.","code":"object Binding : State"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":156,"symbol":"Bound","kind":"class","lang":"kotlin","code":"class Bound(\n val boundServer: BoundServer,\n ) : State {\n override val endpoint: SocketAddress\n get() = boundServer.serverAddress\n override val bound: Boolean\n get() = true\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeServerSocket.kt","line":165,"symbol":"Closed","kind":"class","lang":"kotlin","code":"class Closed(\n override val endpoint: SocketAddress?,\n override val bound: Boolean,\n ) : State {\n constructor(previous: State) : this(\n endpoint = previous.endpoint,\n bound = previous.bound,\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":42,"symbol":"FakeSocket","kind":"class","lang":"kotlin","doc":"A client or server socket. Server sockets are typically created already connected.","code":"internal class FakeSocket(\n val network: FakeNetwork,\n initialState: State = State.New,\n) : Socket() {\n internal val atomicState = AtomicReference(initialState)\n internal val state: State\n get() = atomicState.get()\n\n private var socketReadTimeoutMillis: Long = 0\n\n val connection: FakeConnection?\n get() = (state as? State.Connected)?.connection\n\n override fun getInputStream() =\n (state as? State.Connected)?.inputStream\n ?: throw IOException(\"not connected\")\n\n override fun getOutputStream() =\n (state as? State.Connected)?.outputStream\n ?: throw IOException(\"not connected\")\n\n override fun getRemoteSocketAddress() = state.remoteAddress\n\n override fun getInetAddress() = state.remoteAddress?.address\n\n override fun getPort() = state.remoteAddress?.port ?: 0\n\n override fun getLocalSocketAddress() = state.localAddress\n\n override fun getLocalAddress() = state.localAddress?.address ?: network.anyAddress\n\n override fun getLocalPort() = state.localAddress?.port ?: -1\n\n override fun isBound() = state.bound\n\n override fun isConnected() = state.connected\n\n override fun isClosed() = state is State.Closed\n\n override fun setSoTimeout(soTimeout: Int) {\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":55,"symbol":"getInputStream","kind":"function","lang":"kotlin","code":"override fun getInputStream() =\n (state as? State.Connected)?.inputStream\n ?: throw IOException(\"not connected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":59,"symbol":"getOutputStream","kind":"function","lang":"kotlin","code":"override fun getOutputStream() =\n (state as? State.Connected)?.outputStream\n ?: throw IOException(\"not connected\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":63,"symbol":"getRemoteSocketAddress","kind":"function","lang":"kotlin","code":"override fun getRemoteSocketAddress() = state.remoteAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":65,"symbol":"getInetAddress","kind":"function","lang":"kotlin","code":"override fun getInetAddress() = state.remoteAddress?.address"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":67,"symbol":"getPort","kind":"function","lang":"kotlin","code":"override fun getPort() = state.remoteAddress?.port ?: 0"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":69,"symbol":"getLocalSocketAddress","kind":"function","lang":"kotlin","code":"override fun getLocalSocketAddress() = state.localAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":71,"symbol":"getLocalAddress","kind":"function","lang":"kotlin","code":"override fun getLocalAddress() = state.localAddress?.address ?: network.anyAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":73,"symbol":"getLocalPort","kind":"function","lang":"kotlin","code":"override fun getLocalPort() = state.localAddress?.port ?: -1"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":75,"symbol":"isBound","kind":"function","lang":"kotlin","code":"override fun isBound() = state.bound"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":77,"symbol":"isConnected","kind":"function","lang":"kotlin","code":"override fun isConnected() = state.connected"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":79,"symbol":"isClosed","kind":"function","lang":"kotlin","code":"override fun isClosed() = state is State.Closed"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":81,"symbol":"setSoTimeout","kind":"function","lang":"kotlin","code":"override fun setSoTimeout(soTimeout: Int) {\n if (state is State.Closed) throw SocketException(\"closed\")\n check(soTimeout >= 0)\n this.socketReadTimeoutMillis = soTimeout.toLong()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":87,"symbol":"getSoTimeout","kind":"function","lang":"kotlin","code":"override fun getSoTimeout() = socketReadTimeoutMillis.toInt()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":89,"symbol":"connect","kind":"function","lang":"kotlin","code":"override fun connect(\n endpoint: SocketAddress,\n timeout: Int,\n ) {\n require(timeout >= 0)\n require(endpoint is InetSocketAddress)\n\n val attempt =\n ConnectAttempt(\n clientAddress = network.nextSocketAddress(),\n serverAddress = endpoint,\n )\n\n while (true) {\n val previous = state\n\n if (previous !is State.New) throw SocketException(\"cannot connect\")\n\n val connectingState = State.Connecting(attempt)\n if (!atomicState.compareAndSet(previous, connectingState)) continue // Lost a race, retry.\n\n val connection =\n try {\n network.connect(\n attempt = attempt,\n connectTimeoutMillis = timeout.toLong(),\n )\n } catch (e: Throwable) {\n // If the state changed while we were connecting, the other state wins.\n atomicState.compareAndSet(connectingState, previous)\n throw e\n }\n\n val next =\n State.Connected(\n connection = connection,\n localAddress = attempt.clientAddress,\n remoteAddress = attempt.serverAddress,\n socket = connection.clientSocket,\n )\n\n // If the state changed while we were conne"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":139,"symbol":"isInputShutdown","kind":"function","lang":"kotlin","code":"override fun isInputShutdown() = state.inputShutdown"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":141,"symbol":"shutdownInput","kind":"function","lang":"kotlin","code":"override fun shutdownInput() {\n while (true) {\n val previous = state\n if (previous !is State.Connected) throw SocketException(\"cannot shutdown input\")\n\n if (previous.outputShutdown) {\n val next = State.Closed(previous)\n if (!atomicState.compareAndSet(previous, next)) continue // Lost a race, retry.\n }\n\n previous.inputStream.close()\n if (previous.outputShutdown) previous.connection.close()\n break\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":157,"symbol":"isOutputShutdown","kind":"function","lang":"kotlin","code":"override fun isOutputShutdown() = state.outputShutdown"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":159,"symbol":"shutdownOutput","kind":"function","lang":"kotlin","code":"override fun shutdownOutput() {\n while (true) {\n val previous = state\n if (previous !is State.Connected) throw SocketException(\"cannot shutdown output\")\n\n if (previous.inputShutdown) {\n val next = State.Closed(previous)\n if (!atomicState.compareAndSet(previous, next)) continue // Lost a race, retry.\n }\n\n previous.outputStream.close()\n if (previous.inputShutdown) previous.connection.close()\n break\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":175,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n while (true) {\n val previous = state\n val next = State.Closed(previous)\n\n if (!atomicState.compareAndSet(previous, next)) continue // Lost a race, retry.\n\n when (previous) {\n State.New -> {\n }\n\n is State.Connecting -> {\n previous.attempt.cancel(SocketException(\"client closed\"))\n }\n\n is State.Connected -> {\n previous.source.cancel()\n previous.sink.cancel()\n previous.connection.close()\n }\n\n is State.Closed -> {\n }\n }\n break\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":203,"symbol":"connect","kind":"function","lang":"kotlin","code":"override fun connect(endpoint: SocketAddress) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":205,"symbol":"bind","kind":"function","lang":"kotlin","code":"override fun bind(bindpoint: SocketAddress) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":207,"symbol":"getChannel","kind":"function","lang":"kotlin","code":"override fun getChannel() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":209,"symbol":"setTcpNoDelay","kind":"function","lang":"kotlin","code":"override fun setTcpNoDelay(on: Boolean) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":211,"symbol":"getTcpNoDelay","kind":"function","lang":"kotlin","code":"override fun getTcpNoDelay() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":213,"symbol":"setSoLinger","kind":"function","lang":"kotlin","code":"override fun setSoLinger(\n on: Boolean,\n linger: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":218,"symbol":"getSoLinger","kind":"function","lang":"kotlin","code":"override fun getSoLinger() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":220,"symbol":"sendUrgentData","kind":"function","lang":"kotlin","code":"override fun sendUrgentData(data: Int) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":222,"symbol":"setOOBInline","kind":"function","lang":"kotlin","code":"override fun setOOBInline(on: Boolean) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":224,"symbol":"getOOBInline","kind":"function","lang":"kotlin","code":"override fun getOOBInline() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":226,"symbol":"setSendBufferSize","kind":"function","lang":"kotlin","code":"override fun setSendBufferSize(size: Int) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":228,"symbol":"getSendBufferSize","kind":"function","lang":"kotlin","code":"override fun getSendBufferSize() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":230,"symbol":"setReceiveBufferSize","kind":"function","lang":"kotlin","code":"override fun setReceiveBufferSize(size: Int) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":232,"symbol":"getReceiveBufferSize","kind":"function","lang":"kotlin","code":"override fun getReceiveBufferSize() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":234,"symbol":"setReuseAddress","kind":"function","lang":"kotlin","code":"override fun setReuseAddress(reuseAddress: Boolean) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":236,"symbol":"getReuseAddress","kind":"function","lang":"kotlin","code":"override fun getReuseAddress() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":238,"symbol":"setKeepAlive","kind":"function","lang":"kotlin","code":"override fun setKeepAlive(on: Boolean) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":240,"symbol":"getKeepAlive","kind":"function","lang":"kotlin","code":"override fun getKeepAlive() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":242,"symbol":"setTrafficClass","kind":"function","lang":"kotlin","code":"override fun setTrafficClass(tc: Int) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":244,"symbol":"getTrafficClass","kind":"function","lang":"kotlin","code":"override fun getTrafficClass() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":246,"symbol":"setPerformancePreferences","kind":"function","lang":"kotlin","code":"override fun setPerformancePreferences(\n connectionTime: Int,\n latency: Int,\n bandwidth: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":252,"symbol":"setOption","kind":"function","lang":"kotlin","code":"override fun setOption(\n name: SocketOption,\n value: T?,\n ): Socket = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":257,"symbol":"getOption","kind":"function","lang":"kotlin","code":"override fun getOption(name: SocketOption) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":259,"symbol":"supportedOptions","kind":"function","lang":"kotlin","code":"override fun supportedOptions() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":261,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString() = \"FakeSocket\""} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":268,"symbol":"State","kind":"interface","lang":"kotlin","doc":"This represents the lifecycle state of the TCP socket, which includes a nested lifecycle for the TLS handshake. Tracking the TLS lifecycle here is a layering violation, but it lets us easily keep a single atomic state for both layers.","code":"sealed interface State {\n val localAddress: InetSocketAddress?\n get() = null\n val remoteAddress: InetSocketAddress?\n get() = null\n val bound: Boolean\n get() = false\n val connected: Boolean\n get() = false\n val inputShutdown: Boolean\n get() = false\n val outputShutdown: Boolean\n get() = false\n val handshakeState: HandshakeState\n get() = HandshakeState.New\n\n object New : State\n\n class Connecting(\n val attempt: ConnectAttempt,\n ) : State\n\n class Connected(\n val connection: FakeConnection,\n override val localAddress: InetSocketAddress,\n override val remoteAddress: InetSocketAddress,\n override val handshakeState: HandshakeState = HandshakeState.New,\n val socket: OkioSocket,\n val source: SocketSource = SocketSource(socket),\n val sink: SocketSink = SocketSink(socket),\n val inputStream: InputStream = source.buffer().inputStream(),\n val outputStream: OutputStream = sink.buffer().outputStream(),\n ) : State {\n override val bound: Boolean\n get() = true\n override val connected: Boolean\n get() = true\n override val inputShutdown: Boolean\n get()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":284,"symbol":"New","kind":"object","lang":"kotlin","code":"object New : State"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":290,"symbol":"Connected","kind":"class","lang":"kotlin","code":"class Connected(\n val connection: FakeConnection,\n override val localAddress: InetSocketAddress,\n override val remoteAddress: InetSocketAddress,\n override val handshakeState: HandshakeState = HandshakeState.New,\n val socket: OkioSocket,\n val source: SocketSource = SocketSource(socket),\n val sink: SocketSink = SocketSink(socket),\n val inputStream: InputStream = source.buffer().inputStream(),\n val outputStream: OutputStream = sink.buffer().outputStream(),\n ) : State {\n override val bound: Boolean\n get() = true\n override val connected: Boolean\n get() = true\n override val inputShutdown: Boolean\n get() = source.closed\n override val outputShutdown: Boolean\n get() = sink.closed\n\n /** Note that this yields a new [inputStream] and [outputStream]. */\n fun withHandshakeSuccess(\n handshakeState: HandshakeState.Success,\n socket: OkioSocket,\n ) = Connected(\n connection = connection,\n localAddress = localAddress,\n remoteAddress = remoteAddress,\n handshakeState = handshakeState,\n socket = socket,\n )\n\n /** Note that this retains th"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":311,"symbol":"withHandshakeSuccess","kind":"function","lang":"kotlin","doc":"Note that this yields a new [inputStream] and [outputStream].","code":"fun withHandshakeSuccess(\n handshakeState: HandshakeState.Success,\n socket: OkioSocket,\n ) = Connected(\n connection = connection,\n localAddress = localAddress,\n remoteAddress = remoteAddress,\n handshakeState = handshakeState,\n socket = socket,\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":323,"symbol":"withHandshakeState","kind":"function","lang":"kotlin","doc":"Note that this retains the previous [inputStream] and [outputStream].","code":"fun withHandshakeState(handshakeState: HandshakeState) =\n Connected(\n connection = connection,\n localAddress = localAddress,\n remoteAddress = remoteAddress,\n handshakeState = handshakeState,\n socket = socket,\n source = source,\n sink = sink,\n inputStream = inputStream,\n outputStream = outputStream,\n )"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":338,"symbol":"Closed","kind":"class","lang":"kotlin","doc":"A closed socket remembers what happened before it was closed.","code":"class Closed(\n override val localAddress: InetSocketAddress?,\n override val remoteAddress: InetSocketAddress?,\n override val handshakeState: HandshakeState,\n override val bound: Boolean,\n override val connected: Boolean,\n ) : State {\n constructor(previous: State) : this(\n localAddress = previous.localAddress,\n remoteAddress = previous.remoteAddress,\n handshakeState = previous.handshakeState,\n bound = previous.bound,\n connected = previous.connected,\n )\n\n override val inputShutdown: Boolean\n get() = true\n override val outputShutdown: Boolean\n get() = true\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":374,"symbol":"SocketStream","kind":"class","lang":"kotlin","doc":"To contrast, closing a [java.net.Socket] immediately fails local operations only. The peer can read the remainder of the stream until it is exhausted. Our mitigation is straightforward enough: if the [FakeSocket] is closed while a local operation is in-flight, we trigger a maximally invasive cancel. Otherwise, we do a graceful close.","code":"internal open class SocketStream(\n val socket: OkioSocket,\n val stream: T,\n) : Closeable {\n val closed: Boolean\n get() = state.get() == StreamState.Closed\n\n private val state = AtomicReference(StreamState.Ready)\n\n override fun close() {\n val previous = state.getAndSet(StreamState.Closed)\n if (previous != StreamState.Closed) {\n stream.close()\n }\n }\n\n /**\n * Equivalent to [close] unless there's a local operation in-flight, in which case the entire\n * socket is interrupted.\n */\n fun cancel() {\n val previous = state.getAndSet(StreamState.Closed)\n if (previous != StreamState.Closed) {\n stream.close()\n }\n if (previous == StreamState.Blocked) {\n socket.cancel()\n }\n }\n\n protected inline fun blockingOp(block: () -> T): T {\n if (!state.compareAndSet(StreamState.Ready, StreamState.Blocked)) {\n throw IOException(\"closed\")\n }\n try {\n return block()\n } finally {\n // If the state is since closed, that's okay.\n state.compareAndSet(StreamState.Blocked, StreamState.Ready)\n }\n }\n\n internal enum class StreamState {\n Ready,\n Blocked,\n Closed,\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":383,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n val previous = state.getAndSet(StreamState.Closed)\n if (previous != StreamState.Closed) {\n stream.close()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":394,"symbol":"cancel","kind":"function","lang":"kotlin","doc":"Equivalent to [close] unless there's a local operation in-flight, in which case the entire socket is interrupted.","code":"fun cancel() {\n val previous = state.getAndSet(StreamState.Closed)\n if (previous != StreamState.Closed) {\n stream.close()\n }\n if (previous == StreamState.Blocked) {\n socket.cancel()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":404,"symbol":"blockingOp","kind":"function","lang":"kotlin","code":"protected inline fun blockingOp(block: () -> T): T {\n if (!state.compareAndSet(StreamState.Ready, StreamState.Blocked)) {\n throw IOException(\"closed\")\n }\n try {\n return block()\n } finally {\n // If the state is since closed, that's okay.\n state.compareAndSet(StreamState.Blocked, StreamState.Ready)\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":416,"symbol":"StreamState","kind":"enum","lang":"kotlin","code":"internal enum class StreamState {\n Ready,\n Blocked,\n Closed,\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":417,"symbol":"Ready","kind":"enum_member","lang":"kotlin","code":"Ready"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":418,"symbol":"Blocked","kind":"enum_member","lang":"kotlin","code":"Blocked"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":419,"symbol":"Closed","kind":"enum_member","lang":"kotlin","code":"Closed"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSocket.kt","line":423,"symbol":"SocketSource","kind":"class","lang":"kotlin","code":"internal class SocketSource(\n socket: OkioSocket,\n) : SocketStream(socket, socket.source),\n Source {\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n blockingOp {\n return stream.read(sink, byteCount)\n }\n }\n\n override fun timeout() = stream.timeout()\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":49,"symbol":"FakeSslSocket","kind":"class","lang":"kotlin","doc":"The TLS layer on top of socket. The [java.net.Socket] API uses inheritance rather than composition for TLS, but this uses composition, and delegates socket methods to its underlying [FakeSocket]. It also relies on that class to hold the state of the TLS handshake.","code":"internal class FakeSslSocket(\n val tls: FakeTls,\n val socket: FakeSocket,\n val hostname: String?,\n tlsVersions: List,\n cipherSuites: List,\n) : SSLSocket() {\n private var sslParameters =\n SSLParameters().apply {\n this.protocols = tlsVersions.map { it.javaName }.toTypedArray()\n this.cipherSuites = cipherSuites.map { it.javaName }.toTypedArray()\n }\n private var enableSessionCreation = true\n private var useClientMode = true\n var echConfigList: ByteString? = null\n\n override fun getEnabledProtocols(): Array = sslParameters.protocols\n\n override fun setEnabledProtocols(protocols: Array) {\n sslParameters.protocols = protocols\n }\n\n override fun getSupportedProtocols() = tls.supportedTlsVersions.map { it.javaName }.toTypedArray()\n\n override fun getSupportedCipherSuites() = tls.supportedCipherSuites.map { it.javaName }.toTypedArray()\n\n override fun getEnabledCipherSuites(): Array = sslParameters.cipherSuites\n\n override fun setEnabledCipherSuites(cipherSuites: Array) {\n sslParameters.cipherSuites = cipherSuites\n }\n\n override fun setNeedClientAuth(needClientAuth: Boolean) {\n sslParameters.nee"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":65,"symbol":"getEnabledProtocols","kind":"function","lang":"kotlin","code":"override fun getEnabledProtocols(): Array = sslParameters.protocols"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":67,"symbol":"setEnabledProtocols","kind":"function","lang":"kotlin","code":"override fun setEnabledProtocols(protocols: Array) {\n sslParameters.protocols = protocols\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":71,"symbol":"getSupportedProtocols","kind":"function","lang":"kotlin","code":"override fun getSupportedProtocols() = tls.supportedTlsVersions.map { it.javaName }.toTypedArray()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":73,"symbol":"getSupportedCipherSuites","kind":"function","lang":"kotlin","code":"override fun getSupportedCipherSuites() = tls.supportedCipherSuites.map { it.javaName }.toTypedArray()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":75,"symbol":"getEnabledCipherSuites","kind":"function","lang":"kotlin","code":"override fun getEnabledCipherSuites(): Array = sslParameters.cipherSuites"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":77,"symbol":"setEnabledCipherSuites","kind":"function","lang":"kotlin","code":"override fun setEnabledCipherSuites(cipherSuites: Array) {\n sslParameters.cipherSuites = cipherSuites\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":81,"symbol":"setNeedClientAuth","kind":"function","lang":"kotlin","code":"override fun setNeedClientAuth(needClientAuth: Boolean) {\n sslParameters.needClientAuth = needClientAuth\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":85,"symbol":"setWantClientAuth","kind":"function","lang":"kotlin","code":"override fun setWantClientAuth(wantClientAuth: Boolean) {\n this.sslParameters.wantClientAuth = wantClientAuth\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":89,"symbol":"getNeedClientAuth","kind":"function","lang":"kotlin","code":"override fun getNeedClientAuth() = sslParameters.needClientAuth"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":91,"symbol":"getWantClientAuth","kind":"function","lang":"kotlin","code":"override fun getWantClientAuth() = sslParameters.wantClientAuth"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":93,"symbol":"setEnableSessionCreation","kind":"function","lang":"kotlin","code":"override fun setEnableSessionCreation(flag: Boolean) {\n this.enableSessionCreation = flag\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":97,"symbol":"getEnableSessionCreation","kind":"function","lang":"kotlin","code":"override fun getEnableSessionCreation() = enableSessionCreation"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":99,"symbol":"getSSLParameters","kind":"function","lang":"kotlin","code":"override fun getSSLParameters() = sslParameters"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":101,"symbol":"setSSLParameters","kind":"function","lang":"kotlin","code":"override fun setSSLParameters(sslParameters: SSLParameters) {\n this.sslParameters = sslParameters\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":105,"symbol":"setUseClientMode","kind":"function","lang":"kotlin","code":"override fun setUseClientMode(useClientMode: Boolean) {\n this.useClientMode = useClientMode\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":109,"symbol":"getUseClientMode","kind":"function","lang":"kotlin","code":"override fun getUseClientMode() = useClientMode"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":111,"symbol":"getSession","kind":"function","lang":"kotlin","code":"override fun getSession(): SSLSession =\n requireHandshake().session\n ?: error(\"unexpected state\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":115,"symbol":"startHandshake","kind":"function","lang":"kotlin","code":"override fun startHandshake() {\n val handshakeState = requireHandshake()\n if (handshakeState is HandshakeState.Failed) {\n throw handshakeState.exception\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":122,"symbol":"requireHandshake","kind":"function","lang":"kotlin","code":"private fun requireHandshake(): HandshakeState {\n val tlsVersions = sslParameters.protocols.map { TlsVersion.forJavaName(it) }\n val cipherSuites = sslParameters.cipherSuites.map { CipherSuite.forJavaName(it) }\n val protocols = sslParameters.applicationProtocols.map { Protocol.get(it) }\n\n val inputs =\n when {\n useClientMode -> {\n Handshaker.ClientInputs(\n tlsVersions = tlsVersions,\n cipherSuites = cipherSuites,\n protocols = protocols,\n keyManager = tls.keyManager,\n hostname = hostname,\n echConfigList = echConfigList,\n )\n }\n\n else -> {\n Handshaker.ServerInputs(\n tlsVersions = tlsVersions,\n cipherSuites = cipherSuites,\n protocols = protocols,\n keyManager = tls.keyManager,\n clientAuth =\n when {\n sslParameters.needClientAuth -> Handshaker.ClientAuth.Required\n sslParameters.wantClientAuth -> Handshaker.ClientAuth.Requested\n else -> Handshaker.ClientAuth.None\n },\n )\n }\n }\n\n val previous = socket.state\n if (pre"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":199,"symbol":"getApplicationProtocol","kind":"function","lang":"kotlin","code":"override fun getApplicationProtocol(): String? {\n val session = socket.state.handshakeState.session ?: return null\n return session.selectedProtocol?.toString() ?: \"\"\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":204,"symbol":"getInputStream","kind":"function","lang":"kotlin","code":"override fun getInputStream(): InputStream {\n val state = socket.state\n if (state !is FakeSocket.State.Connected) throw IOException(\"not connected\")\n if (state.handshakeState.session == null) throw IOException(\"no handshake\")\n return state.inputStream\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":211,"symbol":"getOutputStream","kind":"function","lang":"kotlin","code":"override fun getOutputStream(): OutputStream {\n val state = socket.state\n if (state !is FakeSocket.State.Connected) throw IOException(\"not connected\")\n if (state.handshakeState.session == null) throw IOException(\"no handshake\")\n return state.outputStream\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":218,"symbol":"isInputShutdown","kind":"function","lang":"kotlin","code":"override fun isInputShutdown() = socket.isInputShutdown()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":220,"symbol":"shutdownInput","kind":"function","lang":"kotlin","code":"override fun shutdownInput() {\n socket.shutdownInput()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":224,"symbol":"isOutputShutdown","kind":"function","lang":"kotlin","code":"override fun isOutputShutdown() = socket.isOutputShutdown"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":226,"symbol":"shutdownOutput","kind":"function","lang":"kotlin","code":"override fun shutdownOutput() {\n socket.shutdownOutput()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":230,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n socket.close()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":234,"symbol":"isClosed","kind":"function","lang":"kotlin","code":"override fun isClosed() = socket.isClosed"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":236,"symbol":"getLocalSocketAddress","kind":"function","lang":"kotlin","code":"override fun getLocalSocketAddress() = socket.localSocketAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":238,"symbol":"getLocalAddress","kind":"function","lang":"kotlin","code":"override fun getLocalAddress() = socket.localAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":240,"symbol":"getLocalPort","kind":"function","lang":"kotlin","code":"override fun getLocalPort() = socket.localPort"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":242,"symbol":"getRemoteSocketAddress","kind":"function","lang":"kotlin","code":"override fun getRemoteSocketAddress() = socket.remoteSocketAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":244,"symbol":"getInetAddress","kind":"function","lang":"kotlin","code":"override fun getInetAddress() = socket.inetAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":246,"symbol":"getPort","kind":"function","lang":"kotlin","code":"override fun getPort() = socket.port"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":248,"symbol":"getKeepAlive","kind":"function","lang":"kotlin","code":"override fun getKeepAlive() = socket.keepAlive"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":250,"symbol":"getSoLinger","kind":"function","lang":"kotlin","code":"override fun getSoLinger() = socket.soLinger"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":252,"symbol":"getReceiveBufferSize","kind":"function","lang":"kotlin","code":"override fun getReceiveBufferSize() = socket.receiveBufferSize"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":254,"symbol":"getSendBufferSize","kind":"function","lang":"kotlin","code":"override fun getSendBufferSize() = socket.sendBufferSize"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":256,"symbol":"getSoTimeout","kind":"function","lang":"kotlin","code":"override fun getSoTimeout() = socket.soTimeout"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":258,"symbol":"getTcpNoDelay","kind":"function","lang":"kotlin","code":"override fun getTcpNoDelay() = socket.tcpNoDelay"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":260,"symbol":"setKeepAlive","kind":"function","lang":"kotlin","code":"override fun setKeepAlive(keepAlive: Boolean) {\n socket.setKeepAlive(keepAlive)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":264,"symbol":"setSendBufferSize","kind":"function","lang":"kotlin","code":"override fun setSendBufferSize(sendBufferSize: Int) {\n socket.setSendBufferSize(sendBufferSize)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":268,"symbol":"setReceiveBufferSize","kind":"function","lang":"kotlin","code":"override fun setReceiveBufferSize(receiveBufferSize: Int) {\n socket.setReceiveBufferSize(receiveBufferSize)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":272,"symbol":"setSoLinger","kind":"function","lang":"kotlin","code":"override fun setSoLinger(\n on: Boolean,\n timeout: Int,\n ) {\n socket.setSoLinger(on, timeout)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":279,"symbol":"setSoTimeout","kind":"function","lang":"kotlin","code":"override fun setSoTimeout(soTimeout: Int) {\n socket.soTimeout = soTimeout\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":283,"symbol":"setTcpNoDelay","kind":"function","lang":"kotlin","code":"override fun setTcpNoDelay(tcpNoDelay: Boolean) {\n socket.setTcpNoDelay(tcpNoDelay)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":287,"symbol":"isBound","kind":"function","lang":"kotlin","code":"override fun isBound() = socket.isBound"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":289,"symbol":"isConnected","kind":"function","lang":"kotlin","code":"override fun isConnected() = socket.isConnected"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":291,"symbol":"bind","kind":"function","lang":"kotlin","code":"override fun bind(localAddr: SocketAddress) {\n socket.bind(localAddr)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":295,"symbol":"connect","kind":"function","lang":"kotlin","code":"override fun connect(remoteAddr: SocketAddress) {\n socket.connect(remoteAddr)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":299,"symbol":"connect","kind":"function","lang":"kotlin","code":"override fun connect(\n remoteAddr: SocketAddress,\n timeout: Int,\n ) {\n socket.connect(remoteAddr, timeout)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":306,"symbol":"setReuseAddress","kind":"function","lang":"kotlin","code":"override fun setReuseAddress(reuseAddress: Boolean) {\n socket.setReuseAddress(reuseAddress)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":310,"symbol":"getReuseAddress","kind":"function","lang":"kotlin","code":"override fun getReuseAddress() = socket.reuseAddress"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":312,"symbol":"setOOBInline","kind":"function","lang":"kotlin","code":"override fun setOOBInline(oobInline: Boolean) {\n socket.setOOBInline(oobInline)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":316,"symbol":"getOOBInline","kind":"function","lang":"kotlin","code":"override fun getOOBInline() = socket.oobInline"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":318,"symbol":"setTrafficClass","kind":"function","lang":"kotlin","code":"override fun setTrafficClass(trafficClass: Int) {\n socket.setTrafficClass(trafficClass)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":322,"symbol":"getTrafficClass","kind":"function","lang":"kotlin","code":"override fun getTrafficClass() = socket.trafficClass"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":324,"symbol":"getChannel","kind":"function","lang":"kotlin","code":"override fun getChannel(): SocketChannel = socket.channel"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeSslSocket.kt","line":326,"symbol":"sendUrgentData","kind":"function","lang":"kotlin","code":"override fun sendUrgentData(data: Int) = socket.sendUrgentData(data)"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":38,"symbol":"FakeTls","kind":"class","lang":"kotlin","doc":"independent instances of [FakeTls]. This allows us to simulate different configurations for each peer. Note that only the client's [handshaker] is used, and its result is used by both client and server.","code":"class FakeTls(\n val handshaker: Handshaker,\n val keyManager: X509KeyManager,\n val trustManager: X509TrustManager,\n val supportedTlsVersions: List =\n listOf(\n TlsVersion.TLS_1_3,\n TlsVersion.TLS_1_2,\n ),\n val enabledTlsVersions: List = supportedTlsVersions,\n val supportedCipherSuites: List =\n listOf(\n CipherSuite.TLS_AES_128_GCM_SHA256, // TLSv1.3.\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, // TLSv1.2\n ),\n val defaultCipherSuites: List = supportedCipherSuites,\n) {\n constructor(\n handshaker: Handshaker,\n handshakeCertificates: HandshakeCertificates,\n ) : this(\n handshaker = handshaker,\n keyManager = handshakeCertificates.keyManager,\n trustManager = handshakeCertificates.trustManager,\n )\n\n val sslSocketFactory =\n object : SSLSocketFactory() {\n override fun getDefaultCipherSuites() = this@FakeTls.defaultCipherSuites.map { it.javaName }.toTypedArray()\n\n override fun getSupportedCipherSuites() = this@FakeTls.supportedCipherSuites.map { it.javaName }.toTypedArray()\n\n override fun createSocket(\n socket: Socket,\n consumed: InputStream,\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":66,"symbol":"getDefaultCipherSuites","kind":"function","lang":"kotlin","code":"override fun getDefaultCipherSuites() = this@FakeTls.defaultCipherSuites.map { it.javaName }.toTypedArray()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":68,"symbol":"getSupportedCipherSuites","kind":"function","lang":"kotlin","code":"override fun getSupportedCipherSuites() = this@FakeTls.supportedCipherSuites.map { it.javaName }.toTypedArray()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":70,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n socket: Socket,\n consumed: InputStream,\n autoClose: Boolean,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":76,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket() = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":78,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n socket: Socket,\n host: String?,\n port: Int,\n autoClose: Boolean,\n ): FakeSslSocket {\n require(autoClose)\n return FakeSslSocket(\n tls = this@FakeTls,\n socket = socket as FakeSocket,\n hostname = host,\n tlsVersions = this@FakeTls.enabledTlsVersions,\n cipherSuites = this@FakeTls.defaultCipherSuites,\n )\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":94,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: String?,\n port: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":99,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: String?,\n port: Int,\n localHost: InetAddress,\n localPort: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":106,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n host: InetAddress?,\n port: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt","line":111,"symbol":"createSocket","kind":"function","lang":"kotlin","code":"override fun createSocket(\n address: InetAddress,\n port: Int,\n localAddress: InetAddress?,\n localPort: Int,\n ) = error(\"unsupported\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt","line":35,"symbol":"Handshaker","kind":"interface","lang":"kotlin","doc":"[Protocol] to negotiate. In a real TLS handshake the client and server are mutually-distrusting parties, and they each implement their own handshaking logic. For this fake, we use a single handshaker that makes decisions on behalf of both parties.","code":"interface Handshaker {\n /**\n * Returns a two-element array containing the client result and the server result.\n */\n fun handshake(\n client: ClientInputs,\n server: ServerInputs,\n ): Result\n\n sealed interface Inputs {\n val tlsVersions: List\n val cipherSuites: List\n val protocols: List?\n val keyManager: X509KeyManager\n }\n\n data class ClientInputs(\n override val tlsVersions: List,\n override val cipherSuites: List,\n override val protocols: List?,\n override val keyManager: X509KeyManager,\n val hostname: String?,\n val echConfigList: ByteString?,\n ) : Inputs\n\n data class ServerInputs(\n override val tlsVersions: List,\n override val cipherSuites: List,\n override val protocols: List?,\n override val keyManager: X509KeyManager,\n val clientAuth: ClientAuth,\n ) : Inputs\n\n enum class ClientAuth {\n None,\n Requested,\n Required,\n }\n\n sealed interface Result {\n val clientHandshake: Handshake?\n val serverHandshake: Handshake?\n val selectedProtocol: Protocol?\n\n class Success(\n val clientSocket: Socket,\n "} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt","line":39,"symbol":"handshake","kind":"function","lang":"kotlin","doc":"Returns a two-element array containing the client result and the server result.","code":"fun handshake(\n client: ClientInputs,\n server: ServerInputs,\n ): Result"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt","line":44,"symbol":"Inputs","kind":"interface","lang":"kotlin","code":"sealed interface Inputs {\n val tlsVersions: List\n val cipherSuites: List\n val protocols: List?\n val keyManager: X509KeyManager\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt","line":68,"symbol":"ClientAuth","kind":"enum","lang":"kotlin","code":"enum class ClientAuth {\n None,\n Requested,\n Required,\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt","line":69,"symbol":"None","kind":"enum_member","lang":"kotlin","code":"None"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt","line":70,"symbol":"Requested","kind":"enum_member","lang":"kotlin","code":"Requested"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt","line":71,"symbol":"Required","kind":"enum_member","lang":"kotlin","code":"Required"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/Handshaker.kt","line":74,"symbol":"Result","kind":"interface","lang":"kotlin","code":"sealed interface Result {\n val clientHandshake: Handshake?\n val serverHandshake: Handshake?\n val selectedProtocol: Protocol?\n\n class Success(\n val clientSocket: Socket,\n val serverSocket: Socket,\n override val clientHandshake: Handshake,\n override val serverHandshake: Handshake,\n override val selectedProtocol: Protocol?,\n ) : Result\n\n class Failure(\n val exception: SSLException,\n override val clientHandshake: Handshake? = null,\n override val serverHandshake: Handshake? = null,\n override val selectedProtocol: Protocol? = null,\n ) : Result\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/InsecureHandshaker.kt","line":28,"symbol":"InsecureHandshaker","kind":"class","lang":"kotlin","doc":"A basic handshaker that makes policy decisions without doing any useful cryptography.","code":"class InsecureHandshaker : Handshaker {\n override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n val tlsVersion =\n server.tlsVersions.firstOrNull { it in client.tlsVersions }\n ?: throw SSLHandshakeException(\"no matching TLS version\")\n val cipherSuite =\n server.cipherSuites.firstOrNull { it in client.cipherSuites }\n ?: throw SSLHandshakeException(\"no matching cipher suite\")\n val protocol =\n server.protocols\n .orEmpty()\n .firstOrNull { it in client.protocols.orEmpty() }\n\n // For more accuracy, we should pick the key type based on the cipher suite.\n val keyType = \"EC\"\n\n val clientCertificates =\n when (server.clientAuth) {\n Handshaker.ClientAuth.Required -> {\n client.keyManager.clientCertificatesOrNull(keyType)\n ?: throw SSLHandshakeException(\"required client certificates not sent\")\n }\n\n Handshaker.ClientAuth.Requested -> {\n client.keyManager.clientCertificatesOrNull(keyType)\n ?: listOf()\n }\n\n Handshaker.ClientAuth.None -> {\n listOf()\n }\n }\n\n val serverCer"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/InsecureHandshaker.kt","line":29,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: Handshaker.ClientInputs,\n server: Handshaker.ServerInputs,\n ): Handshaker.Result {\n val tlsVersion =\n server.tlsVersions.firstOrNull { it in client.tlsVersions }\n ?: throw SSLHandshakeException(\"no matching TLS version\")\n val cipherSuite =\n server.cipherSuites.firstOrNull { it in client.cipherSuites }\n ?: throw SSLHandshakeException(\"no matching cipher suite\")\n val protocol =\n server.protocols\n .orEmpty()\n .firstOrNull { it in client.protocols.orEmpty() }\n\n // For more accuracy, we should pick the key type based on the cipher suite.\n val keyType = \"EC\"\n\n val clientCertificates =\n when (server.clientAuth) {\n Handshaker.ClientAuth.Required -> {\n client.keyManager.clientCertificatesOrNull(keyType)\n ?: throw SSLHandshakeException(\"required client certificates not sent\")\n }\n\n Handshaker.ClientAuth.Requested -> {\n client.keyManager.clientCertificatesOrNull(keyType)\n ?: listOf()\n }\n\n Handshaker.ClientAuth.None -> {\n listOf()\n }\n }\n\n val serverCertificates = server.keyManager.serverCertif"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/InsecureHandshaker.kt","line":89,"symbol":"serverCertificates","kind":"function","lang":"kotlin","code":"private fun X509KeyManager.serverCertificates(keyType: String): List {\n val alias =\n getServerAliases(keyType, null)\n .firstOrNull()\n ?: throw SSLHandshakeException(\"no server aliases for $keyType\")\n\n return getCertificateChain(alias).toList()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/sockets/InsecureHandshaker.kt","line":98,"symbol":"clientCertificatesOrNull","kind":"function","lang":"kotlin","code":"private fun X509KeyManager.clientCertificatesOrNull(keyType: String): List? {\n val alias =\n getClientAliases(keyType, null)\n .firstOrNull()\n ?: return null\n\n return getCertificateChain(alias).toList()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":70,"symbol":"beforeEach","kind":"function","lang":"kotlin","code":"override fun beforeEach(context: ExtensionContext) {\n setupPlatform()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":74,"symbol":"afterEach","kind":"function","lang":"kotlin","code":"override fun afterEach(context: ExtensionContext) {\n resetPlatform()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":78,"symbol":"interceptTestMethod","kind":"function","lang":"kotlin","code":"override fun interceptTestMethod(\n invocation: InvocationInterceptor.Invocation,\n invocationContext: ReflectiveInvocationContext,\n extensionContext: ExtensionContext,\n ) {\n var failed = false\n try {\n invocation.proceed()\n } catch (e: TestAbortedException) {\n throw e\n } catch (e: Throwable) {\n failed = true\n rethrowIfNotExpected(e)\n } finally {\n resetPlatform()\n }\n if (!failed) {\n failIfExpected()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":99,"symbol":"setupPlatform","kind":"function","lang":"kotlin","code":"fun setupPlatform() {\n if (requiredPlatformName != null) {\n assumeTrue(getPlatformSystemProperty() == requiredPlatformName)\n }\n\n if (platform != null) {\n Platform.resetForTests(platform)\n } else {\n Platform.resetForTests()\n }\n\n if (requiredPlatformName != null) {\n System.err.println(\"Running with ${Platform.get().javaClass.simpleName}\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":115,"symbol":"resetPlatform","kind":"function","lang":"kotlin","code":"fun resetPlatform() {\n if (platform != null) {\n Platform.resetForTests()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":121,"symbol":"expectFailureOnConscryptPlatform","kind":"function","lang":"kotlin","code":"fun expectFailureOnConscryptPlatform() {\n expectFailure(platformMatches(CONSCRYPT_PROPERTY))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":125,"symbol":"expectFailureOnCorrettoPlatform","kind":"function","lang":"kotlin","code":"fun expectFailureOnCorrettoPlatform() {\n expectFailure(platformMatches(CORRETTO_PROPERTY))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":129,"symbol":"expectFailureOnOpenJSSEPlatform","kind":"function","lang":"kotlin","code":"fun expectFailureOnOpenJSSEPlatform() {\n expectFailure(platformMatches(OPENJSSE_PROPERTY))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":133,"symbol":"expectFailureFromJdkVersion","kind":"function","lang":"kotlin","code":"fun expectFailureFromJdkVersion(majorVersion: Int) {\n if (!TestUtil.isGraalVmImage) {\n expectFailure(fromMajor(majorVersion))\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":139,"symbol":"expectFailureOnJdkVersion","kind":"function","lang":"kotlin","code":"fun expectFailureOnJdkVersion(majorVersion: Int) {\n if (!TestUtil.isGraalVmImage) {\n expectFailure(onMajor(majorVersion))\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":145,"symbol":"expectFailureOnLoomPlatform","kind":"function","lang":"kotlin","code":"fun expectFailureOnLoomPlatform() {\n expectFailure(platformMatches(LOOM_PROPERTY))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":149,"symbol":"expectFailure","kind":"function","lang":"kotlin","code":"private fun expectFailure(\n versionMatcher: Matcher,\n failureMatcher: Matcher = anything(),\n ) {\n versionChecks.add(Pair(versionMatcher, failureMatcher))\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":156,"symbol":"platformMatches","kind":"function","lang":"kotlin","code":"fun platformMatches(platform: String): Matcher =\n object : BaseMatcher() {\n override fun describeTo(description: Description) {\n description.appendText(platform)\n }\n\n override fun matches(item: Any?): Boolean = getPlatformSystemProperty() == platform\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":158,"symbol":"describeTo","kind":"function","lang":"kotlin","code":"override fun describeTo(description: Description) {\n description.appendText(platform)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":162,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(item: Any?): Boolean = getPlatformSystemProperty() == platform"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":165,"symbol":"fromMajor","kind":"function","lang":"kotlin","code":"fun fromMajor(version: Int): Matcher =\n object : TypeSafeMatcher() {\n override fun describeTo(description: Description) {\n description.appendText(\"JDK with version from $version\")\n }\n\n override fun matchesSafely(item: PlatformVersion): Boolean = item.majorVersion >= version\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":167,"symbol":"describeTo","kind":"function","lang":"kotlin","code":"override fun describeTo(description: Description) {\n description.appendText(\"JDK with version from $version\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":171,"symbol":"matchesSafely","kind":"function","lang":"kotlin","code":"override fun matchesSafely(item: PlatformVersion): Boolean = item.majorVersion >= version"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":174,"symbol":"onMajor","kind":"function","lang":"kotlin","code":"fun onMajor(version: Int): Matcher =\n object : TypeSafeMatcher() {\n override fun describeTo(description: Description) {\n description.appendText(\"JDK with version $version\")\n }\n\n override fun matchesSafely(item: PlatformVersion): Boolean = item.majorVersion == version\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":176,"symbol":"describeTo","kind":"function","lang":"kotlin","code":"override fun describeTo(description: Description) {\n description.appendText(\"JDK with version $version\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":180,"symbol":"matchesSafely","kind":"function","lang":"kotlin","code":"override fun matchesSafely(item: PlatformVersion): Boolean = item.majorVersion == version"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":183,"symbol":"rethrowIfNotExpected","kind":"function","lang":"kotlin","code":"fun rethrowIfNotExpected(e: Throwable) {\n versionChecks.forEach { (versionMatcher, failureMatcher) ->\n if (versionMatcher.matches(PlatformVersion) && failureMatcher.matches(e)) {\n return\n }\n }\n\n throw e\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":193,"symbol":"failIfExpected","kind":"function","lang":"kotlin","code":"fun failIfExpected() {\n versionChecks.forEach { (versionMatcher, failureMatcher) ->\n if (versionMatcher.matches(PlatformVersion)) {\n val description = StringDescription()\n versionMatcher.describeTo(description)\n description.appendText(\" expected to fail with exception that \")\n failureMatcher.describeTo(description)\n\n fail(description.toString())\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":206,"symbol":"isConscrypt","kind":"function","lang":"kotlin","code":"fun isConscrypt() = getPlatformSystemProperty() == CONSCRYPT_PROPERTY"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":208,"symbol":"isJdk9","kind":"function","lang":"kotlin","code":"fun isJdk9() = getPlatformSystemProperty() == JDK9_PROPERTY"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":210,"symbol":"isJdk8","kind":"function","lang":"kotlin","code":"fun isJdk8() = getPlatformSystemProperty() == JDK8_PROPERTY"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":212,"symbol":"isJdk8Alpn","kind":"function","lang":"kotlin","code":"fun isJdk8Alpn() = getPlatformSystemProperty() == JDK8_ALPN_PROPERTY"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":214,"symbol":"isBouncyCastle","kind":"function","lang":"kotlin","code":"fun isBouncyCastle() = getPlatformSystemProperty() == BOUNCYCASTLE_PROPERTY"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":216,"symbol":"isOpenJsse","kind":"function","lang":"kotlin","code":"fun isOpenJsse() = getPlatformSystemProperty() == OPENJSSE_PROPERTY"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":218,"symbol":"isLoom","kind":"function","lang":"kotlin","code":"fun isLoom() = getPlatformSystemProperty() == LOOM_PROPERTY"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":220,"symbol":"isGraalVMImage","kind":"function","lang":"kotlin","code":"fun isGraalVMImage() = TestUtil.isGraalVmImage"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":222,"symbol":"hasHttp2Support","kind":"function","lang":"kotlin","code":"fun hasHttp2Support() = !isJdk8()"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":224,"symbol":"assumeConscrypt","kind":"function","lang":"kotlin","code":"fun assumeConscrypt() {\n assumeTrue(getPlatformSystemProperty() == CONSCRYPT_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":228,"symbol":"assumeJdk9","kind":"function","lang":"kotlin","code":"fun assumeJdk9() {\n assumeTrue(getPlatformSystemProperty() == JDK9_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":232,"symbol":"assumeOpenJSSE","kind":"function","lang":"kotlin","code":"fun assumeOpenJSSE() {\n assumeTrue(getPlatformSystemProperty() == OPENJSSE_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":236,"symbol":"assumeJdk8","kind":"function","lang":"kotlin","code":"fun assumeJdk8() {\n assumeTrue(getPlatformSystemProperty() == JDK8_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":240,"symbol":"assumeJdk8Alpn","kind":"function","lang":"kotlin","code":"fun assumeJdk8Alpn() {\n assumeTrue(getPlatformSystemProperty() == JDK8_ALPN_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":244,"symbol":"assumeCorretto","kind":"function","lang":"kotlin","code":"fun assumeCorretto() {\n assumeTrue(getPlatformSystemProperty() == CORRETTO_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":248,"symbol":"assumeBouncyCastle","kind":"function","lang":"kotlin","code":"fun assumeBouncyCastle() {\n assumeTrue(getPlatformSystemProperty() == BOUNCYCASTLE_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":252,"symbol":"assumeOpenJsse","kind":"function","lang":"kotlin","code":"fun assumeOpenJsse() {\n assumeTrue(getPlatformSystemProperty() == OPENJSSE_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":256,"symbol":"assumeLoom","kind":"function","lang":"kotlin","code":"fun assumeLoom() {\n assumeTrue(getPlatformSystemProperty() == LOOM_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":260,"symbol":"assumeHttp2Support","kind":"function","lang":"kotlin","code":"fun assumeHttp2Support() {\n assumeTrue(getPlatformSystemProperty() != JDK8_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":264,"symbol":"assumeAndroid","kind":"function","lang":"kotlin","code":"fun assumeAndroid() {\n assumeTrue(Platform.isAndroid)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":268,"symbol":"assumeGraalVMImage","kind":"function","lang":"kotlin","code":"fun assumeGraalVMImage() {\n assumeTrue(isGraalVMImage())\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":272,"symbol":"assumeNotConscrypt","kind":"function","lang":"kotlin","code":"fun assumeNotConscrypt() {\n assumeTrue(getPlatformSystemProperty() != CONSCRYPT_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":276,"symbol":"assumeNotJdk9","kind":"function","lang":"kotlin","code":"fun assumeNotJdk9() {\n assumeTrue(getPlatformSystemProperty() != JDK9_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":280,"symbol":"assumeNotJdk8","kind":"function","lang":"kotlin","code":"fun assumeNotJdk8() {\n assumeTrue(getPlatformSystemProperty() != JDK8_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":284,"symbol":"assumeNotJdk8Alpn","kind":"function","lang":"kotlin","code":"fun assumeNotJdk8Alpn() {\n assumeTrue(getPlatformSystemProperty() != JDK8_ALPN_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":288,"symbol":"assumeNotOpenJSSE","kind":"function","lang":"kotlin","code":"fun assumeNotOpenJSSE() {\n assumeTrue(getPlatformSystemProperty() != OPENJSSE_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":292,"symbol":"assumeNotLoom","kind":"function","lang":"kotlin","code":"fun assumeNotLoom() {\n assumeTrue(getPlatformSystemProperty() != LOOM_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":296,"symbol":"assumeNotCorretto","kind":"function","lang":"kotlin","code":"fun assumeNotCorretto() {\n assumeTrue(getPlatformSystemProperty() != CORRETTO_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":300,"symbol":"assumeNotBouncyCastle","kind":"function","lang":"kotlin","code":"fun assumeNotBouncyCastle() {\n // Most failures are with MockWebServer\n // org.bouncycastle.tls.TlsFatalAlertReceived: handshake_failure(40)\n // at org.bouncycastle.tls.TlsProtocol.handleAlertMessage(TlsProtocol.java:241)\n assumeTrue(getPlatformSystemProperty() != BOUNCYCASTLE_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":307,"symbol":"assumeNotOpenJsse","kind":"function","lang":"kotlin","code":"fun assumeNotOpenJsse() {\n assumeTrue(getPlatformSystemProperty() != OPENJSSE_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":311,"symbol":"assumeNotHttp2Support","kind":"function","lang":"kotlin","code":"fun assumeNotHttp2Support() {\n assumeTrue(getPlatformSystemProperty() == JDK8_PROPERTY)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":315,"symbol":"assumeJettyBootEnabled","kind":"function","lang":"kotlin","code":"fun assumeJettyBootEnabled() {\n assumeTrue(isAlpnBootEnabled())\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":319,"symbol":"assumeNotAndroid","kind":"function","lang":"kotlin","code":"fun assumeNotAndroid() {\n assumeFalse(Platform.isAndroid)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":323,"symbol":"assumeNotGraalVMImage","kind":"function","lang":"kotlin","code":"fun assumeNotGraalVMImage() {\n assumeFalse(isGraalVMImage())\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":327,"symbol":"assumeJdkVersion","kind":"function","lang":"kotlin","code":"fun assumeJdkVersion(majorVersion: Int) {\n assumeNotAndroid()\n assumeNotGraalVMImage()\n assumeTrue(PlatformVersion.majorVersion == majorVersion)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":333,"symbol":"androidSdkVersion","kind":"function","lang":"kotlin","code":"fun androidSdkVersion(): Int? =\n if (Platform.isAndroid) {\n Build.VERSION.SDK_INT\n } else {\n null\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformRule.kt","line":340,"symbol":"localhostHandshakeCertificates","kind":"function","lang":"kotlin","code":"fun localhostHandshakeCertificates(): HandshakeCertificates =\n when {\n isBouncyCastle() -> localhostHandshakeCertificatesWithRsa2048\n else -> localhost()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformVersion.kt","line":18,"symbol":"PlatformVersion","kind":"object","lang":"kotlin","code":"object PlatformVersion {\n val majorVersion: Int by lazy {\n when (val jvmSpecVersion = getJvmSpecVersion()) {\n \"1.8\" -> 8\n else -> jvmSpecVersion.toInt()\n }\n }\n\n fun getJvmSpecVersion(): String = System.getProperty(\"java.specification.version\", \"unknown\")\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/main/kotlin/okhttp3/testing/PlatformVersion.kt","line":26,"symbol":"getJvmSpecVersion","kind":"function","lang":"kotlin","code":"fun getJvmSpecVersion(): String = System.getProperty(\"java.specification.version\", \"unknown\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/OkHttpClientTestRuleTest.kt","line":26,"symbol":"OkHttpClientTestRuleTest","kind":"class","lang":"kotlin","code":"class OkHttpClientTestRuleTest {\n lateinit var extensionContext: ExtensionContext\n\n @RegisterExtension @JvmField\n val beforeEachCallback =\n BeforeEachCallback { context ->\n this@OkHttpClientTestRuleTest.extensionContext = context\n }\n\n @Test fun uncaughtException() {\n val testRule = OkHttpClientTestRule()\n testRule.beforeEach(extensionContext)\n\n val thread =\n object : Thread() {\n override fun run(): Unit = throw RuntimeException(\"boom!\")\n }\n thread.start()\n thread.join()\n\n assertFailsWith {\n testRule.afterEach(extensionContext)\n }.also { expected ->\n assertThat(expected).hasMessage(\"uncaught exception thrown during test\")\n assertThat(expected.cause!!).hasMessage(\"boom!\")\n }\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/OkHttpClientTestRuleTest.kt","line":35,"symbol":"uncaughtException","kind":"function","lang":"kotlin","code":"@Test fun uncaughtException() {\n val testRule = OkHttpClientTestRule()\n testRule.beforeEach(extensionContext)\n\n val thread =\n object : Thread() {\n override fun run(): Unit = throw RuntimeException(\"boom!\")\n }\n thread.start()\n thread.join()\n\n assertFailsWith {\n testRule.afterEach(extensionContext)\n }.also { expected ->\n assertThat(expected).hasMessage(\"uncaught exception thrown during test\")\n assertThat(expected.cause!!).hasMessage(\"boom!\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/OkHttpClientTestRuleTest.kt","line":41,"symbol":"run","kind":"function","lang":"kotlin","code":"override fun run(): Unit = throw RuntimeException(\"boom!\")"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":38,"symbol":"FakeNetworkTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass FakeNetworkTest {\n @RegisterExtension\n @JvmField\n val clientTestRule = OkHttpClientTestRule()\n\n val taskRunner = TaskRunner.INSTANCE\n val network = FakeNetwork()\n val server = network.serverSocketFactory.createServerSocket()\n val serverAddress = network.nextSocketAddress()\n\n @AfterEach\n fun tearDown() {\n server.close()\n }\n\n @Test\n fun `happy path`() {\n server.bind(serverAddress, 3)\n\n taskRunner.schedule(\"client\") {\n network.socketFactory.createSocket().use { socket ->\n socket.connect(serverAddress, 5_000)\n\n val sink = socket.getOutputStream().sink().buffer()\n sink.writeUtf8(\"hello from client\\n\")\n sink.flush()\n\n val source = socket.getInputStream().source().buffer()\n assertThat(source.readUtf8Line()).isEqualTo(\"hello from server\")\n }\n }\n\n server.accept().use { socket ->\n val source = socket.getInputStream().source().buffer()\n assertThat(source.readUtf8Line()).isEqualTo(\"hello from client\")\n\n val sink = socket.getOutputStream().sink().buffer()\n sink.writeUtf8(\"hello from server\\n\")\n sink.flush()\n }\n }\n\n @Test\n fun `cannot bind when already bound by anot"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":49,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n server.close()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":54,"symbol":"`happy path`","kind":"function","lang":"kotlin","code":"@Test\n fun `happy path`() {\n server.bind(serverAddress, 3)\n\n taskRunner.schedule(\"client\") {\n network.socketFactory.createSocket().use { socket ->\n socket.connect(serverAddress, 5_000)\n\n val sink = socket.getOutputStream().sink().buffer()\n sink.writeUtf8(\"hello from client\\n\")\n sink.flush()\n\n val source = socket.getInputStream().source().buffer()\n assertThat(source.readUtf8Line()).isEqualTo(\"hello from server\")\n }\n }\n\n server.accept().use { socket ->\n val source = socket.getInputStream().source().buffer()\n assertThat(source.readUtf8Line()).isEqualTo(\"hello from client\")\n\n val sink = socket.getOutputStream().sink().buffer()\n sink.writeUtf8(\"hello from server\\n\")\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":81,"symbol":"`cannot bind when already bound by another server`","kind":"function","lang":"kotlin","code":"@Test\n fun `cannot bind when already bound by another server`() {\n server.bind(serverAddress, 3)\n\n val server2 = network.serverSocketFactory.createServerSocket()\n val e =\n assertFailsWith {\n server2.bind(serverAddress, 3)\n }\n assertThat(e).hasMessage(\"bind collision\")\n\n server2.close()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":95,"symbol":"`cannot bind after close`","kind":"function","lang":"kotlin","code":"@Test\n fun `cannot bind after close`() {\n server.close()\n\n val e =\n assertFailsWith {\n server.bind(serverAddress, 3)\n }\n assertThat(e).hasMessage(\"cannot bind\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":106,"symbol":"`cannot accept without bind`","kind":"function","lang":"kotlin","code":"@Test\n fun `cannot accept without bind`() {\n val e =\n assertFailsWith {\n server.accept()\n }\n assertThat(e).hasMessage(\"not bound\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":115,"symbol":"`reuse server address`","kind":"function","lang":"kotlin","code":"@Test\n fun `reuse server address`() {\n server.bind(serverAddress, 3)\n\n taskRunner.schedule(\"clientA\") {\n val client = network.socketFactory.createSocket()\n client.connect(serverAddress, 5_000)\n client.close()\n }\n\n val acceptedClientA = server.accept()\n acceptedClientA.close()\n\n server.close()\n\n val server2 = network.serverSocketFactory.createServerSocket()\n server2.bind(serverAddress, 3)\n\n taskRunner.schedule(\"clientB\") {\n val client = network.socketFactory.createSocket()\n client.connect(serverAddress, 5_000)\n client.close()\n }\n\n val acceptedClientB = server2.accept()\n acceptedClientB.close()\n\n server2.close()\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":145,"symbol":"`cannot connect after close`","kind":"function","lang":"kotlin","code":"@Test\n fun `cannot connect after close`() {\n val client = network.socketFactory.createSocket()\n client.close()\n\n val e =\n assertFailsWith {\n client.connect(serverAddress, 5_000)\n }\n assertThat(e).hasMessage(\"cannot connect\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":157,"symbol":"`connect fails because server is closed`","kind":"function","lang":"kotlin","code":"@Test\n fun `connect fails because server is closed`() {\n server.bind(serverAddress, 3)\n\n taskRunner.schedule(\"close server later\", 250.milliseconds) {\n server.close()\n }\n\n val client = network.socketFactory.createSocket()\n val elapsed =\n measureTime {\n val e =\n assertFailsWith {\n client.connect(serverAddress, 5_000)\n }\n assertThat(e).hasMessage(\"server closed\")\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":177,"symbol":"`connect fails because client is closed`","kind":"function","lang":"kotlin","code":"@Test\n fun `connect fails because client is closed`() {\n server.bind(serverAddress, 3)\n\n val client = network.socketFactory.createSocket()\n taskRunner.schedule(\"close client later\", 250.milliseconds) {\n client.close()\n }\n\n val elapsed =\n measureTime {\n val e =\n assertFailsWith {\n client.connect(serverAddress, 5_000)\n }\n assertThat(e).hasMessage(\"client closed\")\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":197,"symbol":"`accept fails because server is closed`","kind":"function","lang":"kotlin","code":"@Test\n fun `accept fails because server is closed`() {\n server.bind(serverAddress, 3)\n\n taskRunner.schedule(\"close server later\", 250.milliseconds) {\n server.close()\n }\n\n val elapsed =\n measureTime {\n val e =\n assertFailsWith {\n server.accept()\n }\n assertThat(e).hasMessage(\"closed\")\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":216,"symbol":"`connect timeout waiting for accept`","kind":"function","lang":"kotlin","code":"@Test\n fun `connect timeout waiting for accept`() {\n server.bind(serverAddress, 3)\n\n val client = network.socketFactory.createSocket()\n val elapsed =\n measureTime {\n assertFailsWith {\n client.connect(serverAddress, 250)\n }\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":234,"symbol":"`connect timeout waiting in backlog`","kind":"function","lang":"kotlin","doc":"This is effectively the same as [`connect timeout waiting for accept`], but in this test we're waiting for a slot in the server's backlog.","code":"@Test\n fun `connect timeout waiting in backlog`() {\n server.bind(serverAddress, 3)\n\n // Put 3 clients in the server's backlog, all blocked waiting for accept().\n connectExpectingServerClose(\"clientA\")\n connectExpectingServerClose(\"clientB\")\n connectExpectingServerClose(\"clientC\")\n\n // A 4th client will time out waiting in the backlog. We don't start it for 100 ms so the\n // previously-started clients can fill up the backlog.\n Thread.sleep(100)\n val clientD = network.socketFactory.createSocket()\n val elapsed =\n measureTime {\n assertFailsWith {\n clientD.connect(serverAddress, 250)\n }\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeNetworkTest.kt","line":256,"symbol":"connectExpectingServerClose","kind":"function","lang":"kotlin","code":"private fun connectExpectingServerClose(name: String) {\n val client = network.socketFactory.createSocket()\n taskRunner.schedule(name) {\n val e =\n assertFailsWith {\n client.connect(serverAddress, 5_000)\n }\n assertThat(e).hasMessage(\"server closed\")\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":43,"symbol":"FakeTlsTest","kind":"class","lang":"kotlin","code":"@Tag(\"Slowish\")\nclass FakeTlsTest {\n @RegisterExtension\n @JvmField\n val clientTestRule = OkHttpClientTestRule()\n\n val taskRunner = TaskRunner.INSTANCE\n val network = FakeNetwork()\n\n val clientTls =\n FakeTls(\n handshaker = InsecureHandshaker(),\n handshakeCertificates = TlsUtil.localhost(),\n )\n val serverTls =\n FakeTls(\n handshaker = InsecureHandshaker(),\n handshakeCertificates = TlsUtil.localhost(),\n )\n\n @Test\n fun `happy path`() {\n val (clientSocket, serverSocket) = network.socketPair()\n val clientSslSocket = clientTls.clientSocket(clientSocket)\n val serverSslSocket = serverTls.serverSocket(serverSocket)\n\n taskRunner.schedule(\"client\") {\n clientSslSocket.startHandshake()\n clientSslSocket.use { socket ->\n val sink = socket.getOutputStream().sink().buffer()\n sink.writeUtf8(\"hello from client\\n\")\n sink.flush()\n\n val source = socket.getInputStream().source().buffer()\n assertThat(source.readUtf8Line()).isEqualTo(\"hello from server\")\n }\n }\n\n serverSslSocket.startHandshake()\n serverSslSocket.use { socket ->\n val source = socket.getInputStream().source().buffer()\n asser"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":63,"symbol":"`happy path`","kind":"function","lang":"kotlin","code":"@Test\n fun `happy path`() {\n val (clientSocket, serverSocket) = network.socketPair()\n val clientSslSocket = clientTls.clientSocket(clientSocket)\n val serverSslSocket = serverTls.serverSocket(serverSocket)\n\n taskRunner.schedule(\"client\") {\n clientSslSocket.startHandshake()\n clientSslSocket.use { socket ->\n val sink = socket.getOutputStream().sink().buffer()\n sink.writeUtf8(\"hello from client\\n\")\n sink.flush()\n\n val source = socket.getInputStream().source().buffer()\n assertThat(source.readUtf8Line()).isEqualTo(\"hello from server\")\n }\n }\n\n serverSslSocket.startHandshake()\n serverSslSocket.use { socket ->\n val source = socket.getInputStream().source().buffer()\n assertThat(source.readUtf8Line()).isEqualTo(\"hello from client\")\n\n val sink = socket.getOutputStream().sink().buffer()\n sink.writeUtf8(\"hello from server\\n\")\n sink.flush()\n }\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":92,"symbol":"`handshake fails`","kind":"function","lang":"kotlin","code":"@Test\n fun `handshake fails`() {\n val (clientSocket, serverSocket) = network.socketPair()\n\n val clientTls =\n FakeTls(\n handshaker =\n object : Handshaker {\n private var handshakeCount = 0\n\n override fun handshake(\n client: ClientInputs,\n server: ServerInputs,\n ): Handshaker.Result {\n assertThat(handshakeCount++).isEqualTo(0)\n val original = InsecureHandshaker().handshake(client, server)\n return Handshaker.Result.Failure(\n exception = SSLHandshakeException(\"boom!\"),\n clientHandshake = original.clientHandshake,\n serverHandshake = original.serverHandshake,\n )\n }\n },\n handshakeCertificates = TlsUtil.localhost(),\n )\n\n val clientSslSocket = clientTls.clientSocket(clientSocket)\n val serverSslSocket = serverTls.serverSocket(serverSocket)\n\n taskRunner.schedule(\"client\") {\n val e =\n assertFailsWith {\n clientSslSocket.startHandshake()\n }\n assertThat(e).hasMessage(\"boom!\")\n }\n\n val e =\n assertFailsWith {\n serverSslSocket.startHandshake()\n }\n assertThat(e).hasMessage(\"closed\")\n }\n\n val e =\n assertFailsWith {\n clientSslSocket.startHandshake()\n }\n assertThat(e).hasMessage(\"closed\")\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":150,"symbol":"handshake","kind":"function","lang":"kotlin","code":"override fun handshake(\n client: ClientInputs,\n server: ServerInputs,\n ): Handshaker.Result {\n clientSocket.close()\n return InsecureHandshaker().handshake(client, server)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":179,"symbol":"`client handshake timeout`","kind":"function","lang":"kotlin","code":"@Test\n fun `client handshake timeout`() {\n val (clientSocket, _) = network.socketPair()\n clientSocket.soTimeout = 250\n\n val clientSslSocket = clientTls.clientSocket(clientSocket)\n\n val elapsed =\n measureTime {\n assertFailsWith {\n clientSslSocket.startHandshake()\n }\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":195,"symbol":"`client handshake fails because server is closed`","kind":"function","lang":"kotlin","code":"@Test\n fun `client handshake fails because server is closed`() {\n val (clientSocket, serverSocket) = network.socketPair()\n clientSocket.soTimeout = 5_000\n\n val clientSslSocket = clientTls.clientSocket(clientSocket)\n\n taskRunner.schedule(\"close server later\", 250.milliseconds) {\n serverSocket.close()\n }\n\n val elapsed =\n measureTime {\n assertFailsWith {\n clientSslSocket.startHandshake()\n }\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":215,"symbol":"`client handshake fails because client is closed`","kind":"function","lang":"kotlin","code":"@Test\n fun `client handshake fails because client is closed`() {\n val (clientSocket, _) = network.socketPair()\n clientSocket.soTimeout = 5_000\n\n val clientSslSocket = clientTls.clientSocket(clientSocket)\n\n taskRunner.schedule(\"close client later\", 250.milliseconds) {\n clientSocket.close()\n }\n\n val elapsed =\n measureTime {\n assertFailsWith {\n clientSslSocket.startHandshake()\n }\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":235,"symbol":"`server handshake timeout`","kind":"function","lang":"kotlin","code":"@Test\n fun `server handshake timeout`() {\n val (_, serverSocket) = network.socketPair()\n serverSocket.soTimeout = 250\n\n val serverSslSocket = serverTls.clientSocket(serverSocket)\n\n val elapsed =\n measureTime {\n assertFailsWith {\n serverSslSocket.startHandshake()\n }\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":251,"symbol":"`server handshake fails because server is closed`","kind":"function","lang":"kotlin","code":"@Test\n fun `server handshake fails because server is closed`() {\n val (_, serverSocket) = network.socketPair()\n serverSocket.soTimeout = 5_000\n\n val serverSslSocket = serverTls.clientSocket(serverSocket)\n\n taskRunner.schedule(\"close server later\", 250.milliseconds) {\n serverSocket.close()\n }\n\n val elapsed =\n measureTime {\n assertFailsWith {\n serverSslSocket.startHandshake()\n }\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/sockets/FakeTlsTest.kt","line":271,"symbol":"`server handshake fails because client is closed`","kind":"function","lang":"kotlin","code":"@Test\n fun `server handshake fails because client is closed`() {\n val (clientSocket, serverSocket) = network.socketPair()\n serverSocket.soTimeout = 5_000\n\n val serverSslSocket = serverTls.clientSocket(serverSocket)\n\n taskRunner.schedule(\"close server later\", 250.milliseconds) {\n clientSocket.close()\n }\n\n val elapsed =\n measureTime {\n assertFailsWith {\n serverSslSocket.startHandshake()\n }\n }\n assertThat(elapsed).isBetween(200.milliseconds, 350.milliseconds)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/testing/PlatformRuleTest.kt","line":25,"symbol":"PlatformRuleTest","kind":"class","lang":"kotlin","doc":"Validates which environment is used by the IDE.","code":"class PlatformRuleTest {\n @RegisterExtension @JvmField\n val platform = PlatformRule()\n\n @Test\n fun testMode() {\n println(PlatformRule.getPlatformSystemProperty())\n println(Platform.get().javaClass.simpleName)\n }\n\n @Test\n fun testGreenCase() {\n }\n\n @Test\n fun testGreenCaseFailingOnLater() {\n platform.expectFailureFromJdkVersion(PlatformVersion.majorVersion + 1)\n }\n\n @Test\n fun failureCase() {\n platform.expectFailureFromJdkVersion(PlatformVersion.majorVersion)\n\n check(false)\n }\n}"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/testing/PlatformRuleTest.kt","line":29,"symbol":"testMode","kind":"function","lang":"kotlin","code":"@Test\n fun testMode() {\n println(PlatformRule.getPlatformSystemProperty())\n println(Platform.get().javaClass.simpleName)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/testing/PlatformRuleTest.kt","line":35,"symbol":"testGreenCase","kind":"function","lang":"kotlin","code":"@Test\n fun testGreenCase() {\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/testing/PlatformRuleTest.kt","line":39,"symbol":"testGreenCaseFailingOnLater","kind":"function","lang":"kotlin","code":"@Test\n fun testGreenCaseFailingOnLater() {\n platform.expectFailureFromJdkVersion(PlatformVersion.majorVersion + 1)\n }"} {"repo":"okhttp","file":"okhttp-testing-support/src/test/kotlin/okhttp3/testing/PlatformRuleTest.kt","line":44,"symbol":"failureCase","kind":"function","lang":"kotlin","code":"@Test\n fun failureCase() {\n platform.expectFailureFromJdkVersion(PlatformVersion.majorVersion)\n\n check(false)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/Certificates.kt","line":45,"symbol":"decodeCertificatePem","kind":"function","lang":"kotlin","doc":"HjAcBgNVHREBAf8EEjAQhwQBAQEBgghjYXNoLmFwcDAKBggqhkjOPQQDAgNIADBF AiAyHHg1N6YDDQiY920+cnI5XSZwEGhAtb9PYWO8bLmkcQIhAI2CfEZf3V/obmdT yyaoEufLKVXhrTQhRfodTeigi4RX -----END CERTIFICATE----- ```","code":"fun String.decodeCertificatePem(): X509Certificate {\n try {\n val certificateFactory = CertificateFactory.getInstance(\"X.509\")\n val certificates =\n certificateFactory\n .generateCertificates(\n Buffer().writeUtf8(this).inputStream(),\n )\n\n return certificates.single() as X509Certificate\n } catch (nsee: NoSuchElementException) {\n throw IllegalArgumentException(\"failed to decode certificate\", nsee)\n } catch (iae: IllegalArgumentException) {\n throw IllegalArgumentException(\"failed to decode certificate\", iae)\n } catch (e: GeneralSecurityException) {\n throw IllegalArgumentException(\"failed to decode certificate\", e)\n }\n}"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/Certificates.kt","line":69,"symbol":"certificatePem","kind":"function","lang":"kotlin","doc":"Returns the certificate encoded in [PEM format][rfc_7468]. [rfc_7468]: https://tools.ietf.org/html/rfc7468","code":"fun X509Certificate.certificatePem(): String =\n buildString {\n append(\"-----BEGIN CERTIFICATE-----\\n\")\n encodeBase64Lines(encoded.toByteString())\n append(\"-----END CERTIFICATE-----\\n\")\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/Certificates.kt","line":76,"symbol":"encodeBase64Lines","kind":"function","lang":"kotlin","code":"internal fun StringBuilder.encodeBase64Lines(data: ByteString) {\n val base64 = data.base64()\n for (i in 0 until base64.length step 64) {\n append(base64, i, minOf(i + 64, base64.length)).append('\\n')\n }\n}"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":73,"symbol":"HandshakeCertificates","kind":"class","lang":"kotlin","doc":"certificate. The root certificate is not included in this chain. * The server's handshake certificates must include a set of trusted root certificates. They will be used to authenticate the client's certificate chain. Typically this is not the same set of root certificates used in server authentication. Instead it will be a small set of roots private to an organization or service.","code":"class HandshakeCertificates private constructor(\n @get:JvmName(\"keyManager\") val keyManager: X509KeyManager,\n @get:JvmName(\"trustManager\") val trustManager: X509TrustManager,\n) {\n @JvmName(\"-deprecated_keyManager\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"keyManager\"),\n level = DeprecationLevel.ERROR,\n )\n fun keyManager(): X509KeyManager = keyManager\n\n @JvmName(\"-deprecated_trustManager\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"trustManager\"),\n level = DeprecationLevel.ERROR,\n )\n fun trustManager(): X509TrustManager = trustManager\n\n fun sslSocketFactory(): SSLSocketFactory = sslContext().socketFactory\n\n fun sslContext(): SSLContext =\n Platform.get().newSSLContext().apply {\n init(arrayOf(keyManager), arrayOf(trustManager), SecureRandom())\n }\n\n class Builder {\n private var heldCertificate: HeldCertificate? = null\n private var intermediates: Array? = null\n private val trustedCertificates = mutableListOf()\n private val insecureHosts = mutableListOf()\n\n /**\n * Configure the cert"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":77,"symbol":"keyManager","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_keyManager\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"keyManager\"),\n level = DeprecationLevel.ERROR,\n )\n fun keyManager(): X509KeyManager = keyManager"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":85,"symbol":"trustManager","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_trustManager\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"trustManager\"),\n level = DeprecationLevel.ERROR,\n )\n fun trustManager(): X509TrustManager = trustManager"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":93,"symbol":"sslSocketFactory","kind":"function","lang":"kotlin","code":"fun sslSocketFactory(): SSLSocketFactory = sslContext().socketFactory"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":95,"symbol":"sslContext","kind":"function","lang":"kotlin","code":"fun sslContext(): SSLContext =\n Platform.get().newSSLContext().apply {\n init(arrayOf(keyManager), arrayOf(trustManager), SecureRandom())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":100,"symbol":"Builder","kind":"class","lang":"kotlin","code":"class Builder {\n private var heldCertificate: HeldCertificate? = null\n private var intermediates: Array? = null\n private val trustedCertificates = mutableListOf()\n private val insecureHosts = mutableListOf()\n\n /**\n * Configure the certificate chain to use when being authenticated. The first certificate is\n * the held certificate, further certificates are included in the handshake so the peer can\n * build a trusted path to a trusted root certificate.\n *\n * The chain should include all intermediate certificates but does not need the root certificate\n * that we expect to be known by the remote peer. The peer already has that certificate so\n * transmitting it is unnecessary.\n */\n fun heldCertificate(\n heldCertificate: HeldCertificate,\n vararg intermediates: X509Certificate,\n ) = apply {\n this.heldCertificate = heldCertificate\n this.intermediates = arrayOf(*intermediates) // Defensive copy.\n }\n\n /**\n * Add a trusted root certificate to use when authenticating a peer. Peers must provide\n * a chain of certificates whose root is one of these.\n */\n fun addT"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":115,"symbol":"heldCertificate","kind":"function","lang":"kotlin","doc":"build a trusted path to a trusted root certificate. The chain should include all intermediate certificates but does not need the root certificate that we expect to be known by the remote peer. The peer already has that certificate so transmitting it is unnecessary.","code":"fun heldCertificate(\n heldCertificate: HeldCertificate,\n vararg intermediates: X509Certificate,\n ) = apply {\n this.heldCertificate = heldCertificate\n this.intermediates = arrayOf(*intermediates) // Defensive copy.\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":127,"symbol":"addTrustedCertificate","kind":"function","lang":"kotlin","doc":"Add a trusted root certificate to use when authenticating a peer. Peers must provide a chain of certificates whose root is one of these.","code":"fun addTrustedCertificate(certificate: X509Certificate) =\n apply {\n this.trustedCertificates += certificate\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":144,"symbol":"addPlatformTrustedCertificates","kind":"function","lang":"kotlin","doc":"Otherwise it is necessary to manually prepare a comprehensive set of trusted roots. If the host platform is compromised or misconfigured this may contain untrustworthy root certificates. Applications that connect to a known set of servers may be able to mitigate this problem with [certificate pinning][CertificatePinner].","code":"fun addPlatformTrustedCertificates() =\n apply {\n val platformTrustManager = Platform.get().platformTrustManager()\n Collections.addAll(trustedCertificates, *platformTrustManager.acceptedIssuers)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":173,"symbol":"addInsecureHost","kind":"function","lang":"kotlin","doc":"**This feature is not supported on Android API levels less than 24.** Prior releases lacked a mechanism to trust some hosts and not others. @param hostname the exact hostname from the URL for insecure connections.","code":"fun addInsecureHost(hostname: String) =\n apply {\n insecureHosts += hostname\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HandshakeCertificates.kt","line":178,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): HandshakeCertificates {\n val immutableInsecureHosts = insecureHosts.toImmutableList()\n\n val heldCertificate = heldCertificate\n if (heldCertificate != null && heldCertificate.keyPair.private.format == null) {\n throw KeyStoreException(\"unable to support unencodable private key\")\n }\n\n val keyManager = newKeyManager(null, heldCertificate, *(intermediates ?: emptyArray()))\n val trustManager = newTrustManager(null, trustedCertificates, immutableInsecureHosts)\n return HandshakeCertificates(keyManager, trustManager)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":128,"symbol":"HeldCertificate","kind":"class","lang":"kotlin","doc":"is used to verify the signature of the \"www.squareup.com\" certificate. This roles are reversed for client authentication. In that case the client has a private key and a chain of certificates. The server uses a set of trusted root certificates to authenticate the client. Subject alternative names are not used for client authentication.","code":"@Suppress(\"DEPRECATION\")\nclass HeldCertificate(\n @get:JvmName(\"keyPair\") val keyPair: KeyPair,\n @get:JvmName(\"certificate\") val certificate: X509Certificate,\n) {\n @JvmName(\"-deprecated_certificate\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"certificate\"),\n level = DeprecationLevel.ERROR,\n )\n fun certificate(): X509Certificate = certificate\n\n @JvmName(\"-deprecated_keyPair\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"keyPair\"),\n level = DeprecationLevel.ERROR,\n )\n fun keyPair(): KeyPair = keyPair\n\n /**\n * Returns the certificate encoded in [PEM format][rfc_7468].\n *\n * [rfc_7468]: https://tools.ietf.org/html/rfc7468\n */\n fun certificatePem(): String = certificate.certificatePem()\n\n /**\n * Returns the private key encoded in [PKCS #8][rfc_5208] [PEM format][rfc_7468].\n *\n * [rfc_5208]: https://tools.ietf.org/html/rfc5208\n * [rfc_7468]: https://tools.ietf.org/html/rfc7468\n */\n fun privateKeyPkcs8Pem(): String =\n buildString {\n append(\"-----BEGIN PRIVATE KEY-----\\n\")\n encodeBase64Lines(keyPair.private.encoded.toByteString())\n append(\"-----END "} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":133,"symbol":"certificate","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_certificate\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"certificate\"),\n level = DeprecationLevel.ERROR,\n )\n fun certificate(): X509Certificate = certificate"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":141,"symbol":"keyPair","kind":"function","lang":"kotlin","code":"@JvmName(\"-deprecated_keyPair\")\n @Deprecated(\n message = \"moved to val\",\n replaceWith = ReplaceWith(expression = \"keyPair\"),\n level = DeprecationLevel.ERROR,\n )\n fun keyPair(): KeyPair = keyPair"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":154,"symbol":"certificatePem","kind":"function","lang":"kotlin","doc":"Returns the certificate encoded in [PEM format][rfc_7468]. [rfc_7468]: https://tools.ietf.org/html/rfc7468","code":"fun certificatePem(): String = certificate.certificatePem()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":162,"symbol":"privateKeyPkcs8Pem","kind":"function","lang":"kotlin","doc":"Returns the private key encoded in [PKCS #8][rfc_5208] [PEM format][rfc_7468]. [rfc_5208]: https://tools.ietf.org/html/rfc5208 [rfc_7468]: https://tools.ietf.org/html/rfc7468","code":"fun privateKeyPkcs8Pem(): String =\n buildString {\n append(\"-----BEGIN PRIVATE KEY-----\\n\")\n encodeBase64Lines(keyPair.private.encoded.toByteString())\n append(\"-----END PRIVATE KEY-----\\n\")\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":175,"symbol":"privateKeyPkcs1Pem","kind":"function","lang":"kotlin","doc":"Returns the RSA private key encoded in [PKCS #1][rfc_8017] [PEM format][rfc_7468]. [rfc_8017]: https://tools.ietf.org/html/rfc8017 [rfc_7468]: https://tools.ietf.org/html/rfc7468","code":"fun privateKeyPkcs1Pem(): String {\n check(keyPair.private is RSAPrivateKey) { \"PKCS1 only supports RSA keys\" }\n return buildString {\n append(\"-----BEGIN RSA PRIVATE KEY-----\\n\")\n encodeBase64Lines(pkcs1Bytes())\n append(\"-----END RSA PRIVATE KEY-----\\n\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":184,"symbol":"pkcs1Bytes","kind":"function","lang":"kotlin","code":"private fun pkcs1Bytes(): ByteString {\n val decoded = CertificateAdapters.privateKeyInfo.fromDer(keyPair.private.encoded.toByteString())\n return decoded.privateKey\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":190,"symbol":"Builder","kind":"class","lang":"kotlin","doc":"Build a held certificate with reasonable defaults.","code":"class Builder {\n private var notBefore = -1L\n private var notAfter = -1L\n private var commonName: String? = null\n private var organizationalUnit: String? = null\n private val altNames = mutableListOf()\n private var serialNumber: BigInteger? = null\n private var keyPair: KeyPair? = null\n private var signedBy: HeldCertificate? = null\n private var maxIntermediateCas = -1\n private var keyAlgorithm: String? = null\n private var keySize: Int = 0\n\n init {\n ecdsa256()\n }\n\n /**\n * Sets the certificate to be valid in ```[notBefore..notAfter]```. Both endpoints are specified\n * in the format of [System.currentTimeMillis]. Specify -1L for both values to use the default\n * interval, 24 hours starting when the certificate is created.\n */\n fun validityInterval(\n notBefore: Long,\n notAfter: Long,\n ) = apply {\n require(notBefore <= notAfter && notBefore == -1L == (notAfter == -1L)) {\n \"invalid interval: $notBefore..$notAfter\"\n }\n this.notBefore = notBefore\n this.notAfter = notAfter\n }\n\n /**\n * Sets the certificate to be valid immediately and until the specified duration has elaps"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":212,"symbol":"validityInterval","kind":"function","lang":"kotlin","doc":"Sets the certificate to be valid in ```[notBefore..notAfter]```. Both endpoints are specified in the format of [System.currentTimeMillis]. Specify -1L for both values to use the default interval, 24 hours starting when the certificate is created.","code":"fun validityInterval(\n notBefore: Long,\n notAfter: Long,\n ) = apply {\n require(notBefore <= notAfter && notBefore == -1L == (notAfter == -1L)) {\n \"invalid interval: $notBefore..$notAfter\"\n }\n this.notBefore = notBefore\n this.notAfter = notAfter\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":227,"symbol":"duration","kind":"function","lang":"kotlin","doc":"Sets the certificate to be valid immediately and until the specified duration has elapsed. The precision of this field is seconds; further precision will be truncated.","code":"fun duration(\n duration: Long,\n unit: TimeUnit,\n ) = apply {\n val now = System.currentTimeMillis()\n validityInterval(now, now + unit.toMillis(duration))\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":240,"symbol":"addSubjectAlternativeName","kind":"function","lang":"kotlin","doc":"Adds a subject alternative name (SAN) to the certificate. This is usually a literal hostname, a literal IP address, or a hostname pattern. If no subject alternative names are added that extension will be omitted.","code":"fun addSubjectAlternativeName(altName: String) =\n apply {\n altNames += altName\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":252,"symbol":"commonName","kind":"function","lang":"kotlin","doc":"Set this certificate's common name (CN). Historically this held the hostname of TLS certificate, but that practice was deprecated by [RFC 2818][rfc_2818] and replaced with [addSubjectAlternativeName]. If unset a random string will be used. [rfc_2818]: https://tools.ietf.org/html/rfc2818","code":"fun commonName(cn: String) =\n apply {\n this.commonName = cn\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":258,"symbol":"organizationalUnit","kind":"function","lang":"kotlin","doc":"Sets the certificate's organizational unit (OU). If unset this field will be omitted.","code":"fun organizationalUnit(ou: String) =\n apply {\n this.organizationalUnit = ou\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":264,"symbol":"serialNumber","kind":"function","lang":"kotlin","doc":"Sets this certificate's serial number. If unset the serial number will be 1.","code":"fun serialNumber(serialNumber: BigInteger) =\n apply {\n this.serialNumber = serialNumber\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":270,"symbol":"serialNumber","kind":"function","lang":"kotlin","doc":"Sets this certificate's serial number. If unset the serial number will be 1.","code":"fun serialNumber(serialNumber: Long) =\n apply {\n serialNumber(BigInteger.valueOf(serialNumber))\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":279,"symbol":"keyPair","kind":"function","lang":"kotlin","doc":"Sets the public/private key pair used for this certificate. If unset a key pair will be generated.","code":"fun keyPair(keyPair: KeyPair) =\n apply {\n this.keyPair = keyPair\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":288,"symbol":"keyPair","kind":"function","lang":"kotlin","doc":"Sets the public/private key pair used for this certificate. If unset a key pair will be generated.","code":"fun keyPair(\n publicKey: PublicKey,\n privateKey: PrivateKey,\n ) = apply {\n keyPair(KeyPair(publicKey, privateKey))\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":299,"symbol":"signedBy","kind":"function","lang":"kotlin","doc":"Set the certificate that will issue this certificate. If unset the certificate will be self-signed.","code":"fun signedBy(signedBy: HeldCertificate?) =\n apply {\n this.signedBy = signedBy\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":313,"symbol":"certificateAuthority","kind":"function","lang":"kotlin","doc":"By default this certificate cannot not sign other certificates. Set this to 0 so this certificate can sign other certificates (but those certificates cannot themselves sign certificates). Set this to 1 so this certificate can sign intermediate certificates that can themselves sign certificates. Add one for each additional layer of intermediates to permit.","code":"fun certificateAuthority(maxIntermediateCas: Int) =\n apply {\n require(maxIntermediateCas >= 0) {\n \"maxIntermediateCas < 0: $maxIntermediateCas\"\n }\n this.maxIntermediateCas = maxIntermediateCas\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":328,"symbol":"ecdsa256","kind":"function","lang":"kotlin","doc":"Configure the certificate to generate a 256-bit ECDSA key, which provides about 128 bits of security. ECDSA keys are noticeably faster than RSA keys. This is the default configuration and has been since this API was introduced in OkHttp 3.11.0. Note that the default may change in future releases.","code":"fun ecdsa256() =\n apply {\n keyAlgorithm = \"EC\"\n keySize = 256\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":338,"symbol":"rsa2048","kind":"function","lang":"kotlin","doc":"Configure the certificate to generate a 2048-bit RSA key, which provides about 112 bits of security. RSA keys are interoperable with very old clients that don't support ECDSA.","code":"fun rsa2048() =\n apply {\n keyAlgorithm = \"RSA\"\n keySize = 2048\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":344,"symbol":"build","kind":"function","lang":"kotlin","code":"fun build(): HeldCertificate {\n // Subject keys & identity.\n val subjectKeyPair = keyPair ?: generateKeyPair()\n val subjectPublicKeyInfo =\n CertificateAdapters.subjectPublicKeyInfo.fromDer(\n subjectKeyPair.public.encoded.toByteString(),\n )\n val subject: List> = subject()\n\n // Issuer/signer keys & identity. May be the subject if it is self-signed.\n val issuerKeyPair: KeyPair\n val issuer: List>\n if (signedBy != null) {\n issuerKeyPair = signedBy!!.keyPair\n issuer =\n CertificateAdapters.rdnSequence.fromDer(\n signedBy!!\n .certificate.subjectX500Principal.encoded\n .toByteString(),\n )\n } else {\n issuerKeyPair = subjectKeyPair\n issuer = subject\n }\n val signatureAlgorithm = signatureAlgorithm(issuerKeyPair)\n\n // Subset of certificate data that's covered by the signature.\n val tbsCertificate =\n TbsCertificate(\n // v3:\n version = 2L,\n serialNumber = serialNumber ?: BigInteger.ONE,\n signature = signatureAlgorithm,\n issu"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":409,"symbol":"subject","kind":"function","lang":"kotlin","code":"private fun subject(): List> {\n val result = mutableListOf>()\n\n if (organizationalUnit != null) {\n result +=\n listOf(\n AttributeTypeAndValue(\n type = ORGANIZATIONAL_UNIT_NAME,\n value = organizationalUnit,\n ),\n )\n }\n\n result +=\n listOf(\n AttributeTypeAndValue(\n type = ObjectIdentifiers.COMMON_NAME,\n value = commonName ?: UUID.randomUUID().toString(),\n ),\n )\n\n return result\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":433,"symbol":"validity","kind":"function","lang":"kotlin","code":"private fun validity(): Validity {\n val notBefore = if (notBefore != -1L) notBefore else System.currentTimeMillis()\n val notAfter = if (notAfter != -1L) notAfter else notBefore + DEFAULT_DURATION_MILLIS\n return Validity(\n notBefore = notBefore,\n notAfter = notAfter,\n )\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":442,"symbol":"extensions","kind":"function","lang":"kotlin","code":"private fun extensions(): MutableList {\n val result = mutableListOf()\n\n if (maxIntermediateCas != -1) {\n result +=\n Extension(\n id = BASIC_CONSTRAINTS,\n critical = true,\n value =\n BasicConstraints(\n ca = true,\n maxIntermediateCas = maxIntermediateCas.toLong(),\n ),\n )\n }\n\n if (altNames.isNotEmpty()) {\n val extensionValue =\n altNames.map {\n when {\n it.canParseAsIpAddress() -> {\n generalNameIpAddress to InetAddress.getByName(it).address.toByteString()\n }\n\n else -> {\n generalNameDnsName to it\n }\n }\n }\n result +=\n Extension(\n id = SUBJECT_ALTERNATIVE_NAME,\n critical = true,\n value = extensionValue,\n )\n }\n\n return result\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":482,"symbol":"signatureAlgorithm","kind":"function","lang":"kotlin","code":"private fun signatureAlgorithm(signedByKeyPair: KeyPair): AlgorithmIdentifier =\n when (signedByKeyPair.private) {\n is RSAPrivateKey -> {\n AlgorithmIdentifier(\n algorithm = SHA256_WITH_RSA_ENCRYPTION,\n parameters = null,\n )\n }\n\n else -> {\n AlgorithmIdentifier(\n algorithm = SHA256_WITH_ECDSA,\n parameters = ByteString.EMPTY,\n )\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":499,"symbol":"generateKeyPair","kind":"function","lang":"kotlin","code":"private fun generateKeyPair(): KeyPair =\n KeyPairGenerator.getInstance(keyAlgorithm).run {\n initialize(keySize, SecureRandom())\n generateKeyPair()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":545,"symbol":"decode","kind":"function","lang":"kotlin","doc":"Encode a held certificate into this format by concatenating the results of [certificatePem()][certificatePem] and [privateKeyPkcs8Pem()][privateKeyPkcs8Pem]. [rfc_7468]: https://tools.ietf.org/html/rfc7468 [rfc_5208]: https://tools.ietf.org/html/rfc5208","code":"@JvmStatic\n fun decode(certificateAndPrivateKeyPem: String): HeldCertificate {\n var certificatePem: String? = null\n var pkcs8Base64: String? = null\n for (match in PEM_REGEX.findAll(certificateAndPrivateKeyPem)) {\n when (val label = match.groups[1]!!.value) {\n \"CERTIFICATE\" -> {\n require(certificatePem == null) { \"string includes multiple certificates\" }\n certificatePem = match.groups[0]!!.value // Keep --BEGIN-- and --END-- for certificates.\n }\n\n \"PRIVATE KEY\" -> {\n require(pkcs8Base64 == null) { \"string includes multiple private keys\" }\n pkcs8Base64 = match.groups[2]!!.value // Include the contents only for PKCS8.\n }\n\n else -> {\n throw IllegalArgumentException(\"unexpected type: $label\")\n }\n }\n }\n require(certificatePem != null) { \"string does not include a certificate\" }\n require(pkcs8Base64 != null) { \"string does not include a private key\" }\n\n return decode(certificatePem, pkcs8Base64)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":572,"symbol":"decode","kind":"function","lang":"kotlin","code":"private fun decode(\n certificatePem: String,\n pkcs8Base64Text: String,\n ): HeldCertificate {\n val certificate = certificatePem.decodeCertificatePem()\n\n val pkcs8Bytes =\n pkcs8Base64Text.decodeBase64()\n ?: throw IllegalArgumentException(\"failed to decode private key\")\n\n // The private key doesn't tell us its type but it's okay because the certificate knows!\n val keyType =\n when (certificate.publicKey) {\n is ECPublicKey -> \"EC\"\n is RSAPublicKey -> \"RSA\"\n else -> throw IllegalArgumentException(\"unexpected key type: ${certificate.publicKey}\")\n }\n\n val privateKey = decodePkcs8(pkcs8Bytes, keyType)\n\n val keyPair = KeyPair(certificate.publicKey, privateKey)\n return HeldCertificate(keyPair, certificate)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt","line":596,"symbol":"decodePkcs8","kind":"function","lang":"kotlin","code":"private fun decodePkcs8(\n data: ByteString,\n keyAlgorithm: String,\n ): PrivateKey {\n try {\n val keyFactory = KeyFactory.getInstance(keyAlgorithm)\n return keyFactory.generatePrivate(PKCS8EncodedKeySpec(data.toByteArray()))\n } catch (e: GeneralSecurityException) {\n throw IllegalArgumentException(\"failed to decode private key\", e)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureAndroidTrustManager.kt","line":26,"symbol":"InsecureAndroidTrustManager","kind":"class","lang":"kotlin","doc":"This extends [X509TrustManager] for Android to disable verification for a set of hosts.","code":"internal class InsecureAndroidTrustManager(\n private val delegate: X509TrustManager,\n private val insecureHosts: List,\n) : X509TrustManager {\n private val checkServerTrustedMethod: Method? =\n try {\n delegate::class.java.getMethod(\n \"checkServerTrusted\",\n Array::class.java,\n String::class.java,\n String::class.java,\n )\n } catch (_: NoSuchMethodException) {\n null\n }\n\n /** Android method to clean and sort certificates, called via reflection. */\n @Suppress(\"unused\", \"UNCHECKED_CAST\")\n fun checkServerTrusted(\n chain: Array,\n authType: String,\n host: String,\n ): List {\n if (host in insecureHosts) return listOf()\n try {\n val method =\n checkServerTrustedMethod\n ?: throw CertificateException(\"Failed to call checkServerTrusted\")\n return method.invoke(delegate, chain, authType, host) as List\n } catch (e: InvocationTargetException) {\n throw e.targetException\n }\n }\n\n override fun getAcceptedIssuers(): Array = delegate.acceptedIssuers\n\n override fun checkClientTrusted(\n chain: Array,\n authType: String,\n host: String,\n ): List {\n if (host in insecureHosts) return listOf()\n try {\n val method =\n checkServerTrustedMethod\n ?: throw CertificateException(\"Failed to call checkServerTrusted\")\n return method.invoke(delegate, chain, authType, host) as List\n } catch (e: InvocationTargetException) {\n throw e.targetException\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureAndroidTrustManager.kt","line":60,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = delegate.acceptedIssuers"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureAndroidTrustManager.kt","line":62,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n chain: Array,\n authType: String?,\n ) = throw CertificateException(\"Unsupported operation\")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureAndroidTrustManager.kt","line":67,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n chain: Array,\n authType: String,\n ) = throw CertificateException(\"Unsupported operation\")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":33,"symbol":"InsecureExtendedTrustManager","kind":"class","lang":"kotlin","doc":"This extends [X509ExtendedTrustManager] to disable verification for a set of hosts. Note that the superclass [X509ExtendedTrustManager] isn't available on Android until version 7 (API level 24).","code":"@IgnoreJRERequirement\ninternal class InsecureExtendedTrustManager(\n private val delegate: X509ExtendedTrustManager,\n private val insecureHosts: List,\n) : X509ExtendedTrustManager() {\n override fun getAcceptedIssuers(): Array = delegate.acceptedIssuers\n\n override fun checkServerTrusted(\n chain: Array,\n authType: String,\n socket: Socket,\n ) {\n if (socket.peerName() !in insecureHosts) {\n delegate.checkServerTrusted(chain, authType, socket)\n }\n }\n\n override fun checkServerTrusted(\n chain: Array,\n authType: String,\n engine: SSLEngine,\n ) {\n if (engine.peerHost !in insecureHosts) {\n delegate.checkServerTrusted(chain, authType, engine)\n }\n }\n\n override fun checkServerTrusted(\n chain: Array,\n authType: String,\n ) = throw CertificateException(\"Unsupported operation\")\n\n override fun checkClientTrusted(\n chain: Array,\n authType: String?,\n ) = throw CertificateException(\"Unsupported operation\")\n\n override fun checkClientTrusted(\n chain: Array,\n authType: String,\n engine: SSLEngine?,\n ) = thr"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":38,"symbol":"getAcceptedIssuers","kind":"function","lang":"kotlin","code":"override fun getAcceptedIssuers(): Array = delegate.acceptedIssuers"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":40,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n chain: Array,\n authType: String,\n socket: Socket,\n ) {\n if (socket.peerName() !in insecureHosts) {\n delegate.checkServerTrusted(chain, authType, socket)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":50,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n chain: Array,\n authType: String,\n engine: SSLEngine,\n ) {\n if (engine.peerHost !in insecureHosts) {\n delegate.checkServerTrusted(chain, authType, engine)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":60,"symbol":"checkServerTrusted","kind":"function","lang":"kotlin","code":"override fun checkServerTrusted(\n chain: Array,\n authType: String,\n ) = throw CertificateException(\"Unsupported operation\")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":65,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n chain: Array,\n authType: String?,\n ) = throw CertificateException(\"Unsupported operation\")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":70,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n chain: Array,\n authType: String,\n engine: SSLEngine?,\n ) = throw CertificateException(\"Unsupported operation\")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":76,"symbol":"checkClientTrusted","kind":"function","lang":"kotlin","code":"override fun checkClientTrusted(\n chain: Array,\n authType: String,\n socket: Socket?,\n ) = throw CertificateException(\"Unsupported operation\")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/InsecureExtendedTrustManager.kt","line":82,"symbol":"peerName","kind":"function","lang":"kotlin","code":"private fun Socket.peerName(): String {\n val address = remoteSocketAddress\n return if (address is InetSocketAddress) address.hostName else address.toString()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/TlsUtil.kt","line":32,"symbol":"TlsUtil","kind":"object","lang":"kotlin","code":"object TlsUtil {\n val password = \"password\".toCharArray()\n\n private val localhost: HandshakeCertificates by lazy {\n // Generate a self-signed cert for the server to serve and the client to trust.\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"localhost\")\n .addSubjectAlternativeName(\"localhost\")\n .addSubjectAlternativeName(\"localhost.localdomain\")\n .build()\n return@lazy HandshakeCertificates\n .Builder()\n .heldCertificate(heldCertificate)\n .addTrustedCertificate(heldCertificate.certificate)\n .build()\n }\n\n /** Returns an SSL client for this host's localhost address. */\n @JvmStatic\n fun localhost(): HandshakeCertificates = localhost\n\n /** Returns a trust manager that trusts `trustedCertificates`. */\n @JvmStatic @IgnoreJRERequirement\n fun newTrustManager(\n keyStoreType: String?,\n trustedCertificates: List,\n insecureHosts: List,\n ): X509TrustManager {\n val trustStore = newEmptyKeyStore(keyStoreType)\n for (i in trustedCertificates.indices) {\n trustStore.setCertificateEntry(\"cert_$i\", trustedCertificates[i])\n }\n\n val factory = TrustManagerFact"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/TlsUtil.kt","line":52,"symbol":"localhost","kind":"function","lang":"kotlin","doc":"Returns an SSL client for this host's localhost address.","code":"@JvmStatic\n fun localhost(): HandshakeCertificates = localhost"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/TlsUtil.kt","line":56,"symbol":"newTrustManager","kind":"function","lang":"kotlin","doc":"Returns a trust manager that trusts `trustedCertificates`.","code":"@JvmStatic @IgnoreJRERequirement\n fun newTrustManager(\n keyStoreType: String?,\n trustedCertificates: List,\n insecureHosts: List,\n ): X509TrustManager {\n val trustStore = newEmptyKeyStore(keyStoreType)\n for (i in trustedCertificates.indices) {\n trustStore.setCertificateEntry(\"cert_$i\", trustedCertificates[i])\n }\n\n val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())\n factory.init(trustStore)\n val result = factory.trustManagers!!\n check(result.size == 1 && result[0] is X509TrustManager) {\n \"Unexpected trust managers: ${result.contentToString()}\"\n }\n\n val trustManager = result[0] as X509TrustManager\n\n return when {\n insecureHosts.isEmpty() -> trustManager\n Platform.isAndroid -> InsecureAndroidTrustManager(trustManager, insecureHosts)\n else -> InsecureExtendedTrustManager(trustManager as X509ExtendedTrustManager, insecureHosts)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/TlsUtil.kt","line":87,"symbol":"newKeyManager","kind":"function","lang":"kotlin","doc":"Returns a key manager for the held certificate and its chain. Returns an empty key manager if `heldCertificate` is null.","code":"@JvmStatic\n fun newKeyManager(\n keyStoreType: String?,\n heldCertificate: HeldCertificate?,\n vararg intermediates: X509Certificate,\n ): X509KeyManager {\n val keyStore = newEmptyKeyStore(keyStoreType)\n if (heldCertificate != null) {\n val chain = arrayOfNulls(1 + intermediates.size)\n chain[0] = heldCertificate.certificate\n intermediates.copyInto(chain, 1)\n keyStore.setKeyEntry(\"private\", heldCertificate.keyPair.private, password, chain)\n }\n\n // https://github.com/bcgit/bc-java/issues/1160\n val isBouncyCastle = keyStore.provider.name == \"BC\"\n val algorithm = if (isBouncyCastle) \"PKIX\" else KeyManagerFactory.getDefaultAlgorithm()\n\n val factory = KeyManagerFactory.getInstance(algorithm)\n factory.init(keyStore, password)\n val result = factory.keyManagers!!\n check(result.size == 1 && result[0] is X509KeyManager) {\n \"Unexpected key managers:${result.contentToString()}\"\n }\n\n return result[0] as X509KeyManager\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/TlsUtil.kt","line":115,"symbol":"newEmptyKeyStore","kind":"function","lang":"kotlin","code":"private fun newEmptyKeyStore(keyStoreType: String?): KeyStore =\n KeyStore.getInstance(keyStoreType ?: KeyStore.getDefaultType()).apply {\n val inputStream: InputStream? = null // By convention, 'null' creates an empty key store.\n load(inputStream, password)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":30,"symbol":"Adapters","kind":"object","lang":"kotlin","doc":"Built-in adapters for reading standard ASN.1 types.","code":"internal object Adapters {\n val BOOLEAN =\n BasicDerAdapter(\n name = \"BOOLEAN\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 1L,\n codec =\n object : BasicDerAdapter.Codec {\n override fun decode(reader: DerReader): Boolean = reader.readBoolean()\n\n override fun encode(\n writer: DerWriter,\n value: Boolean,\n ) = writer.writeBoolean(value)\n },\n )\n\n val INTEGER_AS_LONG =\n BasicDerAdapter(\n name = \"INTEGER\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 2L,\n codec =\n object : BasicDerAdapter.Codec {\n override fun decode(reader: DerReader): Long = reader.readLong()\n\n override fun encode(\n writer: DerWriter,\n value: Long,\n ) = writer.writeLong(value)\n },\n )\n\n val INTEGER_AS_BIG_INTEGER =\n BasicDerAdapter(\n name = \"INTEGER\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 2L,\n codec =\n object : BasicDerAdapter.Codec {\n override fun decode(reader: DerReader): BigInteger = reader.readBigInteger()\n\n override fun encode(\n wr"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":38,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): Boolean = reader.readBoolean()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":40,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: Boolean,\n ) = writer.writeBoolean(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":54,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): Long = reader.readLong()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":56,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: Long,\n ) = writer.writeLong(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":70,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): BigInteger = reader.readBigInteger()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":72,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: BigInteger,\n ) = writer.writeBigInteger(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":86,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): BitString = reader.readBitString()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":88,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: BitString,\n ) = writer.writeBitString(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":102,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): ByteString = reader.readOctetString()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":104,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: ByteString,\n ) = writer.writeOctetString(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":118,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): Unit? = null"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":120,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: Unit?,\n ) {\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":135,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): String = reader.readObjectIdentifier()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":137,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: String,\n ) = writer.writeObjectIdentifier(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":151,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): String = reader.readUtf8String()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":153,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: String,\n ) = writer.writeUtf8(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":176,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): String = reader.readUtf8String()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":178,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: String,\n ) = writer.writeUtf8(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":198,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): String = reader.readUtf8String()"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":200,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: String,\n ) = writer.writeUtf8(value)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":218,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): Long {\n val string = reader.readUtf8String()\n return parseUtcTime(string)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":223,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: Long,\n ) {\n val string = formatUtcTime(value)\n return writer.writeUtf8(string)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":233,"symbol":"parseUtcTime","kind":"function","lang":"kotlin","code":"internal fun parseUtcTime(string: String): Long {\n val utc = TimeZone.getTimeZone(\"GMT\")\n val dateFormat =\n SimpleDateFormat(\"yyMMddHHmmss'Z'\").apply {\n timeZone = utc\n set2DigitYearStart(Date(-631152000000L)) // 1950-01-01T00:00:00Z.\n }\n\n try {\n val parsed = dateFormat.parse(string)\n return parsed.time\n } catch (e: ParseException) {\n throw ProtocolException(\"Failed to parse UTCTime $string\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":249,"symbol":"formatUtcTime","kind":"function","lang":"kotlin","code":"internal fun formatUtcTime(date: Long): String {\n val utc = TimeZone.getTimeZone(\"GMT\")\n val dateFormat =\n SimpleDateFormat(\"yyMMddHHmmss'Z'\").apply {\n timeZone = utc\n set2DigitYearStart(Date(-631152000000L)) // 1950-01-01T00:00:00Z.\n }\n\n return dateFormat.format(date)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":271,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): Long {\n val string = reader.readUtf8String()\n return parseGeneralizedTime(string)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":276,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: Long,\n ) {\n val string = formatGeneralizedTime(value)\n return writer.writeUtf8(string)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":289,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(header: DerHeader): Boolean = true"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":291,"symbol":"fromDer","kind":"function","lang":"kotlin","code":"override fun fromDer(reader: DerReader): AnyValue {\n reader.read(\"ANY\") { header ->\n val bytes = reader.readUnknown()\n return AnyValue(\n tagClass = header.tagClass,\n tag = header.tag,\n constructed = header.constructed,\n length = header.length,\n bytes = bytes,\n )\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":304,"symbol":"toDer","kind":"function","lang":"kotlin","code":"override fun toDer(\n writer: DerWriter,\n value: AnyValue,\n ) {\n writer.write(\"ANY\", value.tagClass, value.tag) {\n writer.writeOctetString(value.bytes)\n writer.constructed = value.constructed\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":315,"symbol":"parseGeneralizedTime","kind":"function","lang":"kotlin","code":"internal fun parseGeneralizedTime(string: String): Long {\n val utc = TimeZone.getTimeZone(\"GMT\")\n val dateFormat =\n SimpleDateFormat(\"yyyyMMddHHmmss'Z'\").apply {\n timeZone = utc\n }\n\n try {\n val parsed = dateFormat.parse(string)\n return parsed.time\n } catch (e: ParseException) {\n throw ProtocolException(\"Failed to parse GeneralizedTime $string\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":330,"symbol":"formatGeneralizedTime","kind":"function","lang":"kotlin","code":"internal fun formatGeneralizedTime(date: Long): String {\n val utc = TimeZone.getTimeZone(\"GMT\")\n val dateFormat =\n SimpleDateFormat(\"yyyyMMddHHmmss'Z'\").apply {\n timeZone = utc\n }\n\n return dateFormat.format(date)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":350,"symbol":"sequence","kind":"function","lang":"kotlin","doc":"The fields are specified as a list of member adapters. When decoding, a value for each non-optional member but be included in sequence. TODO: for sets, sort by tag when encoding. TODO: for set ofs, sort by encoded value when encoding.","code":"fun sequence(\n name: String,\n vararg members: DerAdapter<*>,\n decompose: (T) -> List<*>,\n construct: (List<*>) -> T,\n ): BasicDerAdapter {\n val codec =\n object : BasicDerAdapter.Codec {\n override fun decode(reader: DerReader): T {\n return reader.withTypeHint {\n val list = mutableListOf()\n\n while (list.size < members.size) {\n val member = members[list.size]\n list += member.fromDer(reader)\n }\n\n if (reader.hasNext()) {\n throw ProtocolException(\"unexpected ${reader.peekHeader()} at $reader\")\n }\n\n return@withTypeHint construct(list)\n }\n }\n\n override fun encode(\n writer: DerWriter,\n value: T,\n ) {\n val list = decompose(value)\n writer.withTypeHint {\n for (i in list.indices) {\n val adapter = members[i] as DerAdapter\n adapter.toDer(writer, list[i])\n }\n }\n }\n }\n\n return BasicDerAdapter(\n name = name,\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 16L,\n codec = codec,\n )"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":358,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): T {\n return reader.withTypeHint {\n val list = mutableListOf()\n\n while (list.size < members.size) {\n val member = members[list.size]\n list += member.fromDer(reader)\n }\n\n if (reader.hasNext()) {\n throw ProtocolException(\"unexpected ${reader.peekHeader()} at $reader\")\n }\n\n return@withTypeHint construct(list)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":375,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: T,\n ) {\n val list = decompose(value)\n writer.withTypeHint {\n for (i in list.indices) {\n val adapter = members[i] as DerAdapter\n adapter.toDer(writer, list[i])\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":398,"symbol":"choice","kind":"function","lang":"kotlin","doc":"Returns an adapter that decodes as the first of a list of available types.","code":"fun choice(vararg choices: DerAdapter<*>): DerAdapter, Any?>> {\n return object : DerAdapter, Any?>> {\n override fun matches(header: DerHeader): Boolean = true\n\n override fun fromDer(reader: DerReader): Pair, Any?> {\n val peekedHeader =\n reader.peekHeader()\n ?: throw ProtocolException(\"expected a value at $reader\")\n\n val choice =\n choices.firstOrNull { it.matches(peekedHeader) }\n ?: throw ProtocolException(\n \"expected a matching choice but was $peekedHeader at $reader\",\n )\n\n return choice to choice.fromDer(reader)\n }\n\n override fun toDer(\n writer: DerWriter,\n value: Pair, Any?>,\n ) {\n val (adapter, v) = value\n (adapter as DerAdapter).toDer(writer, v)\n }\n\n override fun toString(): String = choices.joinToString(separator = \" OR \")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":400,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(header: DerHeader): Boolean = true"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":402,"symbol":"fromDer","kind":"function","lang":"kotlin","code":"override fun fromDer(reader: DerReader): Pair, Any?> {\n val peekedHeader =\n reader.peekHeader()\n ?: throw ProtocolException(\"expected a value at $reader\")\n\n val choice =\n choices.firstOrNull { it.matches(peekedHeader) }\n ?: throw ProtocolException(\n \"expected a matching choice but was $peekedHeader at $reader\",\n )\n\n return choice to choice.fromDer(reader)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":416,"symbol":"toDer","kind":"function","lang":"kotlin","code":"override fun toDer(\n writer: DerWriter,\n value: Pair, Any?>,\n ) {\n val (adapter, v) = value\n (adapter as DerAdapter).toDer(writer, v)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":424,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = choices.joinToString(separator = \" OR \")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":437,"symbol":"usingTypeHint","kind":"function","lang":"kotlin","doc":"If the hint is unknown [chooser] should return null which will cause the value to be decoded as an opaque byte string. This may optionally wrap the contents in a tag.","code":"fun usingTypeHint(chooser: (Any?) -> DerAdapter<*>?): DerAdapter {\n return object : DerAdapter {\n override fun matches(header: DerHeader): Boolean = true\n\n override fun toDer(\n writer: DerWriter,\n value: Any?,\n ) {\n // If we don't understand this hint, encode the body as a byte string. The byte string\n // will include a tag and length header as a prefix.\n val adapter = chooser(writer.typeHint) as DerAdapter?\n when {\n adapter != null -> adapter.toDer(writer, value)\n else -> writer.writeOctetString(value as ByteString)\n }\n }\n\n override fun fromDer(reader: DerReader): Any? {\n val adapter = chooser(reader.typeHint) as DerAdapter?\n return when {\n adapter != null -> adapter.fromDer(reader)\n else -> reader.readUnknown()\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":439,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(header: DerHeader): Boolean = true"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":441,"symbol":"toDer","kind":"function","lang":"kotlin","code":"override fun toDer(\n writer: DerWriter,\n value: Any?,\n ) {\n // If we don't understand this hint, encode the body as a byte string. The byte string\n // will include a tag and length header as a prefix.\n val adapter = chooser(writer.typeHint) as DerAdapter?\n when {\n adapter != null -> adapter.toDer(writer, value)\n else -> writer.writeOctetString(value as ByteString)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":454,"symbol":"fromDer","kind":"function","lang":"kotlin","code":"override fun fromDer(reader: DerReader): Any? {\n val adapter = chooser(reader.typeHint) as DerAdapter?\n return when {\n adapter != null -> adapter.fromDer(reader)\n else -> reader.readUnknown()\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":485,"symbol":"any","kind":"function","lang":"kotlin","code":"fun any(\n vararg choices: Pair, DerAdapter<*>> = defaultAnyChoices.toTypedArray(),\n isOptional: Boolean = false,\n optionalValue: Any? = null,\n ): DerAdapter {\n return object : DerAdapter {\n override fun matches(header: DerHeader): Boolean = true\n\n override fun toDer(\n writer: DerWriter,\n value: Any?,\n ) {\n when {\n isOptional && value == optionalValue -> {\n // Write nothing.\n }\n\n else -> {\n for ((type, adapter) in choices) {\n if (type.isInstance(value) || (value == null && type == Unit::class)) {\n (adapter as DerAdapter).toDer(writer, value)\n return\n }\n }\n }\n }\n }\n\n override fun fromDer(reader: DerReader): Any? {\n if (isOptional && !reader.hasNext()) return optionalValue\n\n val peekedHeader =\n reader.peekHeader()\n ?: throw ProtocolException(\"expected a value at $reader\")\n for ((_, adapter) in choices) {\n if (adapter.matches(peekedHeader)) {\n return adapter.fromDer(reader)\n }\n }\n\n throw "} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":491,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(header: DerHeader): Boolean = true"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":493,"symbol":"toDer","kind":"function","lang":"kotlin","code":"override fun toDer(\n writer: DerWriter,\n value: Any?,\n ) {\n when {\n isOptional && value == optionalValue -> {\n // Write nothing.\n }\n\n else -> {\n for ((type, adapter) in choices) {\n if (type.isInstance(value) || (value == null && type == Unit::class)) {\n (adapter as DerAdapter).toDer(writer, value)\n return\n }\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Adapters.kt","line":513,"symbol":"fromDer","kind":"function","lang":"kotlin","code":"override fun fromDer(reader: DerReader): Any? {\n if (isOptional && !reader.hasNext()) return optionalValue\n\n val peekedHeader =\n reader.peekHeader()\n ?: throw ProtocolException(\"expected a value at $reader\")\n for ((_, adapter) in choices) {\n if (adapter.matches(peekedHeader)) {\n return adapter.fromDer(reader)\n }\n }\n\n throw ProtocolException(\"expected any but was $peekedHeader at $reader\")\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":26,"symbol":"BasicDerAdapter","kind":"class","lang":"kotlin","doc":"Handles basic types that always use the same tag. This supports optional types and may set a type hint for further adapters to process. Types like ANY and CHOICE that don't have a consistent tag cannot use this.","code":"internal data class BasicDerAdapter(\n private val name: String,\n /** The tag class this adapter expects, or -1 to match any tag class. */\n val tagClass: Int,\n /** The tag this adapter expects, or -1 to match any tag. */\n val tag: Long,\n /** Encode and decode the value once tags are handled. */\n private val codec: Codec,\n /** True if the default value should be used if this value is absent during decoding. */\n val isOptional: Boolean = false,\n /** The value to return if this value is absent. Undefined unless this is optional. */\n val defaultValue: T? = null,\n /** True to set the encoded or decoded value as the type hint for the current SEQUENCE. */\n private val typeHint: Boolean = false,\n) : DerAdapter {\n init {\n require(tagClass >= 0)\n require(tag >= 0)\n }\n\n override fun matches(header: DerHeader): Boolean = header.tagClass == tagClass && header.tag == tag\n\n override fun fromDer(reader: DerReader): T {\n val peekedHeader = reader.peekHeader()\n if (peekedHeader == null || peekedHeader.tagClass != tagClass || peekedHeader.tag != tag) {\n if (isOptional) return defaultValue as T\n throw ProtocolException(\"expected $this but was $peekedHeade"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":46,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(header: DerHeader): Boolean = header.tagClass == tagClass && header.tag == tag"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":48,"symbol":"fromDer","kind":"function","lang":"kotlin","code":"override fun fromDer(reader: DerReader): T {\n val peekedHeader = reader.peekHeader()\n if (peekedHeader == null || peekedHeader.tagClass != tagClass || peekedHeader.tag != tag) {\n if (isOptional) return defaultValue as T\n throw ProtocolException(\"expected $this but was $peekedHeader at $reader\")\n }\n\n val result =\n reader.read(name) {\n codec.decode(reader)\n }\n\n if (typeHint) {\n reader.typeHint = result\n }\n\n return result\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":67,"symbol":"toDer","kind":"function","lang":"kotlin","code":"override fun toDer(\n writer: DerWriter,\n value: T,\n ) {\n if (typeHint) {\n writer.typeHint = value\n }\n\n if (isOptional && value == defaultValue) {\n // Nothing to write!\n return\n }\n\n writer.write(name, tagClass, tag) {\n codec.encode(writer, value)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":106,"symbol":"withTag","kind":"function","lang":"kotlin","doc":"Point ::= SEQUENCE { x [APPLICATION 0] INTEGER OPTIONAL, y [APPLICATION 1] INTEGER OPTIONAL } ```","code":"fun withTag(\n tagClass: Int = DerHeader.TAG_CLASS_CONTEXT_SPECIFIC,\n tag: Long,\n ): BasicDerAdapter = copy(tagClass = tagClass, tag = tag)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":112,"symbol":"optional","kind":"function","lang":"kotlin","doc":"Returns a copy of this adapter that doesn't encode values equal to [defaultValue].","code":"fun optional(defaultValue: T? = null): BasicDerAdapter = copy(isOptional = true, defaultValue = defaultValue)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":118,"symbol":"asTypeHint","kind":"function","lang":"kotlin","doc":"Returns a copy of this adapter that sets the encoded or decoded value as the type hint for the other adapters on this SEQUENCE to interrogate.","code":"fun asTypeHint(): BasicDerAdapter = copy(typeHint = true)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":120,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"$name [$tagClass/$tag]\""} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":123,"symbol":"Codec","kind":"interface","lang":"kotlin","doc":"Reads and writes values without knowledge of the enclosing tag, length, or defaults.","code":"interface Codec {\n fun decode(reader: DerReader): T\n\n fun encode(\n writer: DerWriter,\n value: T,\n )\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":124,"symbol":"decode","kind":"function","lang":"kotlin","code":"fun decode(reader: DerReader): T"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt","line":126,"symbol":"encode","kind":"function","lang":"kotlin","code":"fun encode(\n writer: DerWriter,\n value: T,\n )"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Certificate.kt","line":29,"symbol":"Certificate","kind":"class","lang":"kotlin","code":"internal data class Certificate(\n val tbsCertificate: TbsCertificate,\n val signatureAlgorithm: AlgorithmIdentifier,\n val signatureValue: BitString,\n) {\n val commonName: Any?\n get() {\n return tbsCertificate.subject\n .flatten()\n .firstOrNull { it.type == ObjectIdentifiers.COMMON_NAME }\n ?.value\n }\n\n val organizationalUnitName: Any?\n get() {\n return tbsCertificate.subject\n .flatten()\n .firstOrNull { it.type == ObjectIdentifiers.ORGANIZATIONAL_UNIT_NAME }\n ?.value\n }\n\n val subjectAlternativeNames: Extension?\n get() {\n return tbsCertificate.extensions.firstOrNull {\n it.id == ObjectIdentifiers.SUBJECT_ALTERNATIVE_NAME\n }\n }\n\n val basicConstraints: Extension\n get() {\n return tbsCertificate.extensions.first {\n it.id == ObjectIdentifiers.BASIC_CONSTRAINTS\n }\n }\n\n /** Returns true if the certificate was signed by [issuer]. */\n @Throws(SignatureException::class)\n fun checkSignature(issuer: PublicKey): Boolean {\n val signedData = CertificateAdapters.tbsCertificate.toDer(tbsCertificate)\n\n return Signature.getInstance(tbsCertificate.signatureAlgorithmName).run {\n ini"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Certificate.kt","line":65,"symbol":"checkSignature","kind":"function","lang":"kotlin","doc":"Returns true if the certificate was signed by [issuer].","code":"@Throws(SignatureException::class)\n fun checkSignature(issuer: PublicKey): Boolean {\n val signedData = CertificateAdapters.tbsCertificate.toDer(tbsCertificate)\n\n return Signature.getInstance(tbsCertificate.signatureAlgorithmName).run {\n initVerify(issuer)\n update(signedData.toByteArray())\n verify(signatureValue.byteString.toByteArray())\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Certificate.kt","line":76,"symbol":"toX509Certificate","kind":"function","lang":"kotlin","code":"fun toX509Certificate(): X509Certificate {\n val data = CertificateAdapters.certificate.toDer(this)\n try {\n val certificateFactory = CertificateFactory.getInstance(\"X.509\")\n val certificates = certificateFactory.generateCertificates(Buffer().write(data).inputStream())\n return certificates.single() as X509Certificate\n } catch (e: NoSuchElementException) {\n throw IllegalArgumentException(\"failed to decode certificate\", e)\n } catch (e: IllegalArgumentException) {\n throw IllegalArgumentException(\"failed to decode certificate\", e)\n } catch (e: GeneralSecurityException) {\n throw IllegalArgumentException(\"failed to decode certificate\", e)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Certificate.kt","line":92,"symbol":"TbsCertificate","kind":"class","lang":"kotlin","code":"internal data class TbsCertificate(\n /** This is a integer enum. Use 0L for v1, 1L for v2, and 2L for v3. */\n val version: Long,\n val serialNumber: BigInteger,\n val signature: AlgorithmIdentifier,\n val issuer: List>,\n val validity: Validity,\n val subject: List>,\n val subjectPublicKeyInfo: SubjectPublicKeyInfo,\n val issuerUniqueID: BitString?,\n val subjectUniqueID: BitString?,\n val extensions: List,\n) {\n /**\n * Returns the standard name of this certificate's signature algorithm as specified by\n * [Signature.getInstance]. Typical values are like \"SHA256WithRSA\".\n */\n val signatureAlgorithmName: String\n get() {\n return when (signature.algorithm) {\n ObjectIdentifiers.SHA256_WITH_RSA_ENCRYPTION -> \"SHA256WithRSA\"\n ObjectIdentifiers.SHA256_WITH_ECDSA -> \"SHA256withECDSA\"\n else -> error(\"unexpected signature algorithm: ${signature.algorithm}\")\n }\n }\n\n // Avoid Long.hashCode(long) which isn't available on Android 5.\n override fun hashCode(): Int {\n var result = 0\n result = 31 * result + version.toInt()\n result = 31 * result + serialNumber.hashCode()\n resu"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/Certificate.kt","line":119,"symbol":"hashCode","kind":"function","lang":"kotlin","doc":"Avoid Long.hashCode(long) which isn't available on Android 5.","code":"override fun hashCode(): Int {\n var result = 0\n result = 31 * result + version.toInt()\n result = 31 * result + serialNumber.hashCode()\n result = 31 * result + signature.hashCode()\n result = 31 * result + issuer.hashCode()\n result = 31 * result + validity.hashCode()\n result = 31 * result + subject.hashCode()\n result = 31 * result + subjectPublicKeyInfo.hashCode()\n result = 31 * result + (issuerUniqueID?.hashCode() ?: 0)\n result = 31 * result + (subjectUniqueID?.hashCode() ?: 0)\n result = 31 * result + extensions.hashCode()\n return result\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt","line":27,"symbol":"CertificateAdapters","kind":"object","lang":"kotlin","doc":"ASN.1 adapters adapted from the specifications in [RFC 5280][rfc_5280]. [rfc_5280]: https://tools.ietf.org/html/rfc5280","code":"@Suppress(\"UNCHECKED_CAST\") // This needs to cast decoded collections.\ninternal object CertificateAdapters {\n /**\n * ```\n * Time ::= CHOICE {\n * utcTime UTCTime,\n * generalTime GeneralizedTime\n * }\n * ```\n *\n * RFC 5280, section 4.1.2.5:\n *\n * > CAs conforming to this profile MUST always encode certificate validity dates through the year\n * > 2049 as UTCTime; certificate validity dates in 2050 or later MUST be encoded as\n * > GeneralizedTime.\n */\n internal val time: DerAdapter =\n object : DerAdapter {\n override fun matches(header: DerHeader): Boolean = Adapters.UTC_TIME.matches(header) || Adapters.GENERALIZED_TIME.matches(header)\n\n override fun fromDer(reader: DerReader): Long {\n val peekHeader =\n reader.peekHeader()\n ?: throw ProtocolException(\"expected time but was exhausted at $reader\")\n\n return when {\n peekHeader.tagClass == Adapters.UTC_TIME.tagClass &&\n peekHeader.tag == Adapters.UTC_TIME.tag -> {\n Adapters.UTC_TIME.fromDer(reader)\n }\n\n peekHeader.tagClass == Adapters.GENERALIZED_TIME.tagClass &&\n peekHeader.tag == Ad"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt","line":45,"symbol":"matches","kind":"function","lang":"kotlin","code":"override fun matches(header: DerHeader): Boolean = Adapters.UTC_TIME.matches(header) || Adapters.GENERALIZED_TIME.matches(header)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt","line":47,"symbol":"fromDer","kind":"function","lang":"kotlin","code":"override fun fromDer(reader: DerReader): Long {\n val peekHeader =\n reader.peekHeader()\n ?: throw ProtocolException(\"expected time but was exhausted at $reader\")\n\n return when {\n peekHeader.tagClass == Adapters.UTC_TIME.tagClass &&\n peekHeader.tag == Adapters.UTC_TIME.tag -> {\n Adapters.UTC_TIME.fromDer(reader)\n }\n\n peekHeader.tagClass == Adapters.GENERALIZED_TIME.tagClass &&\n peekHeader.tag == Adapters.GENERALIZED_TIME.tag -> {\n Adapters.GENERALIZED_TIME.fromDer(reader)\n }\n\n else -> {\n throw ProtocolException(\"expected time but was $peekHeader at $reader\")\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/CertificateAdapters.kt","line":69,"symbol":"toDer","kind":"function","lang":"kotlin","code":"override fun toDer(\n writer: DerWriter,\n value: Long,\n ) {\n // [1950-01-01T00:00:00..2050-01-01T00:00:00Z)\n if (value in -631_152_000_000L until 2_524_608_000_000L) {\n Adapters.UTC_TIME.toDer(writer, value)\n } else {\n Adapters.GENERALIZED_TIME.toDer(writer, value)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":24,"symbol":"DerAdapter","kind":"interface","lang":"kotlin","doc":"Encode and decode a model object like a [Long] or [Certificate] as DER bytes.","code":"internal interface DerAdapter {\n /** Returns true if this adapter can read [header] in a choice. */\n fun matches(header: DerHeader): Boolean\n\n /**\n * Returns a value from this adapter.\n *\n * This must always return a value, though it doesn't necessarily need to consume data from\n * [reader]. For example, if the reader's peeked tag isn't readable by this adapter, it may return\n * a default value.\n *\n * If this does read a value, it starts with the tag and length, and reads an entire value,\n * including any potential composed values.\n *\n * If there's nothing to read and no default value, this will throw an exception.\n */\n fun fromDer(reader: DerReader): T\n\n fun fromDer(byteString: ByteString): T {\n val buffer = Buffer().write(byteString)\n val reader = DerReader(buffer)\n return fromDer(reader)\n }\n\n /**\n * Writes [value] to this adapter, unless it is the default value and can be safely omitted.\n *\n * If this does write a value, it will write a tag and a length and a full value.\n */\n fun toDer(\n writer: DerWriter,\n value: T,\n )\n\n fun toDer(value: T): ByteString {\n val buffer = Buffer()\n val writer = DerWriter(buffer)\n to"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":26,"symbol":"matches","kind":"function","lang":"kotlin","doc":"Returns true if this adapter can read [header] in a choice.","code":"fun matches(header: DerHeader): Boolean"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":40,"symbol":"fromDer","kind":"function","lang":"kotlin","doc":"If this does read a value, it starts with the tag and length, and reads an entire value, including any potential composed values. If there's nothing to read and no default value, this will throw an exception.","code":"fun fromDer(reader: DerReader): T"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":42,"symbol":"fromDer","kind":"function","lang":"kotlin","code":"fun fromDer(byteString: ByteString): T {\n val buffer = Buffer().write(byteString)\n val reader = DerReader(buffer)\n return fromDer(reader)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":53,"symbol":"toDer","kind":"function","lang":"kotlin","doc":"Writes [value] to this adapter, unless it is the default value and can be safely omitted. If this does write a value, it will write a tag and a length and a full value.","code":"fun toDer(\n writer: DerWriter,\n value: T,\n )"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":58,"symbol":"toDer","kind":"function","lang":"kotlin","code":"fun toDer(value: T): ByteString {\n val buffer = Buffer()\n val writer = DerWriter(buffer)\n toDer(writer, value)\n return buffer.readByteString()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":79,"symbol":"withExplicitBox","kind":"function","lang":"kotlin","doc":"``` @param forceConstructed non-null to set the constructed bit to the specified value, even if the writing process sets something else. This is used to encode SEQUENCES in values that are declared to have non-constructed values, like OCTET STRING values.","code":"@Suppress(\"UNCHECKED_CAST\") // read() produces a single element of the expected type.\n fun withExplicitBox(\n tagClass: Int = DerHeader.TAG_CLASS_CONTEXT_SPECIFIC,\n tag: Long,\n forceConstructed: Boolean? = null,\n ): BasicDerAdapter {\n val codec =\n object : BasicDerAdapter.Codec {\n override fun decode(reader: DerReader): T = fromDer(reader)\n\n override fun encode(\n writer: DerWriter,\n value: T,\n ) {\n toDer(writer, value)\n if (forceConstructed != null) {\n writer.constructed = forceConstructed\n }\n }\n }\n\n return BasicDerAdapter(\n name = \"EXPLICIT\",\n tagClass = tagClass,\n tag = tag,\n codec = codec,\n )\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":87,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): T = fromDer(reader)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":89,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: T,\n ) {\n toDer(writer, value)\n if (forceConstructed != null) {\n writer.constructed = forceConstructed\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":109,"symbol":"asSequenceOf","kind":"function","lang":"kotlin","doc":"Returns an adapter that returns a list of values of this type.","code":"fun asSequenceOf(\n name: String = \"SEQUENCE OF\",\n tagClass: Int = DerHeader.TAG_CLASS_UNIVERSAL,\n tag: Long = 16L,\n ): BasicDerAdapter> {\n val codec =\n object : BasicDerAdapter.Codec> {\n override fun encode(\n writer: DerWriter,\n value: List,\n ) {\n for (v in value) {\n toDer(writer, v)\n }\n }\n\n override fun decode(reader: DerReader): List {\n val result = mutableListOf()\n while (reader.hasNext()) {\n result += fromDer(reader)\n }\n return result\n }\n }\n\n return BasicDerAdapter(name, tagClass, tag, codec)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":116,"symbol":"encode","kind":"function","lang":"kotlin","code":"override fun encode(\n writer: DerWriter,\n value: List,\n ) {\n for (v in value) {\n toDer(writer, v)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":125,"symbol":"decode","kind":"function","lang":"kotlin","code":"override fun decode(reader: DerReader): List {\n val result = mutableListOf()\n while (reader.hasNext()) {\n result += fromDer(reader)\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerAdapter.kt","line":138,"symbol":"asSetOf","kind":"function","lang":"kotlin","doc":"Returns an adapter that returns a set of values of this type.","code":"fun asSetOf(): BasicDerAdapter> =\n asSequenceOf(\n name = \"SET OF\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 17L,\n )"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerHeader.kt","line":21,"symbol":"DerHeader","kind":"class","lang":"kotlin","doc":"The first two bytes of each value is a header that includes its tag (field ID) and length.","code":"internal data class DerHeader(\n /**\n * Namespace of the tag.\n *\n * This value is encoded in bits 7 and 8 of the first byte of each value.\n *\n * ```\n * 0b00xxxxxx Universal\n * 0b01xxxxxx Application\n * 0b10xxxxxx Context-Specific\n * 0b11xxxxxx Private\n * ```\n */\n var tagClass: Int,\n /** Identifies which member in the ASN.1 schema the field holds. */\n var tag: Long,\n /**\n * If the constructed bit is set it indicates that the value is composed of other values that have\n * their own headers.\n *\n * This value is encoded in bit 6 of the first byte of each value.\n *\n * ```\n * 0bxx0xxxxx Primitive\n * 0bxx1xxxxx Constructed\n * ```\n */\n var constructed: Boolean,\n /** Length of the message in bytes, or -1L if its length is unknown at the time of encoding. */\n var length: Long,\n) {\n val isEndOfData: Boolean\n get() = tagClass == TAG_CLASS_UNIVERSAL && tag == TAG_END_OF_CONTENTS\n\n override fun toString(): String = \"$tagClass/$tag\"\n\n companion object {\n const val TAG_CLASS_UNIVERSAL = 0b0000_0000\n const val TAG_CLASS_APPLICATION = 0b0100_0000\n const val TAG_CLASS_CONTEXT_SPECIFIC = 0b1000_0000\n const val TAG_CLASS_PRIVATE = 0b110"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerHeader.kt","line":55,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = \"$tagClass/$tag\""} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":40,"symbol":"DerReader","kind":"class","lang":"kotlin","doc":"This class was implemented according to the [X.690 spec][[x690]], and under the advice of [Lets Encrypt's ASN.1 and DER][asn1_and_der] guide. [x690]: https://www.itu.int/rec/T-REC-X.690 [asn1_and_der]: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/","code":"internal class DerReader(\n source: Source,\n) {\n private val countingSource: CountingSource = CountingSource(source)\n private val source: BufferedSource = countingSource.buffer()\n\n /** Total bytes read thus far. */\n private val byteCount: Long\n get() = countingSource.bytesRead - source.buffer.size\n\n /** How many bytes to read before [peekHeader] should return false, or -1L for no limit. */\n private var limit = -1L\n\n /** Type hints scoped to the call stack, manipulated with [withTypeHint]. */\n private val typeHintStack = mutableListOf()\n\n /**\n * The type hint for the current object. Used to pick adapters based on other fields, such as\n * in extensions which have different types depending on their extension ID.\n */\n var typeHint: Any?\n get() = typeHintStack.lastOrNull()\n set(value) {\n typeHintStack[typeHintStack.size - 1] = value\n }\n\n /** Names leading to the current location in the ASN.1 document. */\n private val path = mutableListOf()\n\n private var constructed = false\n\n private var peekedHeader: DerHeader? = null\n\n private val bytesLeft: Long\n get() = if (limit == -1L) -1L else (limit - byteCount)\n\n fun hasNext(): Boolean = pe"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":76,"symbol":"hasNext","kind":"function","lang":"kotlin","code":"fun hasNext(): Boolean = peekHeader() != null"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":87,"symbol":"peekHeader","kind":"function","lang":"kotlin","doc":"This returns null if: * The stream is exhausted. * We've read all of the bytes of an object whose length is known. * We've reached the [DerHeader.TAG_END_OF_CONTENTS] of an object whose length is unknown.","code":"fun peekHeader(): DerHeader? {\n var result = peekedHeader\n\n if (result == null) {\n result = readHeader()\n peekedHeader = result\n }\n\n if (result.isEndOfData) return null\n\n return result\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":104,"symbol":"readHeader","kind":"function","lang":"kotlin","doc":"Consume the next header in the stream and return it. If there is no header to read because we have reached a limit, this returns [END_OF_DATA].","code":"internal fun readHeader(): DerHeader {\n require(peekedHeader == null)\n\n // We've hit a local limit.\n if (byteCount == limit) return END_OF_DATA\n\n // We've exhausted the source stream.\n if (limit == -1L && source.exhausted()) return END_OF_DATA\n\n // Read the tag.\n val tagAndClass = source.readByte().toInt() and 0xff\n val tagClass = tagAndClass and 0b1100_0000\n val constructed = (tagAndClass and 0b0010_0000) == 0b0010_0000\n val tag =\n when (val tag0 = tagAndClass and 0b0001_1111) {\n 0b0001_1111 -> readVariableLengthLong()\n else -> tag0.toLong()\n }\n\n // Read the length.\n val length0 = source.readByte().toInt() and 0xff\n val length =\n when {\n length0 == 0b1000_0000 -> {\n throw ProtocolException(\"indefinite length not permitted for DER\")\n }\n\n (length0 and 0b1000_0000) == 0b1000_0000 -> {\n // Length specified over multiple bytes.\n val lengthBytes = length0 and 0b0111_1111\n if (lengthBytes > 8) {\n throw ProtocolException(\"length encoded with more than 8 bytes is not supported\")\n }\n\n var lengthBits = source.readByte().toLong() and 0xff\n "} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":167,"symbol":"read","kind":"function","lang":"kotlin","doc":"Consume a header and execute [block], which should consume the entire value described by the header. It is an error to not consume a full value in [block].","code":"internal inline fun read(\n name: String?,\n block: (DerHeader) -> T,\n ): T {\n if (!hasNext()) throw ProtocolException(\"expected a value\")\n\n val header = peekedHeader!!\n peekedHeader = null\n\n val pushedLimit = limit\n val pushedConstructed = constructed\n\n val newLimit = if (header.length != -1L) byteCount + header.length else -1L\n if (pushedLimit != -1L && newLimit > pushedLimit) {\n throw ProtocolException(\"enclosed object too large\")\n }\n\n limit = newLimit\n constructed = header.constructed\n if (name != null) path += name\n try {\n val result = block(header)\n\n // The object processed bytes beyond its range.\n if (newLimit != -1L && byteCount > newLimit) {\n throw ProtocolException(\"unexpected byte count at $this\")\n }\n\n return result\n } finally {\n peekedHeader = null\n limit = pushedLimit\n constructed = pushedConstructed\n if (name != null) path.removeAt(path.size - 1)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":208,"symbol":"withTypeHint","kind":"function","lang":"kotlin","doc":"Execute [block] with a new namespace for type hints. Type hints from the enclosing type are no longer usable by the current type's members.","code":"fun withTypeHint(block: () -> T): T {\n typeHintStack.add(null)\n try {\n return block()\n } finally {\n typeHintStack.removeAt(typeHintStack.size - 1)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":217,"symbol":"readBoolean","kind":"function","lang":"kotlin","code":"fun readBoolean(): Boolean {\n if (bytesLeft != 1L) throw ProtocolException(\"unexpected length: $bytesLeft at $this\")\n return source.readByte().toInt() != 0\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":222,"symbol":"readBigInteger","kind":"function","lang":"kotlin","code":"fun readBigInteger(): BigInteger {\n if (bytesLeft == 0L) throw ProtocolException(\"unexpected length: $bytesLeft at $this\")\n val byteArray = source.readByteArray(bytesLeft)\n return BigInteger(byteArray)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":228,"symbol":"readLong","kind":"function","lang":"kotlin","code":"fun readLong(): Long {\n if (bytesLeft !in 1..8) throw ProtocolException(\"unexpected length: $bytesLeft at $this\")\n\n var result = source.readByte().toLong() // No \"and 0xff\" because this is a signed value!\n while (byteCount < limit) {\n result = result shl 8\n result += source.readByte().toInt() and 0xff\n }\n return result\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":239,"symbol":"readBitString","kind":"function","lang":"kotlin","code":"fun readBitString(): BitString {\n if (bytesLeft == -1L || constructed) {\n throw ProtocolException(\"constructed bit strings not supported for DER\")\n }\n if (bytesLeft < 1) {\n throw ProtocolException(\"malformed bit string\")\n }\n val unusedBitCount = source.readByte().toInt() and 0xff\n val byteString = source.readByteString(bytesLeft)\n return BitString(byteString, unusedBitCount)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":251,"symbol":"readOctetString","kind":"function","lang":"kotlin","code":"fun readOctetString(): ByteString {\n if (bytesLeft == -1L || constructed) {\n throw ProtocolException(\"constructed octet strings not supported for DER\")\n }\n return source.readByteString(bytesLeft)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":258,"symbol":"readUtf8String","kind":"function","lang":"kotlin","code":"fun readUtf8String(): String {\n if (bytesLeft == -1L || constructed) {\n throw ProtocolException(\"constructed strings not supported for DER\")\n }\n return source.readUtf8(bytesLeft)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":265,"symbol":"readObjectIdentifier","kind":"function","lang":"kotlin","code":"fun readObjectIdentifier(): String {\n val result = Buffer()\n val dot = '.'.code.toByte().toInt()\n when (val xy = readVariableLengthLong()) {\n in 0L until 40L -> {\n result.writeDecimalLong(0)\n result.writeByte(dot)\n result.writeDecimalLong(xy)\n }\n\n in 40L until 80L -> {\n result.writeDecimalLong(1)\n result.writeByte(dot)\n result.writeDecimalLong(xy - 40L)\n }\n\n else -> {\n result.writeDecimalLong(2)\n result.writeByte(dot)\n result.writeDecimalLong(xy - 80L)\n }\n }\n while (byteCount < limit) {\n result.writeByte(dot)\n result.writeDecimalLong(readVariableLengthLong())\n }\n return result.readUtf8()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":294,"symbol":"readRelativeObjectIdentifier","kind":"function","lang":"kotlin","code":"fun readRelativeObjectIdentifier(): String {\n val result = Buffer()\n val dot = '.'.code.toByte().toInt()\n while (byteCount < limit) {\n if (result.size > 0) {\n result.writeByte(dot)\n }\n result.writeDecimalLong(readVariableLengthLong())\n }\n return result.readUtf8()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":307,"symbol":"readVariableLengthLong","kind":"function","lang":"kotlin","doc":"Used for tags and subidentifiers.","code":"private fun readVariableLengthLong(): Long {\n // TODO(jwilson): detect overflow.\n var result = 0L\n while (true) {\n val byteN = source.readByte().toLong() and 0xff\n if ((byteN and 0b1000_0000L) == 0b1000_0000L) {\n result = (result + (byteN and 0b0111_1111)) shl 7\n } else {\n return result + byteN\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":321,"symbol":"readUnknown","kind":"function","lang":"kotlin","doc":"Read a value as bytes without interpretation of its contents.","code":"fun readUnknown(): ByteString = source.readByteString(bytesLeft)"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":323,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = path.joinToString(separator = \" / \")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":341,"symbol":"CountingSource","kind":"class","lang":"kotlin","doc":"A source that keeps track of how many bytes it's consumed.","code":"private class CountingSource(\n source: Source,\n ) : ForwardingSource(source) {\n var bytesRead = 0L\n\n override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val result = delegate.read(sink, byteCount)\n if (result == -1L) return -1L\n bytesRead += result\n return result\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerReader.kt","line":346,"symbol":"read","kind":"function","lang":"kotlin","code":"override fun read(\n sink: Buffer,\n byteCount: Long,\n ): Long {\n val result = delegate.read(sink, byteCount)\n if (result == -1L) return -1L\n bytesRead += result\n return result\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":23,"symbol":"DerWriter","kind":"class","lang":"kotlin","code":"internal class DerWriter(\n sink: BufferedSink,\n) {\n /** A stack of buffers that will be concatenated once we know the length of each. */\n private val stack = mutableListOf(sink)\n\n /** Type hints scoped to the call stack, manipulated with [pushTypeHint] and [popTypeHint]. */\n private val typeHintStack = mutableListOf()\n\n /**\n * The type hint for the current object. Used to pick adapters based on other fields, such as\n * in extensions which have different types depending on their extension ID.\n */\n var typeHint: Any?\n get() = typeHintStack.lastOrNull()\n set(value) {\n typeHintStack[typeHintStack.size - 1] = value\n }\n\n /** Names leading to the current location in the ASN.1 document. */\n private val path = mutableListOf()\n\n /**\n * False unless we made a recursive call to [write] at the current stack frame. The explicit box\n * adapter can clear this to synthesize non-constructed values that are embedded in octet strings.\n */\n var constructed = false\n\n fun write(\n name: String,\n tagClass: Int,\n tag: Long,\n block: (BufferedSink) -> Unit,\n ) {\n val constructedBit: Int\n val content = Buffer()\n\n stack.add(content)\n c"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":51,"symbol":"write","kind":"function","lang":"kotlin","code":"fun write(\n name: String,\n tagClass: Int,\n tag: Long,\n block: (BufferedSink) -> Unit,\n ) {\n val constructedBit: Int\n val content = Buffer()\n\n stack.add(content)\n constructed = false // The enclosed object written in block() is not constructed.\n path += name\n try {\n block(content)\n constructedBit = if (constructed) 0b0010_0000 else 0\n constructed = true // The enclosing object is constructed.\n } finally {\n stack.removeAt(stack.size - 1)\n path.removeAt(path.size - 1)\n }\n\n val sink = sink()\n\n // Write the tagClass, tag, and constructed bit. This takes 1 byte if tag is less than 31.\n if (tag < 31) {\n val byte0 = tagClass or constructedBit or tag.toInt()\n sink.writeByte(byte0)\n } else {\n val byte0 = tagClass or constructedBit or 0b0001_1111\n sink.writeByte(byte0)\n writeVariableLengthLong(tag)\n }\n\n // Write the length. This takes 1 byte if length is less than 128.\n val length = content.size\n if (length < 128) {\n sink.writeByte(length.toInt())\n } else {\n // count how many bytes we'll need to express the length.\n val lengthBitCount = 64 - java.lang.Long.numberOfL"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":106,"symbol":"withTypeHint","kind":"function","lang":"kotlin","doc":"Execute [block] with a new namespace for type hints. Type hints from the enclosing type are no longer usable by the current type's members.","code":"fun withTypeHint(block: () -> T): T {\n typeHintStack.add(null)\n try {\n return block()\n } finally {\n typeHintStack.removeAt(typeHintStack.size - 1)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":115,"symbol":"sink","kind":"function","lang":"kotlin","code":"private fun sink(): BufferedSink = stack[stack.size - 1]"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":117,"symbol":"writeBoolean","kind":"function","lang":"kotlin","code":"fun writeBoolean(b: Boolean) {\n sink().writeByte(if (b) -1 else 0)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":121,"symbol":"writeBigInteger","kind":"function","lang":"kotlin","code":"fun writeBigInteger(value: BigInteger) {\n sink().write(value.toByteArray())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":125,"symbol":"writeLong","kind":"function","lang":"kotlin","code":"fun writeLong(v: Long) {\n val sink = sink()\n\n val lengthBitCount: Int =\n if (v < 0L) {\n 65 - java.lang.Long.numberOfLeadingZeros(v xor -1L)\n } else {\n 65 - java.lang.Long.numberOfLeadingZeros(v)\n }\n\n val lengthByteCount = (lengthBitCount + 7) / 8\n for (shift in (lengthByteCount - 1) * 8 downTo 0 step 8) {\n sink.writeByte((v shr shift).toInt())\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":141,"symbol":"writeBitString","kind":"function","lang":"kotlin","code":"fun writeBitString(bitString: BitString) {\n val sink = sink()\n sink.writeByte(bitString.unusedBitsCount)\n sink.write(bitString.byteString)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":147,"symbol":"writeOctetString","kind":"function","lang":"kotlin","code":"fun writeOctetString(byteString: ByteString) {\n sink().write(byteString)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":151,"symbol":"writeUtf8","kind":"function","lang":"kotlin","code":"fun writeUtf8(value: String) {\n sink().writeUtf8(value)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":155,"symbol":"writeObjectIdentifier","kind":"function","lang":"kotlin","code":"fun writeObjectIdentifier(s: String) {\n val utf8 = Buffer().writeUtf8(s)\n val v1 = utf8.readDecimalLong()\n require(utf8.readByte() == '.'.code.toByte())\n val v2 = utf8.readDecimalLong()\n writeVariableLengthLong(v1 * 40 + v2)\n\n while (!utf8.exhausted()) {\n require(utf8.readByte() == '.'.code.toByte())\n val vN = utf8.readDecimalLong()\n writeVariableLengthLong(vN)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":169,"symbol":"writeRelativeObjectIdentifier","kind":"function","lang":"kotlin","code":"fun writeRelativeObjectIdentifier(s: String) {\n // Add a leading dot so each subidentifier has a dot prefix.\n val utf8 =\n Buffer()\n .writeByte('.'.code.toByte().toInt())\n .writeUtf8(s)\n\n while (!utf8.exhausted()) {\n require(utf8.readByte() == '.'.code.toByte())\n val vN = utf8.readDecimalLong()\n writeVariableLengthLong(vN)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":184,"symbol":"writeVariableLengthLong","kind":"function","lang":"kotlin","doc":"Used for tags and subidentifiers.","code":"private fun writeVariableLengthLong(v: Long) {\n val sink = sink()\n val bitCount = 64 - java.lang.Long.numberOfLeadingZeros(v)\n val byteCount = (bitCount + 6) / 7\n for (shift in (byteCount - 1) * 7 downTo 0 step 7) {\n val lastBit = if (shift == 0) 0 else 0b1000_0000\n sink.writeByte(((v shr shift) and 0b0111_1111).toInt() or lastBit)\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/DerWriter.kt","line":194,"symbol":"toString","kind":"function","lang":"kotlin","code":"override fun toString(): String = path.joinToString(separator = \" / \")"} {"repo":"okhttp","file":"okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/ObjectIdentifiers.kt","line":19,"symbol":"ObjectIdentifiers","kind":"object","lang":"kotlin","doc":"ASN.1 object identifiers used internally by this implementation.","code":"internal object ObjectIdentifiers {\n const val EC_PUBLIC_KEY = \"1.2.840.10045.2.1\"\n const val SHA256_WITH_ECDSA = \"1.2.840.10045.4.3.2\"\n const val RSA_ENCRYPTION = \"1.2.840.113549.1.1.1\"\n const val SHA256_WITH_RSA_ENCRYPTION = \"1.2.840.113549.1.1.11\"\n const val SUBJECT_ALTERNATIVE_NAME = \"2.5.29.17\"\n const val BASIC_CONSTRAINTS = \"2.5.29.19\"\n const val COMMON_NAME = \"2.5.4.3\"\n const val ORGANIZATIONAL_UNIT_NAME = \"2.5.4.11\"\n}"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/CertificatesJavaTest.java","line":23,"symbol":"CertificatesJavaTest","kind":"class","lang":"java","code":"public class CertificatesJavaTest {\n @Test\n public void testRoundtrip() {\n String certificateString = \"\"\n + \"-----BEGIN CERTIFICATE-----\\n\"\n + \"MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\\n\"\n + \"LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\\n\"\n + \"CGNhc2guYXBwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCApFHhtrLan28q\\n\"\n + \"+oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1wJ4YEoUCjDlPOtpht7XLbUmBnbIzN\\n\"\n + \"89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274wL25fICR+yDEQ5fUVYBmJAKXZF1ao\\n\"\n + \"I0mIoEx0xFsQhIJ637v2MxJDupd61wIDAQABMA0GCSqGSIb3DQEBCwUAA4GBADam\\n\"\n + \"UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8\\n\"\n + \"8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY\\n\"\n + \"jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb\\n\"\n + \"-----END CERTIFICATE-----\\n\";\n\n X509Certificate certificate =\n Certificates.decodeCertificatePem(certificateString);\n\n assertEquals(certificateString, Certificates.certificatePem(certificate));\n }\n}"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/CertificatesJavaTest.java","line":24,"symbol":"testRoundtrip","kind":"method","lang":"java","code":"@Test\n public void testRoundtrip() {\n String certificateString = \"\"\n + \"-----BEGIN CERTIFICATE-----\\n\"\n + \"MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\\n\"\n + \"LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\\n\"\n + \"CGNhc2guYXBwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCApFHhtrLan28q\\n\"\n + \"+oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1wJ4YEoUCjDlPOtpht7XLbUmBnbIzN\\n\"\n + \"89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274wL25fICR+yDEQ5fUVYBmJAKXZF1ao\\n\"\n + \"I0mIoEx0xFsQhIJ637v2MxJDupd61wIDAQABMA0GCSqGSIb3DQEBCwUAA4GBADam\\n\"\n + \"UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8\\n\"\n + \"8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY\\n\"\n + \"jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb\\n\"\n + \"-----END CERTIFICATE-----\\n\";\n\n X509Certificate certificate =\n Certificates.decodeCertificatePem(certificateString);\n\n assertEquals(certificateString, Certificates.certificatePem(certificate));\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/CertificatesTest.kt","line":21,"symbol":"CertificatesTest","kind":"class","lang":"kotlin","code":"class CertificatesTest {\n @Test fun testRoundtrip() {\n val certificateString =\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\n LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\n CGNhc2guYXBwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCApFHhtrLan28q\n +oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1wJ4YEoUCjDlPOtpht7XLbUmBnbIzN\n 89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274wL25fICR+yDEQ5fUVYBmJAKXZF1ao\n I0mIoEx0xFsQhIJ637v2MxJDupd61wIDAQABMA0GCSqGSIb3DQEBCwUAA4GBADam\n UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8\n 8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY\n jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb\n -----END CERTIFICATE-----\n \n \"\"\".trimIndent()\n val certificate = certificateString.decodeCertificatePem()\n assertEquals(certificateString, certificate.certificatePem())\n }\n}"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/CertificatesTest.kt","line":22,"symbol":"testRoundtrip","kind":"function","lang":"kotlin","code":"@Test fun testRoundtrip() {\n val certificateString =\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\n LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\n CGNhc2guYXBwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCApFHhtrLan28q\n +oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1wJ4YEoUCjDlPOtpht7XLbUmBnbIzN\n 89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274wL25fICR+yDEQ5fUVYBmJAKXZF1ao\n I0mIoEx0xFsQhIJ637v2MxJDupd61wIDAQABMA0GCSqGSIb3DQEBCwUAA4GBADam\n UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8\n 8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY\n jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb\n -----END CERTIFICATE-----\n \n \"\"\".trimIndent()\n val certificate = certificateString.decodeCertificatePem()\n assertEquals(certificateString, certificate.certificatePem())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":41,"symbol":"HandshakeCertificatesTest","kind":"class","lang":"kotlin","code":"class HandshakeCertificatesTest {\n @RegisterExtension\n var platform = PlatformRule()\n\n private lateinit var executorService: ExecutorService\n\n private var serverSocket: ServerSocket? = null\n\n @BeforeEach fun setUp() {\n executorService = Executors.newCachedThreadPool(threadFactory(\"HandshakeCertificatesTest\"))\n }\n\n @AfterEach fun tearDown() {\n executorService.shutdown()\n serverSocket?.closeQuietly()\n }\n\n @Test fun clientAndServer() {\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n\n val clientRoot =\n HeldCertificate\n .Builder()\n .certificateAuthority(1)\n .build()\n val clientIntermediate =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .signedBy(clientRoot)\n .build()\n val clientCertificate =\n HeldCertificate\n .Builder()\n .signedBy(clientIntermediate)\n .build()\n val serverRoot =\n HeldCertificate\n .Builder()\n .certificateAuthority(1)\n .build()\n val serverIntermediate =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .signedBy(serverRoot)\n .build()\n val serverCertificate"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":49,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach fun setUp() {\n executorService = Executors.newCachedThreadPool(threadFactory(\"HandshakeCertificatesTest\"))\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":53,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n executorService.shutdown()\n serverSocket?.closeQuietly()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":58,"symbol":"clientAndServer","kind":"function","lang":"kotlin","code":"@Test fun clientAndServer() {\n platform.assumeNotConscrypt()\n platform.assumeNotBouncyCastle()\n\n val clientRoot =\n HeldCertificate\n .Builder()\n .certificateAuthority(1)\n .build()\n val clientIntermediate =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .signedBy(clientRoot)\n .build()\n val clientCertificate =\n HeldCertificate\n .Builder()\n .signedBy(clientIntermediate)\n .build()\n val serverRoot =\n HeldCertificate\n .Builder()\n .certificateAuthority(1)\n .build()\n val serverIntermediate =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .signedBy(serverRoot)\n .build()\n val serverCertificate =\n HeldCertificate\n .Builder()\n .signedBy(serverIntermediate)\n .build()\n val server =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(clientRoot.certificate)\n .heldCertificate(serverCertificate, serverIntermediate.certificate)\n .build()\n val client =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(serverRoot.certific"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":121,"symbol":"keyManager","kind":"function","lang":"kotlin","code":"@Test fun keyManager() {\n val root =\n HeldCertificate\n .Builder()\n .certificateAuthority(1)\n .build()\n val intermediate =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .signedBy(root)\n .build()\n val certificate =\n HeldCertificate\n .Builder()\n .signedBy(intermediate)\n .build()\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addTrustedCertificate(root.certificate) // BouncyCastle requires at least one\n .heldCertificate(certificate, intermediate.certificate)\n .build()\n assertPrivateKeysEquals(\n certificate.keyPair.private,\n handshakeCertificates.keyManager.getPrivateKey(\"private\"),\n )\n assertThat(handshakeCertificates.keyManager.getCertificateChain(\"private\").toList())\n .isEqualTo(listOf(certificate.certificate, intermediate.certificate))\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":152,"symbol":"platformTrustedCertificates","kind":"function","lang":"kotlin","code":"@Test fun platformTrustedCertificates() {\n val handshakeCertificates =\n HandshakeCertificates\n .Builder()\n .addPlatformTrustedCertificates()\n .build()\n val acceptedIssuers = handshakeCertificates.trustManager.acceptedIssuers\n val names =\n acceptedIssuers\n .map { it.subjectDN.name }\n .toSet()\n\n // It's safe to assume all platforms will have a major Internet certificate issuer.\n val majorIssuers =\n listOf(\n \"DigiCert\",\n \"Let's Encrypt\",\n \"ISRG\", // Internet Security Research Group (Let's Encrypt parent)\n \"GlobalSign\",\n \"Comodo\",\n \"Sectigo\",\n \"GeoTrust\",\n \"Entrust\",\n )\n assertThat(names).matchesPredicate { strings ->\n strings.any { name -> majorIssuers.any { issuer -> name.contains(issuer, ignoreCase = true) } }\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":181,"symbol":"startTlsServer","kind":"function","lang":"kotlin","code":"private fun startTlsServer(): InetSocketAddress {\n val serverSocketFactory = Platform.get().serverSocketFactory\n serverSocket = serverSocketFactory.createServerSocket()\n val serverAddress = InetAddress.getByName(\"localhost\")\n serverSocket!!.bind(InetSocketAddress(serverAddress, 0), 50)\n return InetSocketAddress(serverAddress, serverSocket!!.localPort)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":189,"symbol":"doServerHandshake","kind":"function","lang":"kotlin","code":"private fun doServerHandshake(server: HandshakeCertificates): Future {\n return executorService.submit {\n serverSocket!!.accept().use { rawSocket ->\n val sslSocket =\n server.sslSocketFactory().createSocket(\n rawSocket,\n rawSocket.inetAddress.hostAddress,\n rawSocket.port,\n true,\n ) as SSLSocket\n sslSocket.use {\n sslSocket.useClientMode = false\n sslSocket.wantClientAuth = true\n sslSocket.startHandshake()\n return@submit sslSocket.session.handshake()\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":209,"symbol":"doClientHandshake","kind":"function","lang":"kotlin","code":"private fun doClientHandshake(\n client: HandshakeCertificates,\n serverAddress: InetSocketAddress,\n ): Future {\n return executorService.submit {\n Platform.get().socketFactory.createSocket().use { rawSocket ->\n rawSocket.connect(serverAddress)\n val sslSocket =\n client.sslSocketFactory().createSocket(\n rawSocket,\n rawSocket.inetAddress.hostAddress,\n rawSocket.port,\n true,\n ) as SSLSocket\n sslSocket.use {\n sslSocket.startHandshake()\n return@submit sslSocket.session.handshake()\n }\n }\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HandshakeCertificatesTest.kt","line":231,"symbol":"assertPrivateKeysEquals","kind":"function","lang":"kotlin","code":"private fun assertPrivateKeysEquals(\n expected: PrivateKey,\n actual: PrivateKey,\n ) {\n assertThat(actual.encoded.toByteString()).isEqualTo(expected.encoded.toByteString())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":37,"symbol":"HeldCertificateTest","kind":"class","lang":"kotlin","code":"class HeldCertificateTest {\n @RegisterExtension\n var platform = PlatformRule()\n\n @Test\n fun defaultCertificate() {\n val now = System.currentTimeMillis()\n val heldCertificate = HeldCertificate.Builder().build()\n val certificate = heldCertificate.certificate\n assertThat(certificate.getSubjectX500Principal().name, \"self-signed\")\n .isEqualTo(certificate.getIssuerX500Principal().name)\n assertThat(certificate.getIssuerX500Principal().name).matches(Regex(\"CN=[0-9a-f-]{36}\"))\n assertThat(certificate.serialNumber).isEqualTo(BigInteger.ONE)\n assertThat(certificate.subjectAlternativeNames).isNull()\n val deltaMillis = 1000.0\n val durationMillis = TimeUnit.MINUTES.toMillis((60 * 24).toLong())\n assertThat(certificate.notBefore.time.toDouble())\n .isCloseTo(now.toDouble(), deltaMillis)\n assertThat(certificate.notAfter.time.toDouble())\n .isCloseTo(now.toDouble() + durationMillis, deltaMillis)\n }\n\n @Test\n fun customInterval() {\n // 5 seconds starting on 1970-01-01.\n val heldCertificate =\n HeldCertificate\n .Builder()\n .validityInterval(5000L, 10000L)\n .build()\n val certificate = heldCertificate.certificate\n a"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":41,"symbol":"defaultCertificate","kind":"function","lang":"kotlin","code":"@Test\n fun defaultCertificate() {\n val now = System.currentTimeMillis()\n val heldCertificate = HeldCertificate.Builder().build()\n val certificate = heldCertificate.certificate\n assertThat(certificate.getSubjectX500Principal().name, \"self-signed\")\n .isEqualTo(certificate.getIssuerX500Principal().name)\n assertThat(certificate.getIssuerX500Principal().name).matches(Regex(\"CN=[0-9a-f-]{36}\"))\n assertThat(certificate.serialNumber).isEqualTo(BigInteger.ONE)\n assertThat(certificate.subjectAlternativeNames).isNull()\n val deltaMillis = 1000.0\n val durationMillis = TimeUnit.MINUTES.toMillis((60 * 24).toLong())\n assertThat(certificate.notBefore.time.toDouble())\n .isCloseTo(now.toDouble(), deltaMillis)\n assertThat(certificate.notAfter.time.toDouble())\n .isCloseTo(now.toDouble() + durationMillis, deltaMillis)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":59,"symbol":"customInterval","kind":"function","lang":"kotlin","code":"@Test\n fun customInterval() {\n // 5 seconds starting on 1970-01-01.\n val heldCertificate =\n HeldCertificate\n .Builder()\n .validityInterval(5000L, 10000L)\n .build()\n val certificate = heldCertificate.certificate\n assertThat(certificate.notBefore.time).isEqualTo(5000L)\n assertThat(certificate.notAfter.time).isEqualTo(10000L)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":72,"symbol":"customDuration","kind":"function","lang":"kotlin","code":"@Test\n fun customDuration() {\n val now = System.currentTimeMillis()\n val heldCertificate =\n HeldCertificate\n .Builder()\n .duration(5, TimeUnit.SECONDS)\n .build()\n val certificate = heldCertificate.certificate\n val deltaMillis = 1000.0\n val durationMillis = 5000L\n assertThat(certificate.notBefore.time.toDouble())\n .isCloseTo(now.toDouble(), deltaMillis)\n assertThat(certificate.notAfter.time.toDouble())\n .isCloseTo(now.toDouble() + durationMillis, deltaMillis)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":89,"symbol":"subjectAlternativeNames","kind":"function","lang":"kotlin","code":"@Test\n fun subjectAlternativeNames() {\n val heldCertificate =\n HeldCertificate\n .Builder()\n .addSubjectAlternativeName(\"1.1.1.1\")\n .addSubjectAlternativeName(\"cash.app\")\n .build()\n val certificate = heldCertificate.certificate\n assertThat(certificate.subjectAlternativeNames.toList()).containsExactly(\n listOf(GeneralName.iPAddress, \"1.1.1.1\"),\n listOf(GeneralName.dNSName, \"cash.app\"),\n )\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":104,"symbol":"commonName","kind":"function","lang":"kotlin","code":"@Test\n fun commonName() {\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"cash.app\")\n .build()\n val certificate = heldCertificate.certificate\n assertThat(certificate.getSubjectX500Principal().name).isEqualTo(\"CN=cash.app\")\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":115,"symbol":"organizationalUnit","kind":"function","lang":"kotlin","code":"@Test\n fun organizationalUnit() {\n val heldCertificate =\n HeldCertificate\n .Builder()\n .commonName(\"cash.app\")\n .organizationalUnit(\"cash\")\n .build()\n val certificate = heldCertificate.certificate\n assertThat(certificate.getSubjectX500Principal().name).isEqualTo(\n \"CN=cash.app,OU=cash\",\n )\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":130,"symbol":"pems","kind":"function","lang":"kotlin","doc":"Confirm golden values of encoded PEMs.","code":"@Test\n fun pems() {\n val keyFactory = KeyFactory.getInstance(\"RSA\")\n val publicKeyBytes =\n (\n \"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCApFHhtrLan28q+oMolZuaTfWBA0V5aM\" +\n \"Ivq32BsloQu6LlvX1wJ4YEoUCjDlPOtpht7XLbUmBnbIzN89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274wL25fICR+\" +\n \"yDEQ5fUVYBmJAKXZF1aoI0mIoEx0xFsQhIJ637v2MxJDupd61wIDAQAB\"\n ).decodeBase64()!!\n val publicKey =\n keyFactory.generatePublic(\n X509EncodedKeySpec(publicKeyBytes.toByteArray()),\n )\n val privateKeyBytes =\n (\n \"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAICkUeG2stqfbyr6gyiVm\" +\n \"5pN9YEDRXlowi+rfYGyWhC7ouW9fXAnhgShQKMOU862mG3tcttSYGdsjM3z1crhQlUzpKqncrzwqbzPuAyt2t9Oib/\" +\n \"bvjAvbl8gJH7IMRDl9RVgGYkApdkXVqgjSYigTHTEWxCEgnrfu/YzEkO6l3rXAgMBAAECgYB99mhnB6piADOuddXv6\" +\n \"26NzUBTr4xbsYRTgSxHzwf50oFTTBSDuW+1IOBVyTWu94SSPyt0LllPbC8Di3sQSTnVGpSqAvEXknBMzIc0UO74Rn9\" +\n \"p3gZjEenPt1l77fIBa2nK06/rdsJCoE/1P1JSfM9w7LU1RsTmseYMLeJl5F79gQJBAO/BbAKqg1yzK7VijygvBoUrr\" +\n \"+rt2lbmKgcUQ/rxu8IIQk0M/xgJqSkXDXuOnboGM7sQSKfJAZUtT7xozvLzV7ECQQCJW59w7NIM0qZ/gIX2gcNZr1B\" +\n \"/V3zcGlolTDciRm+fnKGNt2EEDKnVL3swzbEfTCa48"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":227,"symbol":"ecdsaSignedByRsa","kind":"function","lang":"kotlin","code":"@Test\n fun ecdsaSignedByRsa() {\n val root =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .rsa2048()\n .build()\n val leaf =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .ecdsa256()\n .signedBy(root)\n .build()\n assertThat(root.certificate.sigAlgName).isEqualTo(\"SHA256WITHRSA\", ignoreCase = true)\n assertThat(leaf.certificate.sigAlgName).isEqualTo(\"SHA256WITHRSA\", ignoreCase = true)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":246,"symbol":"rsaSignedByEcdsa","kind":"function","lang":"kotlin","code":"@Test\n fun rsaSignedByEcdsa() {\n val root =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .ecdsa256()\n .build()\n val leaf =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .rsa2048()\n .signedBy(root)\n .build()\n assertThat(root.certificate.sigAlgName).isEqualTo(\"SHA256WITHECDSA\", ignoreCase = true)\n assertThat(leaf.certificate.sigAlgName).isEqualTo(\"SHA256WITHECDSA\", ignoreCase = true)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":265,"symbol":"decodeEcdsa256","kind":"function","lang":"kotlin","code":"@Test\n fun decodeEcdsa256() {\n // The certificate + private key below was generated programmatically:\n //\n // HeldCertificate heldCertificate = new HeldCertificate.Builder()\n // .validityInterval(5_000L, 10_000L)\n // .addSubjectAlternativeName(\"1.1.1.1\")\n // .addSubjectAlternativeName(\"cash.app\")\n // .serialNumber(42L)\n // .commonName(\"cash.app\")\n // .organizationalUnit(\"engineering\")\n // .ecdsa256()\n // .build();\n val certificatePem =\n \"\"\"\n |-----BEGIN CERTIFICATE-----\n |MIIBYTCCAQegAwIBAgIBKjAKBggqhkjOPQQDAjApMRQwEgYDVQQLEwtlbmdpbmVl\n |cmluZzERMA8GA1UEAxMIY2FzaC5hcHAwHhcNNzAwMTAxMDAwMDA1WhcNNzAwMTAx\n |MDAwMDEwWjApMRQwEgYDVQQLEwtlbmdpbmVlcmluZzERMA8GA1UEAxMIY2FzaC5h\n |cHAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASda8ChkQXxGELnrV/oBnIAx3dD\n |ocUOJfdz4pOJTP6dVQB9U3UBiW5uSX/MoOD0LL5zG3bVyL3Y6pDwKuYvfLNhoyAw\n |HjAcBgNVHREBAf8EEjAQhwQBAQEBgghjYXNoLmFwcDAKBggqhkjOPQQDAgNIADBF\n |AiAyHHg1N6YDDQiY920+cnI5XSZwEGhAtb9PYWO8bLmkcQIhAI2CfEZf3V/obmdT\n |yyaoEufLKVXhrTQhRfodTeigi4RX\n |-----END CERTIFICATE-----\n |\n \"\"\".trimMargin()\n val pkcs8Pem =\n \"\"\"\n |-----B"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":328,"symbol":"decodeRsa512","kind":"function","lang":"kotlin","code":"@Test\n fun decodeRsa512() {\n // The certificate + private key below was generated with OpenSSL. Never generate certificates\n // with MD5 or 512-bit RSA; that's insecure!\n //\n // openssl req \\\n // -x509 \\\n // -md5 \\\n // -nodes \\\n // -days 1 \\\n // -newkey rsa:512 \\\n // -keyout privateKey.key \\\n // -out certificate.crt\n val certificatePem =\n \"\"\"\n |-----BEGIN CERTIFICATE-----\n |MIIBFzCBwgIJAIVAqagcVN7/MA0GCSqGSIb3DQEBBAUAMBMxETAPBgNVBAMMCGNh\n |c2guYXBwMB4XDTE5MDkwNzAyMjg0NFoXDTE5MDkwODAyMjg0NFowEzERMA8GA1UE\n |AwwIY2FzaC5hcHAwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA8qAeoubm4mBTD9/J\n |ujLQkfk/fuJt/T5pVQ1vUEqxfcMw0zYgszQ5C2MiIl7M6JkTRKU01q9hVFCR83wX\n |zIdrLQIDAQABMA0GCSqGSIb3DQEBBAUAA0EAO1UpwhrkW3Ho1nZK/taoUQOoqz/n\n |HFVMtyEkm5gBDgz8nJXwb3zbegclQyH+kVou02S8zC5WWzEtd0R8S0LsTA==\n |-----END CERTIFICATE-----\n |\n \"\"\".trimMargin()\n val pkcs8Pem =\n \"\"\"\n |-----BEGIN PRIVATE KEY-----\n |MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA8qAeoubm4mBTD9/J\n |ujLQkfk/fuJt/T5pVQ1vUEqxfcMw0zYgszQ5C2MiIl7M6JkTRKU01q9hVFCR83wX\n |zIdrLQIDAQABAkEA7dEA9o/5k77y68ZhRv9z7QEwucBcKzQ3rsSCbWMpY"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":375,"symbol":"decodeRsa2048","kind":"function","lang":"kotlin","code":"@Test\n fun decodeRsa2048() {\n // The certificate + private key below was generated programmatically:\n //\n // HeldCertificate heldCertificate = new HeldCertificate.Builder()\n // .validityInterval(5_000L, 10_000L)\n // .addSubjectAlternativeName(\"1.1.1.1\")\n // .addSubjectAlternativeName(\"cash.app\")\n // .serialNumber(42L)\n // .commonName(\"cash.app\")\n // .organizationalUnit(\"engineering\")\n // .rsa2048()\n // .build();\n val certificatePem =\n \"\"\"\n |-----BEGIN CERTIFICATE-----\n |MIIC7TCCAdWgAwIBAgIBKjANBgkqhkiG9w0BAQsFADApMRQwEgYDVQQLEwtlbmdp\n |bmVlcmluZzERMA8GA1UEAxMIY2FzaC5hcHAwHhcNNzAwMTAxMDAwMDA1WhcNNzAw\n |MTAxMDAwMDEwWjApMRQwEgYDVQQLEwtlbmdpbmVlcmluZzERMA8GA1UEAxMIY2Fz\n |aC5hcHAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCaU+vrUPL0APGI\n |SXIuRX4xRrigXmGKx+GRPnWDWvGJwOm23Vpq/eZxQx6PbSUB1+QZzAwge20RpNAp\n |2lt5/qFtgUpEon2j06rd/0+ODqqVJX+6d3SpmF1fPfKUB6AOZbxEkaJpBSTavoTg\n |G2M/NMdjZjrcB3quNQcLg54mmI3HJm1zOd/8i2fZjvoiyVY30Inn2SmQsAotXw1u\n |aE/319bnR2sQlnkp6MJU0eLEtKyRif/IODvY+mtRYYdkFtoeT6qQPMIh+gF/H3to\n |5tjs3g59QC8k2TJDop4EFYUOwdrtnb8wUiBnLyURD1szASE2IO2Ftk1zaNOPKtrv\n"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":456,"symbol":"decodeWrongNumber","kind":"function","lang":"kotlin","code":"@Test\n fun decodeWrongNumber() {\n val certificatePem =\n \"\"\"\n |-----BEGIN CERTIFICATE-----\n |MIIBYTCCAQegAwIBAgIBKjAKBggqhkjOPQQDAjApMRQwEgYDVQQLEwtlbmdpbmVl\n |cmluZzERMA8GA1UEAxMIY2FzaC5hcHAwHhcNNzAwMTAxMDAwMDA1WhcNNzAwMTAx\n |MDAwMDEwWjApMRQwEgYDVQQLEwtlbmdpbmVlcmluZzERMA8GA1UEAxMIY2FzaC5h\n |cHAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASda8ChkQXxGELnrV/oBnIAx3dD\n |ocUOJfdz4pOJTP6dVQB9U3UBiW5uSX/MoOD0LL5zG3bVyL3Y6pDwKuYvfLNhoyAw\n |HjAcBgNVHREBAf8EEjAQhwQBAQEBgghjYXNoLmFwcDAKBggqhkjOPQQDAgNIADBF\n |AiAyHHg1N6YDDQiY920+cnI5XSZwEGhAtb9PYWO8bLmkcQIhAI2CfEZf3V/obmdT\n |yyaoEufLKVXhrTQhRfodTeigi4RX\n |-----END CERTIFICATE-----\n |\n \"\"\".trimMargin()\n val pkcs8Pem =\n \"\"\"\n |-----BEGIN PRIVATE KEY-----\n |MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCA7ODT0xhGSNn4ESj6J\n |lu/GJQZoU9lDrCPeUcQ28tzOWw==\n |-----END PRIVATE KEY-----\n |\n \"\"\".trimMargin()\n try {\n decode(certificatePem)\n fail()\n } catch (expected: IllegalArgumentException) {\n assertThat(expected.message).isEqualTo(\"string does not include a private key\")\n }\n try {\n decode(pkcs8Pem)\n fail()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":506,"symbol":"decodeWrongType","kind":"function","lang":"kotlin","code":"@Test\n fun decodeWrongType() {\n try {\n decode(\n \"\"\"\n |-----BEGIN CERTIFICATE-----\n |MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\n |-----END CERTIFICATE-----\n |-----BEGIN RSA PRIVATE KEY-----\n |sXPVYAsGD1wizrXX+wFaL3chtF1oG1Fx/jcsSsG6BA==\n |-----END RSA PRIVATE KEY-----\n |\n \"\"\".trimMargin(),\n )\n fail()\n } catch (expected: IllegalArgumentException) {\n assertThat(expected.message).isEqualTo(\"unexpected type: RSA PRIVATE KEY\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/HeldCertificateTest.kt","line":526,"symbol":"decodeMalformed","kind":"function","lang":"kotlin","code":"@Test\n fun decodeMalformed() {\n try {\n decode(\n \"\"\"\n |-----BEGIN CERTIFICATE-----\n |MIIBYTCCAQegAwIBAgIBKjAKBggqhkjOPQQDAjApMRQwEgYDVQQLEwtlbmdpbmVl\n |-----END CERTIFICATE-----\n |-----BEGIN PRIVATE KEY-----\n |MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCA7ODT0xhGSNn4ESj6J\n |lu/GJQZoU9lDrCPeUcQ28tzOWw==\n |-----END PRIVATE KEY-----\n |\n \"\"\".trimMargin(),\n )\n fail()\n } catch (expected: IllegalArgumentException) {\n if (!platform.isConscrypt()) {\n assertThat(expected.message).isEqualTo(\"failed to decode certificate\")\n }\n }\n try {\n decode(\n \"\"\"\n |-----BEGIN CERTIFICATE-----\n |MIIBYTCCAQegAwIBAgIBKjAKBggqhkjOPQQDAjApMRQwEgYDVQQLEwtlbmdpbmVl\n |cmluZzERMA8GA1UEAxMIY2FzaC5hcHAwHhcNNzAwMTAxMDAwMDA1WhcNNzAwMTAx\n |MDAwMDEwWjApMRQwEgYDVQQLEwtlbmdpbmVlcmluZzERMA8GA1UEAxMIY2FzaC5h\n |cHAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASda8ChkQXxGELnrV/oBnIAx3dD\n |ocUOJfdz4pOJTP6dVQB9U3UBiW5uSX/MoOD0LL5zG3bVyL3Y6pDwKuYvfLNhoyAw\n |HjAcBgNVHREBAf8EEjAQhwQBAQEBgghjYXNoLmFwcDAKBggqhkjOPQQDAgNIADBF\n |AiAyHHg1N6YDDQiY920+cnI5XSZwEGhAt"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":46,"symbol":"DerCertificatesTest","kind":"class","lang":"kotlin","code":"internal class DerCertificatesTest {\n private val stateOrProvince = \"1.3.6.1.4.1.311.60.2.1.2\"\n private val country = \"1.3.6.1.4.1.311.60.2.1.3\"\n private val certificateTransparencySignedCertificateTimestamps = \"1.3.6.1.4.1.11129.2.4.2\"\n private val authorityInfoAccess = \"1.3.6.1.5.5.7.1.1\"\n private val serialNumber = \"2.5.4.5\"\n private val countryName = \"2.5.4.6\"\n private val localityName = \"2.5.4.7\"\n private val stateOrProvinceName = \"2.5.4.8\"\n private val organizationName = \"2.5.4.10\"\n private val businessCategory = \"2.5.4.15\"\n private val subjectKeyIdentifier = \"2.5.29.14\"\n private val keyUsage = \"2.5.29.15\"\n private val crlDistributionPoints = \"2.5.29.31\"\n private val certificatePolicies = \"2.5.29.32\"\n private val authorityKeyIdentifier = \"2.5.29.35\"\n private val extendedKeyUsage = \"2.5.29.37\"\n\n @Test\n fun `decode simple certificate`() {\n val certificateBase64 =\n \"\"\"\n |MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\n |LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\n |CGNhc2guYXBwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCApFHhtrLan28q\n |+oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1wJ4YEoUCjDlPOtpht7XLbUmBnbIzN\n "} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":64,"symbol":"`decode simple certificate`","kind":"function","lang":"kotlin","code":"@Test\n fun `decode simple certificate`() {\n val certificateBase64 =\n \"\"\"\n |MIIBmjCCAQOgAwIBAgIBATANBgkqhkiG9w0BAQsFADATMREwDwYDVQQDEwhjYXNo\n |LmFwcDAeFw03MDAxMDEwMDAwMDBaFw03MDAxMDEwMDAwMDFaMBMxETAPBgNVBAMT\n |CGNhc2guYXBwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCApFHhtrLan28q\n |+oMolZuaTfWBA0V5aMIvq32BsloQu6LlvX1wJ4YEoUCjDlPOtpht7XLbUmBnbIzN\n |89XK4UJVM6Sqp3K88Km8z7gMrdrfTom/274wL25fICR+yDEQ5fUVYBmJAKXZF1ao\n |I0mIoEx0xFsQhIJ637v2MxJDupd61wIDAQABMA0GCSqGSIb3DQEBCwUAA4GBADam\n |UVwKh5Ry7es3OxtY3IgQunPUoLc0Gw71gl9Z+7t2FJ5VkcI5gWfutmdxZ2bDXCI8\n |8V0vxo1pHXnbBrnxhS/Z3TBerw8RyQqcaWOdp+pBXyIWmR+jHk9cHZCqQveTIBsY\n |jaA9VEhgdaVhxBsT2qzUNDsXlOzGsliznDfoqETb\n |\n \"\"\".trimMargin()\n val certificateByteString = certificateBase64.decodeBase64()!!\n val certificatePem =\n \"\"\"\n |-----BEGIN CERTIFICATE-----\n |$certificateBase64\n |-----END CERTIFICATE-----\n |\n \"\"\".trimMargin()\n\n val javaCertificate = certificatePem.decodeCertificatePem()\n val okHttpCertificate =\n CertificateAdapters.certificate\n .fromDer(certificateByteString)\n\n assertThat(okHttpCertificate.signatureValue.byteString)\n "} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":175,"symbol":"`decode CA certificate`","kind":"function","lang":"kotlin","code":"@Test\n fun `decode CA certificate`() {\n val certificateBase64 =\n \"\"\"\n |MIIE/zCCA+egAwIBAgIEUdNARDANBgkqhkiG9w0BAQsFADCBsDELMAkGA1UEBhMC\n |VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0\n |Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW\n |KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl\n |cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTE0MDkyMjE3MTQ1N1oXDTI0MDkyMzAx\n |MzE1M1owgb4xCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgw\n |JgYDVQQLEx9TZWUgd3d3LmVudHJ1c3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQL\n |EzAoYykgMjAwOSBFbnRydXN0LCBJbmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9u\n |bHkxMjAwBgNVBAMTKUVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0\n |eSAtIEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuoS2ctueDGvi\n |mekwAad26jK4lUEaydphTlhyz/72gnm/c2EGCqUn2LNf00VOHHLWTjLycooP94MZ\n |0GqAgABFHrDH55q/ElcnHKNoLwqHvWprDl5l8xx31dSFjXAhtLMy54ui1YY5ArG4\n |0kfO5MlJxDun3vtUfVe+8OhuwnmyOgtV4lCYFjITXC94VsHClLPyWuQnmp8k18bs\n |0JslguPMwsRFxYyXegZrKhGfqQpuSDtv29QRGUL3jwe/9VNfnD70FyzmaaxOMkxi\n |d+q36OW7NLwZi66cUee3frVTsTMi5W3PcDwa+uKbZ7aD9I2lr2JMTeBYrGQ0EgP4\n |to2UYySkcQIDAQABo4IBDzCCAQswDgYDVR0"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":410,"symbol":"`decode typical certificate`","kind":"function","lang":"kotlin","code":"@Test\n fun `decode typical certificate`() {\n val certificateBase64 =\n \"\"\"\n |MIIHHTCCBgWgAwIBAgIRAL5oALmpH7l6AAAAAFTRMh0wDQYJKoZIhvcNAQELBQAw\n |gboxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQL\n |Ex9TZWUgd3d3LmVudHJ1c3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykg\n |MjAxNCBFbnRydXN0LCBJbmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxLjAs\n |BgNVBAMTJUVudHJ1c3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBMMU0wHhcN\n |MjAwNDEzMTMyNTQ5WhcNMjEwNDEyMTM1NTQ5WjCBxTELMAkGA1UEBhMCVVMxEzAR\n |BgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBGcmFuY2lzY28xEzARBgsr\n |BgEEAYI3PAIBAxMCVVMxGTAXBgsrBgEEAYI3PAIBAhMIRGVsYXdhcmUxFTATBgNV\n |BAoTDFNxdWFyZSwgSW5jLjEdMBsGA1UEDxMUUHJpdmF0ZSBPcmdhbml6YXRpb24x\n |EDAOBgNVBAUTBzQ2OTk4NTUxETAPBgNVBAMTCGNhc2guYXBwMIIBIjANBgkqhkiG\n |9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqv2iSwWvb6ys/Ru4LtSz0R4wDaxklrFIGqdJ\n |rxxYdAdLQjyjHyJsfkNQdt2u4JYPRKaRTVYR9VIIeWUx/IjhZhsGPstPMjYT3cN1\n |VsphSDtrRVuxYlmkrvHar0HoadNr1MHd96Ach3g1QJlV8uyUJ7JXpPCNJ8EMiH52\n |n8bVzpjDjXwoYg3oOYvceteA0GJ5VWYACDgfmkeoaN1Cx31O9qcSiUk5AY8HfAnP\n |h20VcrnPo2dJmm7fkUKohIxrMjtpwi5esWhCBZJk50FveKrgdeSe4XxNL7uJPD89\n |SJtKmX7jxoNQSY3mrPssLdadwltUOh"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":715,"symbol":"`certificate attributes`","kind":"function","lang":"kotlin","code":"@Test\n fun `certificate attributes`() {\n val certificate =\n HeldCertificate\n .Builder()\n .certificateAuthority(3)\n .commonName(\"Jurassic Park\")\n .organizationalUnit(\"Gene Research\")\n .addSubjectAlternativeName(\"*.example.com\")\n .addSubjectAlternativeName(\"www.example.org\")\n .validityInterval(-1000L, 2000L)\n .serialNumber(17L)\n .build()\n\n val certificateByteString = certificate.certificate.encoded.toByteString()\n\n val okHttpCertificate =\n CertificateAdapters.certificate\n .fromDer(certificateByteString)\n\n assertThat(okHttpCertificate.basicConstraints).isEqualTo(\n Extension(\n id = BASIC_CONSTRAINTS,\n critical = true,\n value = BasicConstraints(true, 3),\n ),\n )\n assertThat(okHttpCertificate.commonName).isEqualTo(\"Jurassic Park\")\n assertThat(okHttpCertificate.organizationalUnitName).isEqualTo(\"Gene Research\")\n assertThat(okHttpCertificate.subjectAlternativeNames).isEqualTo(\n Extension(\n id = SUBJECT_ALTERNATIVE_NAME,\n critical = true,\n value =\n listOf(\n CertificateAdapters.generalNameDnsName to \"*.example.com"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":759,"symbol":"`missing subject alternative names`","kind":"function","lang":"kotlin","code":"@Test\n fun `missing subject alternative names`() {\n val certificate =\n HeldCertificate\n .Builder()\n .certificateAuthority(3)\n .commonName(\"Jurassic Park\")\n .organizationalUnit(\"Gene Research\")\n .validityInterval(-1000L, 2000L)\n .serialNumber(17L)\n .build()\n\n val certificateByteString = certificate.certificate.encoded.toByteString()\n\n val okHttpCertificate =\n CertificateAdapters.certificate\n .fromDer(certificateByteString)\n\n assertThat(okHttpCertificate.commonName).isEqualTo(\"Jurassic Park\")\n assertThat(okHttpCertificate.subjectAlternativeNames).isNull()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":781,"symbol":"`public key`","kind":"function","lang":"kotlin","code":"@Test\n fun `public key`() {\n val publicKeyBytes =\n (\n \"MIGJAoGBAICkUeG2stqfbyr6gyiVm5pN9YEDRXlowi+rfYGyWhC7ouW9fXAnhgShQKMOU8\" +\n \"62mG3tcttSYGdsjM3z1crhQlUzpKqncrzwqbzPuAyt2t9Oib/bvjAvbl8gJH7IMRDl9RVgGYkApdkXVqgjSYigTH\" +\n \"TEWxCEgnrfu/YzEkO6l3rXAgMBAAE=\"\n ).decodeBase64()!!\n val privateKeyBytes =\n (\n \"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAICkUeG2stqfbyr6gyiVm\" +\n \"5pN9YEDRXlowi+rfYGyWhC7ouW9fXAnhgShQKMOU862mG3tcttSYGdsjM3z1crhQlUzpKqncrzwqbzPuAyt2t9Oi\" +\n \"b/bvjAvbl8gJH7IMRDl9RVgGYkApdkXVqgjSYigTHTEWxCEgnrfu/YzEkO6l3rXAgMBAAECgYB99mhnB6piADOud\" +\n \"dXv626NzUBTr4xbsYRTgSxHzwf50oFTTBSDuW+1IOBVyTWu94SSPyt0LllPbC8Di3sQSTnVGpSqAvEXknBMzIc0U\" +\n \"O74Rn9p3gZjEenPt1l77fIBa2nK06/rdsJCoE/1P1JSfM9w7LU1RsTmseYMLeJl5F79gQJBAO/BbAKqg1yzK7Vij\" +\n \"ygvBoUrr+rt2lbmKgcUQ/rxu8IIQk0M/xgJqSkXDXuOnboGM7sQSKfJAZUtT7xozvLzV7ECQQCJW59w7NIM0qZ/g\" +\n \"IX2gcNZr1B/V3zcGlolTDciRm+fnKGNt2EEDKnVL3swzbEfTCa48IT0QKgZJqpXZERa26UHAkBLXmiP5f5pk8F3w\" +\n \"cXzAeVw06z3k1IB41Tu6MX+CyPU+TeudRlz+wV8b0zDvK+EnRKCCbptVFj1Bkt8lQ4JfcnhAkAk2Y3Gz+HySrkcT\" +\n \"7Cg12M/NkdUQnZe3jr88pt/+IGNwomc6Wt/m"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":828,"symbol":"`time before 2050 uses UTC_TIME`","kind":"function","lang":"kotlin","code":"@Test fun `time before 2050 uses UTC_TIME`() {\n val utcTimeDer = \"170d3439313233313233353935395a\".decodeHex()\n\n val decoded = CertificateAdapters.time.fromDer(utcTimeDer)\n val encoded = CertificateAdapters.time.toDer(decoded)\n\n assertThat(decoded).isEqualTo(date(\"2049-12-31T23:59:59.000+0000\").time)\n assertThat(encoded).isEqualTo(utcTimeDer)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":838,"symbol":"`time not before 2050 uses GENERALIZED_TIME`","kind":"function","lang":"kotlin","code":"@Test fun `time not before 2050 uses GENERALIZED_TIME`() {\n val generalizedTimeDer = \"180f32303530303130313030303030305a\".decodeHex()\n\n val decoded = CertificateAdapters.time.fromDer(generalizedTimeDer)\n val encoded = CertificateAdapters.time.toDer(decoded)\n\n assertThat(decoded).isEqualTo(date(\"2050-01-01T00:00:00.000+0000\").time)\n assertThat(encoded).isEqualTo(generalizedTimeDer)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":852,"symbol":"`can read GENERALIZED_TIME before 2050`","kind":"function","lang":"kotlin","doc":"Conforming applications MUST be able to process validity dates that are encoded in either UTCTime or GeneralizedTime.","code":"@Test fun `can read GENERALIZED_TIME before 2050`() {\n val generalizedTimeDer = \"180f32303439313233313233353935395a\".decodeHex()\n\n val decoded = CertificateAdapters.time.fromDer(generalizedTimeDer)\n assertThat(decoded).isEqualTo(date(\"2049-12-31T23:59:59.000+0000\").time)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":859,"symbol":"`time before 1950 uses GENERALIZED_TIME`","kind":"function","lang":"kotlin","code":"@Test fun `time before 1950 uses GENERALIZED_TIME`() {\n val generalizedTimeDer = \"180f31393439313233313233353935395a\".decodeHex()\n\n val decoded = CertificateAdapters.time.fromDer(generalizedTimeDer)\n val encoded = CertificateAdapters.time.toDer(decoded)\n\n assertThat(decoded).isEqualTo(date(\"1949-12-31T23:59:59.000+0000\").time)\n assertThat(encoded).isEqualTo(generalizedTimeDer)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":869,"symbol":"`reencode golden EC certificate`","kind":"function","lang":"kotlin","code":"@Test\n fun `reencode golden EC certificate`() {\n val certificateByteString =\n (\n \"MIIBkjCCATmgAwIBAgIBETAKBggqhkjOPQQDAjAwMRYwFAYDVQQLDA1HZW5lIFJ\" +\n \"lc2VhcmNoMRYwFAYDVQQDDA1KdXJhc3NpYyBQYXJrMB4XDTY5MTIzMTIzNTk1OVoXDTcwMDEwMTAwMDAwMlowMDE\" +\n \"WMBQGA1UECwwNR2VuZSBSZXNlYXJjaDEWMBQGA1UEAwwNSnVyYXNzaWMgUGFyazBZMBMGByqGSM49AgEGCCqGSM4\" +\n \"9AwEHA0IABKzhiMzpN+BkUSPLIKItu6O2iao2Pd7dxrvPdIs4xv9/2tPCVgUxevZ27qRcqZOnSd31ZP6B04vkXag\" +\n \"/awy2/iujRDBCMBIGA1UdEwEB/wQIMAYBAf8CAQMwLAYDVR0RAQH/BCIwIIINKi5leGFtcGxlLmNvbYIPd3d3LmV\" +\n \"4YW1wbGUub3JnMAoGCCqGSM49BAMCA0cAMEQCIHzutN/uzViLBXZ0slMqO5oz7ghgBgDbgo2ZyroVeQ/KAiB6Vqo\" +\n \"QXETXce4IZyv3mwGWYePlXU2yMXtezbNluXqUxQ==\"\n ).decodeBase64()!!\n\n val decoded = CertificateAdapters.certificate.fromDer(certificateByteString)\n val encoded = CertificateAdapters.certificate.toDer(decoded)\n\n assertThat(encoded).isEqualTo(certificateByteString)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":888,"symbol":"`reencode golden RSA certificate`","kind":"function","lang":"kotlin","code":"@Test\n fun `reencode golden RSA certificate`() {\n val certificateByteString =\n (\n \"MIIDHzCCAgegAwIBAgIBETANBgkqhkiG9w0BAQsFADAwMRYwFAYDVQQLDA1HZW5\" +\n \"lIFJlc2VhcmNoMRYwFAYDVQQDDA1KdXJhc3NpYyBQYXJrMB4XDTY5MTIzMTIzNTk1OVoXDTcwMDEwMTAwMDAwMlo\" +\n \"wMDEWMBQGA1UECwwNR2VuZSBSZXNlYXJjaDEWMBQGA1UEAwwNSnVyYXNzaWMgUGFyazCCASIwDQYJKoZIhvcNAQE\" +\n \"BBQADggEPADCCAQoCggEBAMfROxfCzmxIX5bDSZt6hstXALVeiywFFzTLW5UI0eKSDCliojmiKBcGR5ln7gVe6/t\" +\n \"me35J9n+Xe5LLmRogMo1CxCoyJxuDX4RrTpPGSepJCrvsBaMA7bQXc/9SbckPF4DYGbE5j3L6IyFU++8RKep/xjc\" +\n \"FAK4yhEgriDh7Gb+sbG6Mv2qTO4p6TR9WhMKXhMgHdk1JYyaSsJ+tSruKiPVmMAcQLBWgNez6MUIC1WVDyvCvfXI\" +\n \"pgsxosVCMtEDSllYe2lVta5tq1RkyzrvkazMEROK+0CVTfg8CadyBn83WTdWRsAX3qiwng8fQU3R4D9HuF/monfH\" +\n \"XuHsr53J+6v8CAwEAAaNEMEIwEgYDVR0TAQH/BAgwBgEB/wIBAzAsBgNVHREBAf8EIjAggg0qLmV4YW1wbGUuY29\" +\n \"tgg93d3cuZXhhbXBsZS5vcmcwDQYJKoZIhvcNAQELBQADggEBAC/+HbZBfVzazPARyI90ot3wzyEmCnXEotNhyl3\" +\n \"0QHZ6UGtJwvVBqY187xg9whytqdMFmadCp8FQT/dLRUn27gtQLOju4FfA3yetJ5oWjbgkaAr7YGP7Auz3o+w51aa\" +\n \"YpseFTZ/zABwnADSiHCIl35TGZJa1XOl32+RWn9VhT92zm3R12FMBovpMFaDckSJAi0jhMHm/QsFK66V0DZxdvl9\" +\n "} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":913,"symbol":"`private key info`","kind":"function","lang":"kotlin","code":"@Test\n fun `private key info`() {\n val privateKeyInfoByteString =\n (\n \"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAICkUeG2stqf\" +\n \"byr6gyiVm5pN9YEDRXlowi+rfYGyWhC7ouW9fXAnhgShQKMOU862mG3tcttSYGdsjM3z1crhQlUzpKqncrzwqbzP\" +\n \"uAyt2t9Oib/bvjAvbl8gJH7IMRDl9RVgGYkApdkXVqgjSYigTHTEWxCEgnrfu/YzEkO6l3rXAgMBAAECgYB99mhn\" +\n \"B6piADOuddXv626NzUBTr4xbsYRTgSxHzwf50oFTTBSDuW+1IOBVyTWu94SSPyt0LllPbC8Di3sQSTnVGpSqAvEX\" +\n \"knBMzIc0UO74Rn9p3gZjEenPt1l77fIBa2nK06/rdsJCoE/1P1JSfM9w7LU1RsTmseYMLeJl5F79gQJBAO/BbAKq\" +\n \"g1yzK7VijygvBoUrr+rt2lbmKgcUQ/rxu8IIQk0M/xgJqSkXDXuOnboGM7sQSKfJAZUtT7xozvLzV7ECQQCJW59w\" +\n \"7NIM0qZ/gIX2gcNZr1B/V3zcGlolTDciRm+fnKGNt2EEDKnVL3swzbEfTCa48IT0QKgZJqpXZERa26UHAkBLXmiP\" +\n \"5f5pk8F3wcXzAeVw06z3k1IB41Tu6MX+CyPU+TeudRlz+wV8b0zDvK+EnRKCCbptVFj1Bkt8lQ4JfcnhAkAk2Y3G\" +\n \"z+HySrkcT7Cg12M/NkdUQnZe3jr88pt/+IGNwomc6Wt/mJ4fcWONTkGMcfOZff1NQeNXDAZ6941XCsIVAkASOg02\" +\n \"PlVHLidU7mIE65swMM5/RNhS4aFjez/MwxFNOHaxc9VgCwYPXCLOtdf7AVovdyG0XWgbUXH+NyxKwboE\"\n ).decodeBase64()!!\n\n val decoded = CertificateAdapters.privateKeyInfo.fromDer(privateKeyInfoByteString)\n\n assertThat(dec"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":939,"symbol":"`RSA issuer and signature`","kind":"function","lang":"kotlin","code":"@Test\n fun `RSA issuer and signature`() {\n val root =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .rsa2048()\n .build()\n val certificate =\n HeldCertificate\n .Builder()\n .signedBy(root)\n .rsa2048()\n .build()\n\n val certificateByteString = certificate.certificate.encoded.toByteString()\n\n // Valid signature.\n val okHttpCertificate =\n CertificateAdapters.certificate\n .fromDer(certificateByteString)\n println(okHttpCertificate)\n assertThat(okHttpCertificate.checkSignature(root.keyPair.public)).isTrue()\n\n // Invalid signature.\n val okHttpCertificateWithBadSignature =\n okHttpCertificate.copy(\n signatureValue =\n okHttpCertificate.signatureValue.copy(\n byteString = okHttpCertificate.signatureValue.byteString.offByOneBit(),\n ),\n )\n assertThat(okHttpCertificateWithBadSignature.checkSignature(root.keyPair.public)).isFalse()\n\n // Wrong public key.\n assertThat(okHttpCertificate.checkSignature(certificate.keyPair.public)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":977,"symbol":"`EC issuer and signature`","kind":"function","lang":"kotlin","code":"@Test\n fun `EC issuer and signature`() {\n val root =\n HeldCertificate\n .Builder()\n .certificateAuthority(0)\n .ecdsa256()\n .build()\n val certificate =\n HeldCertificate\n .Builder()\n .signedBy(root)\n .ecdsa256()\n .build()\n\n val certificateByteString = certificate.certificate.encoded.toByteString()\n\n // Valid signature.\n val okHttpCertificate =\n CertificateAdapters.certificate\n .fromDer(certificateByteString)\n assertThat(okHttpCertificate.checkSignature(root.keyPair.public)).isTrue()\n\n // Invalid signature.\n val okHttpCertificateWithBadSignature =\n okHttpCertificate.copy(\n signatureValue =\n okHttpCertificate.signatureValue.copy(\n byteString = okHttpCertificate.signatureValue.byteString.offByOneBit(),\n ),\n )\n assertThat(okHttpCertificateWithBadSignature.checkSignature(root.keyPair.public)).isFalse()\n\n // Wrong public key.\n assertThat(okHttpCertificate.checkSignature(certificate.keyPair.public)).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":1018,"symbol":"`unsupported general name tag`","kind":"function","lang":"kotlin","doc":"We don't have API support for rfc822Name values (email addresses) in the subject alternative name, but we don't crash either.","code":"@Test\n fun `unsupported general name tag`() {\n val certificateByteString =\n (\n \"MIIFEDCCA/igAwIBAgIRAJK4dE9xztDibHKj2NXZJbIwDQYJKoZIhvcNAQELBQA\" +\n \"wSDELMAkGA1UEBhMCVVMxIDAeBgNVBAoTF1NlY3VyZVRydXN0IENvcnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmV\" +\n \"UcnVzdCBDQTAeFw0xNjA5MDExNDM1MzVaFw0yNDA5MjkxNDM1MzVaMIG1MQswCQYDVQQGEwJVUzERMA8GA1UECBM\" +\n \"ISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE9MDs\" +\n \"GA1UEAxM0VHJ1c3R3YXZlIE9yZ2FuaXphdGlvbiBWYWxpZGF0aW9uIFNIQTI1NiBDQSwgTGV2ZWwgMTEfMB0GCSq\" +\n \"GSIb3DQEJARYQY2FAdHJ1c3R3YXZlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOPTqIZSRwS\" +\n \"f47okE5omzktvKR7wgqdWzznOnpUOtgwmBPwNeCV1LSPMmlHPZxY4enTc0eyoxTxKv6g6ZUJe39U74eYnwTTT9sE\" +\n \"OnvNtE1pTzuB4Uf+YOPt4hZidTe5Ba8Q6dfz/Ht/vZXCbF3JFwrXxZEPbJaICap2grIqYHax+IEIYnBQC+WKh8Ng\" +\n \"Cn3LWS0j6cYSN8SEjFf5SEMGT1iNtttb/QC3JKJIeaVunUyvMfMjVFMntc7eZrFs6rp3wY1WFVI+fy17uOoUvfTH\" +\n \"8bvNAESUch7FyLh2zM8FVxqilT2XygHRwZeXtxJQozcDcvh4ItPb0uz6AFIYwn/8Gzp0CAwEAAaOCAYUwggGBMBI\" +\n \"GA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFMrOHRgDdx4c83xYsppwqAiAFvSuMA4GA1UdDwEB/wQEAwIBhjA\" +\n "} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":1065,"symbol":"encodeKey","kind":"function","lang":"kotlin","doc":"Converts public key bytes to SubjectPublicKeyInfo bytes.","code":"private fun encodeKey(\n algorithm: String,\n publicKeyBytes: ByteString,\n ): ByteString {\n val subjectPublicKeyInfo =\n SubjectPublicKeyInfo(\n algorithm = AlgorithmIdentifier(algorithm = algorithm, parameters = null),\n subjectPublicKey = BitString(publicKeyBytes, 0),\n )\n return CertificateAdapters.subjectPublicKeyInfo.toDer(subjectPublicKeyInfo)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":1078,"symbol":"offByOneBit","kind":"function","lang":"kotlin","doc":"Returns a byte string that differs from this one by one bit.","code":"private fun ByteString.offByOneBit(): ByteString =\n Buffer()\n .write(this, 0, size - 1)\n .writeByte(this[size - 1].toInt() xor 1)\n .readByteString()"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerCertificatesTest.kt","line":1084,"symbol":"date","kind":"function","lang":"kotlin","code":"private fun date(s: String): Date =\n SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\").run {\n timeZone = TimeZone.getTimeZone(\"GMT\")\n parse(s)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":44,"symbol":"DerTest","kind":"class","lang":"kotlin","code":"internal class DerTest {\n @Test fun `decode tag and length`() {\n val buffer =\n Buffer()\n .writeByte(0b00011110)\n .writeByte(0b10000001)\n .writeByte(0b11001001)\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_UNIVERSAL)\n assertThat(header.tag).isEqualTo(30)\n assertThat(header.constructed).isFalse()\n assertThat(header.length).isEqualTo(201)\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }\n\n @Test fun `decode length encoded with leading zero byte`() {\n val buffer =\n Buffer()\n .writeByte(0b00000010)\n .writeByte(0b10000010)\n .writeByte(0b00000000)\n .writeByte(0b01111111)\n\n val derReader = DerReader(buffer)\n\n assertFailsWith {\n derReader.read(\"test\") {}\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"invalid encoding for length\")\n }\n }\n\n @Test fun `decode length not encoded in shortest form possible`() {\n val buffer =\n Buffer()\n .writeByte(0b00000010)\n .writeByte(0b10000001)\n .writeByte(0b01111111)\n\n val derReader = D"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":45,"symbol":"`decode tag and length`","kind":"function","lang":"kotlin","code":"@Test fun `decode tag and length`() {\n val buffer =\n Buffer()\n .writeByte(0b00011110)\n .writeByte(0b10000001)\n .writeByte(0b11001001)\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_UNIVERSAL)\n assertThat(header.tag).isEqualTo(30)\n assertThat(header.constructed).isFalse()\n assertThat(header.length).isEqualTo(201)\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":64,"symbol":"`decode length encoded with leading zero byte`","kind":"function","lang":"kotlin","code":"@Test fun `decode length encoded with leading zero byte`() {\n val buffer =\n Buffer()\n .writeByte(0b00000010)\n .writeByte(0b10000010)\n .writeByte(0b00000000)\n .writeByte(0b01111111)\n\n val derReader = DerReader(buffer)\n\n assertFailsWith {\n derReader.read(\"test\") {}\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"invalid encoding for length\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":81,"symbol":"`decode length not encoded in shortest form possible`","kind":"function","lang":"kotlin","code":"@Test fun `decode length not encoded in shortest form possible`() {\n val buffer =\n Buffer()\n .writeByte(0b00000010)\n .writeByte(0b10000001)\n .writeByte(0b01111111)\n\n val derReader = DerReader(buffer)\n\n assertFailsWith {\n derReader.read(\"test\") {}\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"invalid encoding for length\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":97,"symbol":"`decode length equal to Long MAX_VALUE`","kind":"function","lang":"kotlin","code":"@Test fun `decode length equal to Long MAX_VALUE`() {\n val buffer =\n Buffer()\n .writeByte(0b00000010)\n .writeByte(0b10001000)\n .writeByte(0b01111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n\n val derReader = DerReader(buffer)\n\n val header = derReader.readHeader()\n assertThat(header.length).isEqualTo(Long.MAX_VALUE)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":117,"symbol":"`decode length overflowing Long`","kind":"function","lang":"kotlin","code":"@Test fun `decode length overflowing Long`() {\n val buffer =\n Buffer()\n .writeByte(0b00000010)\n .writeByte(0b10001000)\n .writeByte(0b10000000)\n .writeByte(0b00000000)\n .writeByte(0b00000000)\n .writeByte(0b00000000)\n .writeByte(0b00000000)\n .writeByte(0b00000000)\n .writeByte(0b00000000)\n .writeByte(0b00000000)\n\n val derReader = DerReader(buffer)\n\n assertFailsWith {\n derReader.read(\"test\") {}\n }.also { expected ->\n assertThat(expected.message).isEqualTo(\"length > Long.MAX_VALUE\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":140,"symbol":"`decode length encoded with more than 8 bytes`","kind":"function","lang":"kotlin","code":"@Test fun `decode length encoded with more than 8 bytes`() {\n val buffer =\n Buffer()\n .writeByte(0b00000010)\n .writeByte(0b10001001)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n .writeByte(0b11111111)\n\n val derReader = DerReader(buffer)\n\n assertFailsWith {\n derReader.read(\"test\") {}\n }.also { expected ->\n assertThat(expected.message)\n .isEqualTo(\"length encoded with more than 8 bytes is not supported\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":166,"symbol":"`encode tag and length`","kind":"function","lang":"kotlin","code":"@Test fun `encode tag and length`() {\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\"test\", tagClass = DerHeader.TAG_CLASS_UNIVERSAL, tag = 30L) {\n derWriter.writeUtf8(\"a\".repeat(201))\n }\n\n assertThat(buffer.readByteString(3)).isEqualTo(\"1e81c9\".decodeHex())\n assertThat(buffer.readUtf8()).isEqualTo(\"a\".repeat(201))\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":178,"symbol":"`decode primitive bit string`","kind":"function","lang":"kotlin","code":"@Test fun `decode primitive bit string`() {\n val buffer =\n Buffer()\n .write(\"0307040A3B5F291CD0\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(3L)\n assertThat(derReader.readBitString()).isEqualTo(BitString(\"0A3B5F291CD0\".decodeHex(), 4))\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":193,"symbol":"`encode primitive bit string`","kind":"function","lang":"kotlin","code":"@Test fun `encode primitive bit string`() {\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\"test\", tagClass = DerHeader.TAG_CLASS_UNIVERSAL, tag = 3L) {\n derWriter.writeBitString(BitString(\"0A3B5F291CD0\".decodeHex(), 4))\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"0307040A3B5F291CD0\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":204,"symbol":"`decode primitive string`","kind":"function","lang":"kotlin","code":"@Test fun `decode primitive string`() {\n val buffer =\n Buffer()\n .write(\"1A054A6F6E6573\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(26L)\n assertThat(header.constructed).isFalse()\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_UNIVERSAL)\n assertThat(derReader.readOctetString()).isEqualTo(\"Jones\".encodeUtf8())\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":221,"symbol":"`encode primitive string`","kind":"function","lang":"kotlin","code":"@Test fun `encode primitive string`() {\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\"test\", tagClass = DerHeader.TAG_CLASS_UNIVERSAL, tag = 26L) {\n derWriter.writeOctetString(\"Jones\".encodeUtf8())\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"1A054A6F6E6573\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":232,"symbol":"`decode implicit prefixed type`","kind":"function","lang":"kotlin","code":"@Test fun `decode implicit prefixed type`() {\n // Type1 ::= VisibleString\n // Type2 ::= [APPLICATION 3] IMPLICIT Type1\n val buffer =\n Buffer()\n .write(\"43054A6F6E6573\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(3L)\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_APPLICATION)\n assertThat(derReader.readOctetString()).isEqualTo(\"Jones\".encodeUtf8())\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":250,"symbol":"`encode implicit prefixed type`","kind":"function","lang":"kotlin","code":"@Test fun `encode implicit prefixed type`() {\n // Type1 ::= VisibleString\n // Type2 ::= [APPLICATION 3] IMPLICIT Type1\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\"test\", tagClass = DerHeader.TAG_CLASS_APPLICATION, tag = 3L) {\n derWriter.writeOctetString(\"Jones\".encodeUtf8())\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"43054A6F6E6573\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":263,"symbol":"`decode tagged implicit prefixed type`","kind":"function","lang":"kotlin","code":"@Test fun `decode tagged implicit prefixed type`() {\n // Type1 ::= VisibleString\n // Type2 ::= [APPLICATION 3] IMPLICIT Type1\n // Type3 ::= [2] Type2\n val buffer =\n Buffer()\n .write(\"A20743054A6F6E6573\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(2L)\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_CONTEXT_SPECIFIC)\n assertThat(header.length).isEqualTo(7L)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(3L)\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_APPLICATION)\n assertThat(header.length).isEqualTo(5L)\n assertThat(derReader.readOctetString()).isEqualTo(\"Jones\".encodeUtf8())\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":291,"symbol":"`encode tagged implicit prefixed type`","kind":"function","lang":"kotlin","code":"@Test fun `encode tagged implicit prefixed type`() {\n // Type1 ::= VisibleString\n // Type2 ::= [APPLICATION 3] IMPLICIT Type1\n // Type3 ::= [2] Type2\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\"test\", tagClass = DerHeader.TAG_CLASS_CONTEXT_SPECIFIC, tag = 2L) {\n derWriter.write(\"test\", tagClass = DerHeader.TAG_CLASS_APPLICATION, tag = 3L) {\n derWriter.writeOctetString(\"Jones\".encodeUtf8())\n }\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"A20743054A6F6E6573\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":307,"symbol":"`decode implicit tagged implicit prefixed type`","kind":"function","lang":"kotlin","code":"@Test fun `decode implicit tagged implicit prefixed type`() {\n // Type1 ::= VisibleString\n // Type2 ::= [APPLICATION 3] IMPLICIT Type1\n // Type3 ::= [2] Type2\n // Type4 ::= [APPLICATION 7] IMPLICIT Type3\n val buffer =\n Buffer()\n .write(\"670743054A6F6E6573\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(7L)\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_APPLICATION)\n assertThat(header.length).isEqualTo(7L)\n\n derReader.read(\"test\") { header2 ->\n assertThat(header2.tag).isEqualTo(3L)\n assertThat(header2.tagClass).isEqualTo(DerHeader.TAG_CLASS_APPLICATION)\n assertThat(header2.length).isEqualTo(5L)\n assertThat(derReader.readOctetString()).isEqualTo(\"Jones\".encodeUtf8())\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":336,"symbol":"`encode implicit tagged implicit prefixed type`","kind":"function","lang":"kotlin","code":"@Test fun `encode implicit tagged implicit prefixed type`() {\n // Type1 ::= VisibleString\n // Type2 ::= [APPLICATION 3] IMPLICIT Type1\n // Type3 ::= [2] Type2\n // Type4 ::= [APPLICATION 7] IMPLICIT Type3\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\"test\", tagClass = DerHeader.TAG_CLASS_APPLICATION, tag = 7L) {\n derWriter.write(\"test\", tagClass = DerHeader.TAG_CLASS_APPLICATION, tag = 3L) {\n derWriter.writeOctetString(\"Jones\".encodeUtf8())\n }\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"670743054A6F6E6573\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":353,"symbol":"`decode implicit implicit prefixed type`","kind":"function","lang":"kotlin","code":"@Test fun `decode implicit implicit prefixed type`() {\n // Type1 ::= VisibleString\n // Type2 ::= [APPLICATION 3] IMPLICIT Type1\n // Type5 ::= [2] IMPLICIT Type2\n val buffer =\n Buffer()\n .write(\"82054A6F6E6573\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(2L)\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_CONTEXT_SPECIFIC)\n assertThat(header.length).isEqualTo(5L)\n assertThat(derReader.readOctetString()).isEqualTo(\"Jones\".encodeUtf8())\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":373,"symbol":"`encode implicit implicit prefixed type`","kind":"function","lang":"kotlin","code":"@Test fun `encode implicit implicit prefixed type`() {\n // Type1 ::= VisibleString\n // Type2 ::= [APPLICATION 3] IMPLICIT Type1\n // Type5 ::= [2] IMPLICIT Type2\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\n name = \"test\",\n tagClass = DerHeader.TAG_CLASS_CONTEXT_SPECIFIC,\n tag = 2L,\n ) {\n derWriter.writeOctetString(\"Jones\".encodeUtf8())\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"82054A6F6E6573\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":391,"symbol":"`decode object identifier without adapter`","kind":"function","lang":"kotlin","code":"@Test fun `decode object identifier without adapter`() {\n val buffer =\n Buffer()\n .write(\"0603883703\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(6L)\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_UNIVERSAL)\n assertThat(header.length).isEqualTo(3L)\n assertThat(derReader.readObjectIdentifier()).isEqualTo(\"2.999.3\")\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":408,"symbol":"`encode object identifier without adapter`","kind":"function","lang":"kotlin","code":"@Test fun `encode object identifier without adapter`() {\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\n name = \"test\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 6L,\n ) {\n derWriter.writeObjectIdentifier(\"2.999.3\")\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"0603883703\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":423,"symbol":"`decode relative object identifier`","kind":"function","lang":"kotlin","code":"@Test fun `decode relative object identifier`() {\n val buffer =\n Buffer()\n .write(\"0D04c27B0302\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(13L)\n assertThat(header.tagClass).isEqualTo(DerHeader.TAG_CLASS_UNIVERSAL)\n assertThat(header.length).isEqualTo(4L)\n assertThat(derReader.readRelativeObjectIdentifier()).isEqualTo(\"8571.3.2\")\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":440,"symbol":"`encode relative object identifier`","kind":"function","lang":"kotlin","code":"@Test fun `encode relative object identifier`() {\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\n name = \"test\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 13L,\n ) {\n derWriter.writeRelativeObjectIdentifier(\"8571.3.2\")\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"0D04c27B0302\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":455,"symbol":"`decode raw sequence`","kind":"function","lang":"kotlin","code":"@Test fun `decode raw sequence`() {\n val buffer =\n Buffer()\n .write(\"300A\".decodeHex())\n .write(\"1505\".decodeHex())\n .write(\"Smith\".encodeUtf8())\n .write(\"01\".decodeHex())\n .write(\"01\".decodeHex())\n .write(\"FF\".decodeHex())\n\n val derReader = DerReader(buffer)\n\n derReader.read(\"test\") { header ->\n assertThat(header.tag).isEqualTo(16L)\n\n derReader.read(\"test\") { header2 ->\n assertThat(header2.tag).isEqualTo(21L)\n assertThat(derReader.readOctetString()).isEqualTo(\"Smith\".encodeUtf8())\n }\n\n derReader.read(\"test\") { header3 ->\n assertThat(header3.tag).isEqualTo(1L)\n assertThat(derReader.readBoolean()).isTrue()\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }\n\n assertThat(derReader.hasNext()).isFalse()\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":486,"symbol":"`encode raw sequence`","kind":"function","lang":"kotlin","code":"@Test fun `encode raw sequence`() {\n val buffer = Buffer()\n val derWriter = DerWriter(buffer)\n\n derWriter.write(\n name = \"test\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 16L,\n ) {\n derWriter.write(\n name = \"test\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 21L,\n ) {\n derWriter.writeOctetString(\"Smith\".encodeUtf8())\n }\n\n derWriter.write(\n name = \"test\",\n tagClass = DerHeader.TAG_CLASS_UNIVERSAL,\n tag = 1L,\n ) {\n derWriter.writeBoolean(true)\n }\n }\n\n assertThat(buffer.readByteString()).isEqualTo(\"300a1505536d6974680101ff\".decodeHex())\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":515,"symbol":"`sequence of`","kind":"function","lang":"kotlin","code":"@Test fun `sequence of`() {\n val bytes = \"3009020107020108020109\".decodeHex()\n val sequenceOf = listOf(7L, 8L, 9L)\n val adapter = Adapters.INTEGER_AS_LONG.asSequenceOf()\n assertThat(adapter.fromDer(bytes)).isEqualTo(sequenceOf)\n assertThat(adapter.toDer(sequenceOf)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":523,"symbol":"`point with only x set`","kind":"function","lang":"kotlin","code":"@Test fun `point with only x set`() {\n val bytes = \"3003800109\".decodeHex()\n val point = Point(9L, null)\n assertThat(Point.ADAPTER.fromDer(bytes)).isEqualTo(point)\n assertThat(Point.ADAPTER.toDer(point)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":530,"symbol":"`point with only y set`","kind":"function","lang":"kotlin","code":"@Test fun `point with only y set`() {\n val bytes = \"3003810109\".decodeHex()\n val point = Point(null, 9L)\n assertThat(Point.ADAPTER.fromDer(bytes)).isEqualTo(point)\n assertThat(Point.ADAPTER.toDer(point)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":537,"symbol":"`point with both fields set`","kind":"function","lang":"kotlin","code":"@Test fun `point with both fields set`() {\n val bytes = \"3006800109810109\".decodeHex()\n val point = Point(9L, 9L)\n assertThat(Point.ADAPTER.fromDer(bytes)).isEqualTo(point)\n assertThat(Point.ADAPTER.toDer(point)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":544,"symbol":"`implicit tag`","kind":"function","lang":"kotlin","code":"@Test fun `implicit tag`() {\n // [5] IMPLICIT UTF8String\n val bytes = \"85026869\".decodeHex()\n val implicitAdapter = Adapters.UTF8_STRING.withTag(tag = 5L)\n assertThat(implicitAdapter.fromDer(bytes)).isEqualTo(\"hi\")\n assertThat(implicitAdapter.toDer(\"hi\")).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":552,"symbol":"`encode implicit`","kind":"function","lang":"kotlin","code":"@Test fun `encode implicit`() {\n // [5] IMPLICIT UTF8String\n val implicitAdapter = Adapters.UTF8_STRING.withTag(tag = 5L)\n val string = implicitAdapter.fromDer(\"85026869\".decodeHex())\n assertThat(string).isEqualTo(\"hi\")\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":559,"symbol":"`explicit tag`","kind":"function","lang":"kotlin","code":"@Test fun `explicit tag`() {\n // [5] EXPLICIT UTF8String\n val bytes = \"A5040C026869\".decodeHex()\n val explicitAdapter = Adapters.UTF8_STRING.withExplicitBox(tag = 5L)\n assertThat(explicitAdapter.fromDer(bytes)).isEqualTo(\"hi\")\n assertThat(explicitAdapter.toDer(\"hi\")).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":567,"symbol":"`boolean`","kind":"function","lang":"kotlin","code":"@Test fun `boolean`() {\n val bytes = \"0101FF\".decodeHex()\n assertThat(Adapters.BOOLEAN.fromDer(bytes)).isEqualTo(true)\n assertThat(Adapters.BOOLEAN.toDer(true)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":573,"symbol":"`positive integer`","kind":"function","lang":"kotlin","code":"@Test fun `positive integer`() {\n val bytes = \"020132\".decodeHex()\n assertThat(Adapters.INTEGER_AS_LONG.toDer(50L)).isEqualTo(bytes)\n assertThat(Adapters.INTEGER_AS_LONG.fromDer(bytes)).isEqualTo(50L)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":579,"symbol":"`decode negative integer`","kind":"function","lang":"kotlin","code":"@Test fun `decode negative integer`() {\n val bytes = \"02019c\".decodeHex()\n assertThat(Adapters.INTEGER_AS_LONG.fromDer(bytes)).isEqualTo(-100L)\n assertThat(Adapters.INTEGER_AS_LONG.toDer(-100L)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":585,"symbol":"`five byte integer`","kind":"function","lang":"kotlin","code":"@Test fun `five byte integer`() {\n val bytes = \"02058000000001\".decodeHex()\n assertThat(Adapters.INTEGER_AS_LONG.fromDer(bytes)).isEqualTo(-549755813887L)\n assertThat(Adapters.INTEGER_AS_LONG.toDer(-549755813887L)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":591,"symbol":"`eight zeros`","kind":"function","lang":"kotlin","code":"@Test fun `eight zeros`() {\n val bytes = \"020200ff\".decodeHex()\n assertThat(Adapters.INTEGER_AS_LONG.fromDer(bytes)).isEqualTo(255)\n assertThat(Adapters.INTEGER_AS_LONG.toDer(255)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":597,"symbol":"`eight ones`","kind":"function","lang":"kotlin","code":"@Test fun `eight ones`() {\n val bytes = \"0201ff\".decodeHex()\n assertThat(Adapters.INTEGER_AS_LONG.toDer(-1L)).isEqualTo(bytes)\n assertThat(Adapters.INTEGER_AS_LONG.fromDer(bytes)).isEqualTo(-1L)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":603,"symbol":"`last byte all zeros`","kind":"function","lang":"kotlin","code":"@Test fun `last byte all zeros`() {\n val bytes = \"0202ff00\".decodeHex()\n assertThat(Adapters.INTEGER_AS_LONG.toDer(-256L)).isEqualTo(bytes)\n assertThat(Adapters.INTEGER_AS_LONG.fromDer(bytes)).isEqualTo(-256L)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":609,"symbol":"`max long`","kind":"function","lang":"kotlin","code":"@Test fun `max long`() {\n val bytes = \"02087fffffffffffffff\".decodeHex()\n assertThat(Adapters.INTEGER_AS_LONG.fromDer(bytes)).isEqualTo(Long.MAX_VALUE)\n assertThat(Adapters.INTEGER_AS_LONG.toDer(Long.MAX_VALUE)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":615,"symbol":"`min long`","kind":"function","lang":"kotlin","code":"@Test fun `min long`() {\n val bytes = \"02088000000000000000\".decodeHex()\n assertThat(Adapters.INTEGER_AS_LONG.fromDer(bytes)).isEqualTo(Long.MIN_VALUE)\n assertThat(Adapters.INTEGER_AS_LONG.toDer(Long.MIN_VALUE)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":621,"symbol":"`bigger than max long`","kind":"function","lang":"kotlin","code":"@Test fun `bigger than max long`() {\n val bytes = \"0209008000000000000001\".decodeHex()\n val bigInteger = BigInteger(\"9223372036854775809\")\n assertThat(Adapters.INTEGER_AS_BIG_INTEGER.fromDer(bytes)).isEqualTo(bigInteger)\n assertThat(Adapters.INTEGER_AS_BIG_INTEGER.toDer(bigInteger)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":628,"symbol":"`utf8 string`","kind":"function","lang":"kotlin","code":"@Test fun `utf8 string`() {\n val bytes = \"0c04f09f988e\".decodeHex()\n assertThat(Adapters.UTF8_STRING.fromDer(bytes)).isEqualTo(\"\\uD83D\\uDE0E\")\n assertThat(Adapters.UTF8_STRING.toDer(\"\\uD83D\\uDE0E\")).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":634,"symbol":"`ia5 string`","kind":"function","lang":"kotlin","code":"@Test fun `ia5 string`() {\n val bytes = \"16026869\".decodeHex()\n assertThat(Adapters.IA5_STRING.fromDer(bytes)).isEqualTo(\"hi\")\n assertThat(Adapters.IA5_STRING.toDer(\"hi\")).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":640,"symbol":"`printable string`","kind":"function","lang":"kotlin","code":"@Test fun `printable string`() {\n val bytes = \"13026869\".decodeHex()\n assertThat(Adapters.PRINTABLE_STRING.fromDer(bytes)).isEqualTo(\"hi\")\n assertThat(Adapters.PRINTABLE_STRING.toDer(\"hi\")).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":646,"symbol":"`cannot decode utc time with offset`","kind":"function","lang":"kotlin","code":"@Test fun `cannot decode utc time with offset`() {\n assertFailsWith {\n Adapters.UTC_TIME.fromDer(\"17113139313231353139303231302d30383030\".decodeHex())\n }.also { expected ->\n assertThat(expected).hasMessage(\"Failed to parse UTCTime 191215190210-0800\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":654,"symbol":"`utc time`","kind":"function","lang":"kotlin","code":"@Test fun `utc time`() {\n val bytes = \"170d3139313231363033303231305a\".decodeHex()\n val utcTime = date(\"2019-12-16T03:02:10.000+0000\").time\n assertThat(Adapters.UTC_TIME.toDer(utcTime)).isEqualTo(bytes)\n assertThat(Adapters.UTC_TIME.fromDer(bytes)).isEqualTo(utcTime)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":661,"symbol":"`cannot decode malformed utc time`","kind":"function","lang":"kotlin","code":"@Test fun `cannot decode malformed utc time`() {\n val bytes = \"170d3139313231362333303231305a\".decodeHex()\n assertFailsWith {\n Adapters.UTC_TIME.fromDer(bytes)\n }.also { expected ->\n assertThat(expected).hasMessage(\"Failed to parse UTCTime 191216#30210Z\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":670,"symbol":"`cannot decode generalized time with offset`","kind":"function","lang":"kotlin","code":"@Test fun `cannot decode generalized time with offset`() {\n assertFailsWith {\n Adapters.GENERALIZED_TIME.fromDer(\"181332303139313231353139303231302d30383030\".decodeHex())\n }.also { expected ->\n assertThat(expected).hasMessage(\"Failed to parse GeneralizedTime 20191215190210-0800\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":678,"symbol":"`generalized time`","kind":"function","lang":"kotlin","code":"@Test fun `generalized time`() {\n val bytes = \"180f32303139313231363033303231305a\".decodeHex()\n val generalizedTime = date(\"2019-12-16T03:02:10.000+0000\").time\n assertThat(Adapters.GENERALIZED_TIME.fromDer(bytes)).isEqualTo(generalizedTime)\n assertThat(Adapters.GENERALIZED_TIME.toDer(generalizedTime)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":685,"symbol":"`cannot decode malformed generalized time`","kind":"function","lang":"kotlin","code":"@Test fun `cannot decode malformed generalized time`() {\n val bytes = \"180f32303139313231362333303231305a\".decodeHex()\n assertFailsWith {\n Adapters.GENERALIZED_TIME.fromDer(bytes)\n }.also { expected ->\n assertThat(expected).hasMessage(\"Failed to parse GeneralizedTime 20191216#30210Z\")\n }\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":694,"symbol":"`parse utc time`","kind":"function","lang":"kotlin","code":"@Test fun `parse utc time`() {\n assertThat(Adapters.parseUtcTime(\"920521000000Z\"))\n .isEqualTo(date(\"1992-05-21T00:00:00.000+0000\").time)\n assertThat(Adapters.parseUtcTime(\"920622123421Z\"))\n .isEqualTo(date(\"1992-06-22T12:34:21.000+0000\").time)\n assertThat(Adapters.parseUtcTime(\"920722132100Z\"))\n .isEqualTo(date(\"1992-07-22T13:21:00.000+0000\").time)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":703,"symbol":"`decode utc time two digit year cutoff is 1950`","kind":"function","lang":"kotlin","code":"@Test fun `decode utc time two digit year cutoff is 1950`() {\n assertThat(Adapters.parseUtcTime(\"500101000000Z\"))\n .isEqualTo(date(\"1950-01-01T00:00:00.000+0000\").time)\n assertThat(Adapters.parseUtcTime(\"500101010000Z\"))\n .isEqualTo(date(\"1950-01-01T01:00:00.000+0000\").time)\n\n assertThat(Adapters.parseUtcTime(\"491231225959Z\"))\n .isEqualTo(date(\"2049-12-31T22:59:59.000+0000\").time)\n assertThat(Adapters.parseUtcTime(\"491231235959Z\"))\n .isEqualTo(date(\"2049-12-31T23:59:59.000+0000\").time)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":715,"symbol":"`encode utc time two digit year cutoff is 1950`","kind":"function","lang":"kotlin","code":"@Test fun `encode utc time two digit year cutoff is 1950`() {\n assertThat(Adapters.formatUtcTime(date(\"1950-01-01T00:00:00.000+0000\").time))\n .isEqualTo(\"500101000000Z\")\n assertThat(Adapters.formatUtcTime(date(\"2049-12-31T23:59:59.000+0000\").time))\n .isEqualTo(\"491231235959Z\")\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":722,"symbol":"`parse generalized time`","kind":"function","lang":"kotlin","code":"@Test fun `parse generalized time`() {\n assertThat(Adapters.parseGeneralizedTime(\"18990101000000Z\"))\n .isEqualTo(date(\"1899-01-01T00:00:00.000+0000\").time)\n assertThat(Adapters.parseGeneralizedTime(\"19500101000000Z\"))\n .isEqualTo(date(\"1950-01-01T00:00:00.000+0000\").time)\n assertThat(Adapters.parseGeneralizedTime(\"20500101000000Z\"))\n .isEqualTo(date(\"2050-01-01T00:00:00.000+0000\").time)\n assertThat(Adapters.parseGeneralizedTime(\"20990101000000Z\"))\n .isEqualTo(date(\"2099-01-01T00:00:00.000+0000\").time)\n assertThat(Adapters.parseGeneralizedTime(\"19920521000000Z\"))\n .isEqualTo(date(\"1992-05-21T00:00:00.000+0000\").time)\n assertThat(Adapters.parseGeneralizedTime(\"19920622123421Z\"))\n .isEqualTo(date(\"1992-06-22T12:34:21.000+0000\").time)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":737,"symbol":"`parse generalized time with fractional seconds`","kind":"function","lang":"kotlin","code":"@Disabled(\"fractional seconds are not implemented\")\n @Test\n fun `parse generalized time with fractional seconds`() {\n assertThat(Adapters.parseGeneralizedTime(\"19920722132100.3Z\"))\n .isEqualTo(date(\"1992-07-22T13:21:00.300+0000\").time)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":744,"symbol":"`format generalized time`","kind":"function","lang":"kotlin","code":"@Test fun `format generalized time`() {\n assertThat(Adapters.formatGeneralizedTime(date(\"1899-01-01T00:00:00.000+0000\").time))\n .isEqualTo(\"18990101000000Z\")\n assertThat(Adapters.formatGeneralizedTime(date(\"1950-01-01T00:00:00.000+0000\").time))\n .isEqualTo(\"19500101000000Z\")\n assertThat(Adapters.formatGeneralizedTime(date(\"2050-01-01T00:00:00.000+0000\").time))\n .isEqualTo(\"20500101000000Z\")\n assertThat(Adapters.formatGeneralizedTime(date(\"2099-01-01T00:00:00.000+0000\").time))\n .isEqualTo(\"20990101000000Z\")\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":755,"symbol":"`decode object identifier`","kind":"function","lang":"kotlin","code":"@Test fun `decode object identifier`() {\n val bytes = \"06092a864886f70d01010b\".decodeHex()\n assertThat(Adapters.OBJECT_IDENTIFIER.fromDer(bytes)).isEqualTo(SHA256_WITH_RSA_ENCRYPTION)\n assertThat(Adapters.OBJECT_IDENTIFIER.toDer(SHA256_WITH_RSA_ENCRYPTION)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-tls/src/test/java/okhttp3/tls/internal/der/DerTest.kt","line":761,"symbol":"`null value`","kind":"function","lang":"kotlin","code":"@Test fun `null value`() {\n val bytes = \"0500\".decodeHex()\n assertThat(Adapters.NULL.fromDer(bytes)).isNull()\n assertThat(Adapters.NULL.toDer(null)).isEqualTo(bytes)\n }"} {"repo":"okhttp","file":"okhttp-urlconnection/src/main/kotlin/okhttp3/JavaNetAuthenticator.kt","line":32,"symbol":"JavaNetAuthenticator","kind":"class","lang":"kotlin","doc":"``` val okHttpClient = OkHttpClient.Builder() .authenticator(okhttp3.Authenticator.Companion.JAVA_NET_AUTHENTICATOR) .build() ```","code":"@Deprecated(message = \"Use okhttp3.Authenticator.Companion.JAVA_NET_AUTHENTICATOR instead\")\nclass JavaNetAuthenticator : Authenticator {\n @Throws(IOException::class)\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? = JAVA_NET_AUTHENTICATOR.authenticate(route, response)\n}"} {"repo":"okhttp","file":"okhttp-urlconnection/src/main/kotlin/okhttp3/JavaNetAuthenticator.kt","line":34,"symbol":"authenticate","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? = JAVA_NET_AUTHENTICATOR.authenticate(route, response)"} {"repo":"okhttp","file":"okhttp-urlconnection/src/main/kotlin/okhttp3/JavaNetCookieJar.kt","line":29,"symbol":"JavaNetCookieJar","kind":"class","lang":"kotlin","doc":"This implementation delegates everything to [okhttp3.java.net.cookiejar.JavaNetCookieJar], which conforms to the package-naming limitations of JPMS. Callers should prefer to use [okhttp3.java.net.cookiejar.JavaNetCookieJar] directly.","code":"class JavaNetCookieJar private constructor(\n delegate: okhttp3.java.net.cookiejar.JavaNetCookieJar,\n) : CookieJar by delegate {\n constructor(cookieHandler: CookieHandler) : this(\n okhttp3.java.net.cookiejar.JavaNetCookieJar(\n cookieHandler,\n ),\n )\n}"} {"repo":"okhttp","file":"okhttp-zstd/src/main/kotlin/okhttp3/zstd/Zstd.kt","line":26,"symbol":"Zstd","kind":"object","lang":"kotlin","doc":"Support for Zstandard encoding. Use via the [CompressionInterceptor].","code":"object Zstd : CompressionInterceptor.DecompressionAlgorithm {\n override val encoding: String get() = \"zstd\"\n\n override fun decompress(compressedSource: BufferedSource): Source = compressedSource.zstdDecompress()\n}"} {"repo":"okhttp","file":"okhttp-zstd/src/main/kotlin/okhttp3/zstd/Zstd.kt","line":29,"symbol":"decompress","kind":"function","lang":"kotlin","code":"override fun decompress(compressedSource: BufferedSource): Source = compressedSource.zstdDecompress()"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorJavaTest.java","line":23,"symbol":"ZstdInterceptorJavaTest","kind":"class","lang":"java","code":"class ZstdInterceptorJavaTest {\n @Test\n public void testConstructor() {\n CompressionInterceptor interceptor = new CompressionInterceptor(\n Zstd.INSTANCE,\n Gzip.INSTANCE,\n Brotli.INSTANCE\n );\n }\n}"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorJavaTest.java","line":24,"symbol":"testConstructor","kind":"method","lang":"java","code":"@Test\n public void testConstructor() {\n CompressionInterceptor interceptor = new CompressionInterceptor(\n Zstd.INSTANCE,\n Gzip.INSTANCE,\n Brotli.INSTANCE\n );\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":42,"symbol":"ZstdInterceptorTest","kind":"class","lang":"kotlin","code":"class ZstdInterceptorTest {\n val zstdInterceptor = CompressionInterceptor(Zstd, Gzip)\n\n @Test\n fun testDecompressZstd() {\n val s = \"hello zstd world\".encodeUtf8().zstdCompress()\n\n val response =\n response(\"https://example.com/\", s) {\n header(\"Content-Encoding\", \"zstd\")\n }\n\n val decompressed = zstdInterceptor.decompress(response)\n assertThat(decompressed.header(\"Content-Encoding\")).isNull()\n\n val responseString = decompressed.body.string()\n assertThat(responseString).isEqualTo(\"hello zstd world\")\n }\n\n @Test\n fun testDecompressGzip() {\n val s = \"hello gzip world\".encodeUtf8().gzipCompress()\n\n val response =\n response(\"https://example.com/\", s) {\n header(\"Content-Encoding\", \"gzip\")\n }\n\n val decompressed = zstdInterceptor.decompress(response)\n assertThat(decompressed.header(\"Content-Encoding\")).isNull()\n\n val responseString = decompressed.body.string()\n assertThat(responseString).isEqualTo(\"hello gzip world\")\n }\n\n @Test\n fun testNoDecompress() {\n val s = \"hello not compressed world\".encodeUtf8()\n\n val response = response(\"https://example.com/\", s)\n\n val decompressed = zstdInterceptor.decompress(resp"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":45,"symbol":"testDecompressZstd","kind":"function","lang":"kotlin","code":"@Test\n fun testDecompressZstd() {\n val s = \"hello zstd world\".encodeUtf8().zstdCompress()\n\n val response =\n response(\"https://example.com/\", s) {\n header(\"Content-Encoding\", \"zstd\")\n }\n\n val decompressed = zstdInterceptor.decompress(response)\n assertThat(decompressed.header(\"Content-Encoding\")).isNull()\n\n val responseString = decompressed.body.string()\n assertThat(responseString).isEqualTo(\"hello zstd world\")\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":61,"symbol":"testDecompressGzip","kind":"function","lang":"kotlin","code":"@Test\n fun testDecompressGzip() {\n val s = \"hello gzip world\".encodeUtf8().gzipCompress()\n\n val response =\n response(\"https://example.com/\", s) {\n header(\"Content-Encoding\", \"gzip\")\n }\n\n val decompressed = zstdInterceptor.decompress(response)\n assertThat(decompressed.header(\"Content-Encoding\")).isNull()\n\n val responseString = decompressed.body.string()\n assertThat(responseString).isEqualTo(\"hello gzip world\")\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":77,"symbol":"testNoDecompress","kind":"function","lang":"kotlin","code":"@Test\n fun testNoDecompress() {\n val s = \"hello not compressed world\".encodeUtf8()\n\n val response = response(\"https://example.com/\", s)\n\n val decompressed = zstdInterceptor.decompress(response)\n assertThat(decompressed.header(\"Content-Encoding\")).isNull()\n\n val responseString = decompressed.body.string()\n assertThat(responseString).isEqualTo(\"hello not compressed world\")\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":90,"symbol":"testUnknownAlgorithm","kind":"function","lang":"kotlin","code":"@Test\n fun testUnknownAlgorithm() {\n val s = \"hello unknown algorithm world\".encodeUtf8()\n\n val response =\n response(\"https://example.com/\", s) {\n header(\"Content-Encoding\", \"deflate\")\n }\n\n val decompressed = zstdInterceptor.decompress(response)\n assertThat(decompressed.header(\"Content-Encoding\")).isEqualTo(\"deflate\")\n\n val responseString = decompressed.body.string()\n assertThat(responseString).isEqualTo(\"hello unknown algorithm world\")\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":106,"symbol":"testFailsDecompress","kind":"function","lang":"kotlin","code":"@Test\n fun testFailsDecompress() {\n val s = \"this is not valid zstd\".encodeUtf8()\n\n val response =\n response(\"https://example.com/\", s) {\n header(\"Content-Encoding\", \"zstd\")\n }\n\n val decompressed = zstdInterceptor.decompress(response)\n assertThat(decompressed.header(\"Content-Encoding\")).isNull()\n\n assertFailsWith {\n decompressed.body.string()\n }.also { ioe ->\n assertThat(ioe).hasMessage(\"zstd decompress failed: Unknown frame descriptor\")\n }\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":125,"symbol":"testSkipDecompressNoContentResponse","kind":"function","lang":"kotlin","code":"@Test\n fun testSkipDecompressNoContentResponse() {\n val response =\n response(\"https://example.com/\", EMPTY) {\n header(\"Content-Encoding\", \"zstd\")\n code(204)\n message(\"NO CONTENT\")\n }\n\n val same = zstdInterceptor.decompress(response)\n\n val responseString = same.body.string()\n assertThat(responseString).isEmpty()\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":140,"symbol":"zstdCompress","kind":"function","lang":"kotlin","code":"private fun ByteString.zstdCompress(): ByteString {\n val result = Buffer()\n result.zstdCompress().buffer().use {\n it.write(this@zstdCompress)\n }\n return result.readByteString()\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":148,"symbol":"gzipCompress","kind":"function","lang":"kotlin","code":"private fun ByteString.gzipCompress(): ByteString {\n val result = Buffer()\n (result as Sink).gzip().buffer().use {\n it.write(this@gzipCompress)\n }\n return result.readByteString()\n }"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdInterceptorTest.kt","line":156,"symbol":"response","kind":"function","lang":"kotlin","code":"private fun response(\n url: String,\n body: ByteString,\n fn: Response.Builder.() -> Unit = {},\n ): Response =\n Response\n .Builder()\n .body(body.toResponseBody(\"text/plain\".toMediaType()))\n .code(200)\n .message(\"OK\")\n .request(Request.Builder().url(url).build())\n .protocol(Protocol.HTTP_2)\n .apply(fn)\n .build()"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdTestMain.kt","line":22,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n val client =\n OkHttpClient\n .Builder()\n .addInterceptor(CompressionInterceptor(Zstd))\n .build()\n\n sendRequest(\"https://developers.facebook.com/docs/\", client)\n sendRequest(\"https://www.facebook.com/robots.txt\", client)\n sendRequest(\"https://www.instagram.com/robots.txt\", client)\n}"} {"repo":"okhttp","file":"okhttp-zstd/src/test/java/okhttp3/zstd/ZstdTestMain.kt","line":34,"symbol":"sendRequest","kind":"function","lang":"kotlin","code":"private fun sendRequest(\n url: String,\n client: OkHttpClient,\n) {\n val req = Request.Builder().url(url).build()\n\n client.newCall(req).execute().use {\n println(url)\n println(\"\"\"Content-Encoding: ${it.networkResponse?.header(\"Content-Encoding\")}\"\"\")\n println(\"| ${it.body.string().replace(\"\\n\", \"\\n| \")}\")\n }\n}"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/IssueReproductionTest.java","line":37,"symbol":"IssueReproductionTest","kind":"class","lang":"java","doc":"Simple test adaptable to show a failure in older versions of OkHttp or Android SDKs.","code":"@RunWith(AndroidJUnit4.class)\npublic class IssueReproductionTest {\n @Test public void getFailsWithoutAdditionalCert() throws IOException {\n OkHttpClient client = new OkHttpClient();\n\n sendRequest(client, \"https://google.com/robots.txt\");\n }\n\n private void sendRequest(OkHttpClient client, String url) throws IOException {\n Request request = new Request.Builder()\n .url(url)\n .build();\n try (Response response = client.newCall(request).execute()) {\n assertTrue(response.code() == 200 || response.code() == 404);\n assertEquals(Protocol.HTTP_2, response.protocol());\n\n for (Certificate c: response.handshake().peerCertificates()) {\n X509Certificate x = (X509Certificate) c;\n System.out.println(x.getSubjectDN());\n }\n }\n }\n}"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/IssueReproductionTest.java","line":39,"symbol":"getFailsWithoutAdditionalCert","kind":"method","lang":"java","code":"@Test public void getFailsWithoutAdditionalCert() throws IOException {\n OkHttpClient client = new OkHttpClient();\n\n sendRequest(client, \"https://google.com/robots.txt\");\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/IssueReproductionTest.java","line":45,"symbol":"sendRequest","kind":"method","lang":"java","code":"private void sendRequest(OkHttpClient client, String url) throws IOException {\n Request request = new Request.Builder()\n .url(url)\n .build();\n try (Response response = client.newCall(request).execute()) {\n assertTrue(response.code() == 200 || response.code() == 404);\n assertEquals(Protocol.HTTP_2, response.protocol());\n\n for (Certificate c: response.handshake().peerCertificates()) {\n X509Certificate x = (X509Certificate) c;\n System.out.println(x.getSubjectDN());\n }\n }\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/LetsEncryptTest.java","line":47,"symbol":"LetsEncryptTest","kind":"class","lang":"java","doc":"Let's Encrypt expiring root test. Read https://community.letsencrypt.org/t/mobile-client-workarounds-for-isrg-issue/137807 for background.","code":"@RunWith(AndroidJUnit4.class)\npublic class LetsEncryptTest {\n @Test public void getFailsWithoutAdditionalCert() throws IOException {\n OkHttpClient client = new OkHttpClient();\n\n boolean androidMorEarlier = Build.VERSION.SDK_INT <= 23;\n try {\n sendRequest(client, \"https://valid-isrgrootx1.letsencrypt.org/robots.txt\");\n if (androidMorEarlier) {\n fail();\n }\n } catch (SSLHandshakeException sslhe) {\n assertTrue(androidMorEarlier);\n }\n }\n\n @Test public void getPassesAdditionalCert() throws IOException, CertificateException {\n boolean androidMorEarlier = Build.VERSION.SDK_INT <= 23;\n\n OkHttpClient.Builder builder = new OkHttpClient.Builder();\n\n if (androidMorEarlier) {\n String isgCert =\n \"-----BEGIN CERTIFICATE-----\\n\" +\n \"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\\n\" +\n \"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\\n\" +\n \"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\\n\" +\n \"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\\n\" +\n \"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTD"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/LetsEncryptTest.java","line":49,"symbol":"getFailsWithoutAdditionalCert","kind":"method","lang":"java","code":"@Test public void getFailsWithoutAdditionalCert() throws IOException {\n OkHttpClient client = new OkHttpClient();\n\n boolean androidMorEarlier = Build.VERSION.SDK_INT <= 23;\n try {\n sendRequest(client, \"https://valid-isrgrootx1.letsencrypt.org/robots.txt\");\n if (androidMorEarlier) {\n fail();\n }\n } catch (SSLHandshakeException sslhe) {\n assertTrue(androidMorEarlier);\n }\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/LetsEncryptTest.java","line":63,"symbol":"getPassesAdditionalCert","kind":"method","lang":"java","code":"@Test public void getPassesAdditionalCert() throws IOException, CertificateException {\n boolean androidMorEarlier = Build.VERSION.SDK_INT <= 23;\n\n OkHttpClient.Builder builder = new OkHttpClient.Builder();\n\n if (androidMorEarlier) {\n String isgCert =\n \"-----BEGIN CERTIFICATE-----\\n\" +\n \"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\\n\" +\n \"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\\n\" +\n \"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\\n\" +\n \"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\\n\" +\n \"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\\n\" +\n \"MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\\n\" +\n \"h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\\n\" +\n \"0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\\n\" +\n \"A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\\n\" +\n \"T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\\n\" +\n \"B5T0Y3HsLuJvW5iB4YlcNH"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/LetsEncryptTest.java","line":130,"symbol":"sendRequest","kind":"method","lang":"java","code":"private void sendRequest(OkHttpClient client, String url) throws IOException {\n Request request = new Request.Builder()\n .url(url)\n .build();\n try (Response response = client.newCall(request).execute()) {\n assertTrue(response.code() == 200 || response.code() == 404);\n assertEquals(Protocol.HTTP_2, response.protocol());\n }\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":49,"symbol":"AndroidHttpEngineTest","kind":"class","lang":"kotlin","doc":"Android HttpEngine.","code":"@RunWith(AndroidJUnit4::class)\n@SdkSuppress(minSdkVersion = 34)\nclass AndroidHttpEngineTest {\n val context = InstrumentationRegistry.getInstrumentation().context\n\n val cacheDir =\n context.cacheDir.resolve(\"httpEngine\").also {\n it.mkdirs()\n }\n val engine =\n HttpEngine\n .Builder(context)\n .setEnableBrotli(true)\n .setStoragePath(cacheDir.path)\n .setEnableHttpCache(HttpEngine.Builder.HTTP_CACHE_DISK, 10_000_000)\n .setConnectionMigrationOptions(\n ConnectionMigrationOptions\n .Builder()\n .setDefaultNetworkMigration(ConnectionMigrationOptions.MIGRATION_OPTION_ENABLED)\n .setPathDegradationMigration(ConnectionMigrationOptions.MIGRATION_OPTION_ENABLED)\n .setAllowNonDefaultNetworkUsage(ConnectionMigrationOptions.MIGRATION_OPTION_ENABLED)\n .build(),\n ).setDnsOptions(\n DnsOptions\n .Builder()\n .setUseHttpStackDnsResolver(DnsOptions.DNS_OPTION_ENABLED)\n .setStaleDns(DnsOptions.DNS_OPTION_ENABLED)\n .setPersistHostCache(DnsOptions.DNS_OPTION_ENABLED)\n .build(),\n ).setQuicOptions(\n QuicOptions\n .Builder()\n .addAllowedQuicH"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":88,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@After\n fun tearDown() {\n engine.shutdown()\n cacheDir.deleteRecursively()\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":94,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test\n fun get() {\n val executor = Executors.newCachedThreadPool()\n\n val completableFuture = execute(engine, executor, \"https://google.com/robots.txt\")\n\n try {\n val response = completableFuture.get(10, TimeUnit.SECONDS)\n\n assertEquals(200, response.code)\n assertEquals(\"h3\", response.negotiatedProtocol)\n assertTrue(response.content.contains(\"Disallow\"))\n } catch (ee: ExecutionException) {\n throw ee.cause?.cause ?: ee.cause!!\n }\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":117,"symbol":"execute","kind":"function","lang":"kotlin","code":"private fun execute(\n engine: HttpEngine,\n executor: ExecutorService,\n url: String,\n ): CompletableFuture {\n val completableFuture = CompletableFuture()\n val buffer = Buffer()\n\n val req =\n engine\n .newUrlRequestBuilder(\n url,\n executor,\n object : Callback {\n override fun onRedirectReceived(\n request: UrlRequest,\n info: UrlResponseInfo,\n newLocationUrl: String,\n ) {\n println(\"request \" + info.httpStatusCode + \" \" + newLocationUrl)\n request.followRedirect()\n }\n\n override fun onResponseStarted(\n request: UrlRequest,\n info: UrlResponseInfo,\n ) {\n println(\"onResponseStarted ${info.headers.asMap} ${info.negotiatedProtocol}\")\n request.read(ByteBuffer.allocateDirect(4096 * 8))\n }\n\n override fun onReadCompleted(\n request: UrlRequest,\n info: UrlResponseInfo,\n byteBuffer: ByteBuffer,\n ) {\n println(\"onReadCompleted ${info.headers.asMap}\")\n byteBuffer.f"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":131,"symbol":"onRedirectReceived","kind":"function","lang":"kotlin","code":"override fun onRedirectReceived(\n request: UrlRequest,\n info: UrlResponseInfo,\n newLocationUrl: String,\n ) {\n println(\"request \" + info.httpStatusCode + \" \" + newLocationUrl)\n request.followRedirect()\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":140,"symbol":"onResponseStarted","kind":"function","lang":"kotlin","code":"override fun onResponseStarted(\n request: UrlRequest,\n info: UrlResponseInfo,\n ) {\n println(\"onResponseStarted ${info.headers.asMap} ${info.negotiatedProtocol}\")\n request.read(ByteBuffer.allocateDirect(4096 * 8))\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":148,"symbol":"onReadCompleted","kind":"function","lang":"kotlin","code":"override fun onReadCompleted(\n request: UrlRequest,\n info: UrlResponseInfo,\n byteBuffer: ByteBuffer,\n ) {\n println(\"onReadCompleted ${info.headers.asMap}\")\n byteBuffer.flip()\n buffer.write(byteBuffer)\n byteBuffer.clear()\n request.read(byteBuffer)\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":160,"symbol":"onSucceeded","kind":"function","lang":"kotlin","code":"override fun onSucceeded(\n request: UrlRequest,\n info: UrlResponseInfo,\n ) {\n println(\"onSucceeded ${info.headers.asMap}\")\n completableFuture.complete(Response(info.httpStatusCode, info.negotiatedProtocol, buffer.readUtf8()))\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":168,"symbol":"onFailed","kind":"function","lang":"kotlin","code":"override fun onFailed(\n request: UrlRequest,\n info: UrlResponseInfo?,\n error: HttpException,\n ) {\n println(\"onSucceeded ${info?.headers?.asMap}\")\n completableFuture.completeExceptionally(error)\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":177,"symbol":"onCanceled","kind":"function","lang":"kotlin","code":"override fun onCanceled(\n request: UrlRequest,\n info: UrlResponseInfo?,\n ) {\n completableFuture.completeExceptionally(CancellationException())\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/AndroidHttpEngineTest.kt","line":193,"symbol":"urlConnection","kind":"function","lang":"kotlin","code":"@Test\n fun urlConnection() {\n val conn = engine.openConnection(URL(\"https://google.com/robots.txt\")) as HttpURLConnection\n\n val text =\n conn.inputStream.use {\n it.bufferedReader().readText()\n }\n\n assertEquals(200, conn.responseCode)\n\n assertTrue(text.contains(\"Disallow\"))\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientHttp2Test.kt","line":45,"symbol":"ApacheHttpClientHttp2Test","kind":"class","lang":"kotlin","doc":"Simplified from https://hc.apache.org/httpcomponents-client-5.0.x/httpclient5/examples/AsyncClientTlsAlpn.java Mainly intended to verify behaviour of popular clients across Android versions, similar to observing Firefox or Chrome browser behaviour.","code":"@Ignore(\"Failing with Netty errors\")\nclass ApacheHttpClientHttp2Test {\n @Test\n fun testHttp2() {\n val client = HttpAsyncClients.createHttp2Default()\n\n client.use { client ->\n client.start()\n val request = SimpleHttpRequests.get(\"https://google.com/robots.txt\")\n val response = client.execute(request, LoggingCallback).get()\n\n println(\"Protocol ${response.version}\")\n println(\"Response ${response.code}\")\n println(\"${response.body.bodyText.substring(0, 20)}...\")\n\n Assert.assertEquals(ProtocolVersion(\"HTTP\", 2, 0), response.version)\n }\n }\n}"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientHttp2Test.kt","line":47,"symbol":"testHttp2","kind":"function","lang":"kotlin","code":"@Test\n fun testHttp2() {\n val client = HttpAsyncClients.createHttp2Default()\n\n client.use { client ->\n client.start()\n val request = SimpleHttpRequests.get(\"https://google.com/robots.txt\")\n val response = client.execute(request, LoggingCallback).get()\n\n println(\"Protocol ${response.version}\")\n println(\"Response ${response.code}\")\n println(\"${response.body.bodyText.substring(0, 20)}...\")\n\n Assert.assertEquals(ProtocolVersion(\"HTTP\", 2, 0), response.version)\n }\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientHttp2Test.kt","line":65,"symbol":"LoggingCallback","kind":"object","lang":"kotlin","code":"object LoggingCallback : FutureCallback {\n override fun completed(response: SimpleHttpResponse) {\n }\n\n override fun failed(ex: Exception) {\n println(\"Failed: $ex\")\n }\n\n override fun cancelled() {\n println(\"Cancelled\")\n }\n}"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientHttp2Test.kt","line":66,"symbol":"completed","kind":"function","lang":"kotlin","code":"override fun completed(response: SimpleHttpResponse) {\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientHttp2Test.kt","line":69,"symbol":"failed","kind":"function","lang":"kotlin","code":"override fun failed(ex: Exception) {\n println(\"Failed: $ex\")\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientHttp2Test.kt","line":73,"symbol":"cancelled","kind":"function","lang":"kotlin","code":"override fun cancelled() {\n println(\"Cancelled\")\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientTest.kt","line":33,"symbol":"ApacheHttpClientTest","kind":"class","lang":"kotlin","doc":"Apache HttpClient 5.x. https://hc.apache.org/httpcomponents-client-5.0.x/index.html","code":"@Ignore(\"Failing with Netty errors\")\n@RunWith(AndroidJUnit4::class)\nclass ApacheHttpClientTest {\n private var httpClient = HttpClients.createDefault()\n\n @After fun tearDown() {\n httpClient.close()\n }\n\n @Test fun get() {\n val request = HttpGet(\"https://google.com/robots.txt\")\n\n httpClient.execute(request).use { response ->\n assertEquals(200, response.code)\n // TODO enable ALPN later\n assertEquals(HttpVersion.HTTP_1_1, response.version)\n }\n }\n}"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientTest.kt","line":38,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@After fun tearDown() {\n httpClient.close()\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/ApacheHttpClientTest.kt","line":42,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test fun get() {\n val request = HttpGet(\"https://google.com/robots.txt\")\n\n httpClient.execute(request).use { response ->\n assertEquals(200, response.code)\n // TODO enable ALPN later\n assertEquals(HttpVersion.HTTP_1_1, response.version)\n }\n }"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/OkHttpClientTest.java","line":34,"symbol":"OkHttpClientTest","kind":"class","lang":"java","doc":"OkHttp. https://lysine.dev/okhttp/","code":"@RunWith(AndroidJUnit4.class)\npublic class OkHttpClientTest {\n @Test public void get() throws IOException {\n OkHttpClient client = new OkHttpClient();\n Request request = new Request.Builder()\n .url(\"https://google.com/robots.txt\")\n .build();\n try (Response response = client.newCall(request).execute()) {\n assertEquals(200, response.code());\n assertEquals(Protocol.HTTP_2, response.protocol());\n }\n }\n}"} {"repo":"okhttp","file":"regression-test/src/androidTest/java/okhttp/regression/compare/OkHttpClientTest.java","line":36,"symbol":"get","kind":"method","lang":"java","code":"@Test public void get() throws IOException {\n OkHttpClient client = new OkHttpClient();\n Request request = new Request.Builder()\n .url(\"https://google.com/robots.txt\")\n .build();\n try (Response response = client.newCall(request).execute()) {\n assertEquals(200, response.code());\n assertEquals(Protocol.HTTP_2, response.protocol());\n }\n }"} {"repo":"okhttp","file":"samples/android/src/androidTest/kotlin/okhttp3/sample/ech/EchClientTest.kt","line":32,"symbol":"EchClientTest","kind":"class","lang":"kotlin","code":"@RunWith(AndroidJUnit4::class)\n@SdkSuppress(minSdkVersion = 37)\nclass EchClientTest {\n @Test\n fun androidDns() {\n testEch(AndroidDns())\n }\n\n @Test\n fun dnsOverHttps() {\n testEch(\n DnsOverHttps.Builder()\n .client(OkHttpClient())\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .build()\n )\n }\n\n /**\n * ```\n * DNS record: cloudflare-ech.com/104.18.10.118\n * DNS record: cloudflare-ech.com/104.18.11.118\n * DNS record: cloudflare-ech.com/2606:4700::6812:a76\n * DNS record: cloudflare-ech.com/2606:4700::6812:b76\n * DNS record: ServiceMetadata{\n * cloudflare-ech.com,\n * alpnIds=[h3, h2, http/1.1],\n * ipAddressHints=[104.18.10.118, 104.18.11.118, 2606:4700::6812:a76, 2606:4700::6812:b76],\n * echConfigList=0045fe0d0041da002000201e8ee5aa34c64a7439d45dfd1157ab774e2f70abccceef4cd24ae0998286cc760004000100010012636c6f7564666c6172652d6563682e636f6d0000\n * }\n * Parsed ECHConfigList:\n * config[0]:\n * version: 0xfe0d\n * contents length: 65\n * config ID: 218\n * KEM ID: 0x0020\n * public key: 1e8ee5aa34c64a7439d45dfd1157ab774e2f70abccceef4cd24ae0998286cc76\n * maximum name length: 0\n * pub"} {"repo":"okhttp","file":"samples/android/src/androidTest/kotlin/okhttp3/sample/ech/EchClientTest.kt","line":35,"symbol":"androidDns","kind":"function","lang":"kotlin","code":"@Test\n fun androidDns() {\n testEch(AndroidDns())\n }"} {"repo":"okhttp","file":"samples/android/src/androidTest/kotlin/okhttp3/sample/ech/EchClientTest.kt","line":40,"symbol":"dnsOverHttps","kind":"function","lang":"kotlin","code":"@Test\n fun dnsOverHttps() {\n testEch(\n DnsOverHttps.Builder()\n .client(OkHttpClient())\n .url(\"https://1.1.1.1/dns-query\".toHttpUrl())\n .build()\n )\n }"} {"repo":"okhttp","file":"samples/android/src/androidTest/kotlin/okhttp3/sample/ech/EchClientTest.kt","line":76,"symbol":"testEch","kind":"function","lang":"kotlin","doc":"public name: cloudflare-ech.com cipher suites: KDF 0x0001, AEAD 0x0001 extensions: ```","code":"private fun testEch(dns: Dns) {\n val client = OkHttpClient.Builder()\n .dns(dns)\n .build()\n\n val echCheckRequest =\n Request(\"https://cloudflare-ech.com/cdn-cgi/trace\".toHttpUrl())\n\n client.newCall(echCheckRequest).execute().use { response ->\n assertThat(response.isSuccessful).isTrue()\n assertThat(response.body.string()).contains(\"sni=encrypted\")\n }\n }"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/ApacheHttpClientTest.kt","line":38,"symbol":"ApacheHttpClientTest","kind":"class","lang":"kotlin","doc":"Apache HttpClient 5.x. https://hc.apache.org/httpcomponents-client-5.0.x/index.html Baseline test if we ned to validate OkHttp behaviour against other popular clients.","code":"class ApacheHttpClientTest {\n private val httpClient = HttpClients.createDefault()\n\n @StartStop\n private val server = MockWebServer()\n\n @AfterEach\n fun tearDown() {\n httpClient.close()\n }\n\n @Test\n fun get() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"hello, Apache HttpClient 5.x\")\n .build(),\n )\n\n val request = HttpGet(server.url(\"/\").toUri())\n request.addHeader(\"Accept\", \"text/plain\")\n\n @Suppress(\"DEPRECATION\")\n httpClient.execute(request).use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(EntityUtils.toString(response.entity)).isEqualTo(\"hello, Apache HttpClient 5.x\")\n }\n\n val recorded = server.takeRequest()\n assertThat(recorded.headers[\"Accept\"]).isEqualTo(\"text/plain\")\n assertThat(\n recorded.headers[\"Accept-Encoding\"]?.split(\", \").orEmpty(),\n ).containsExactlyInAnyOrder(\n \"gzip\",\n \"x-gzip\",\n \"deflate\",\n )\n assertThat(recorded.headers[\"User-Agent\"]!!).startsWith(\"Apache-HttpClient/\")\n }\n}"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/ApacheHttpClientTest.kt","line":44,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach\n fun tearDown() {\n httpClient.close()\n }"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/ApacheHttpClientTest.kt","line":49,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test\n fun get() {\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"hello, Apache HttpClient 5.x\")\n .build(),\n )\n\n val request = HttpGet(server.url(\"/\").toUri())\n request.addHeader(\"Accept\", \"text/plain\")\n\n @Suppress(\"DEPRECATION\")\n httpClient.execute(request).use { response ->\n assertThat(response.code).isEqualTo(200)\n assertThat(EntityUtils.toString(response.entity)).isEqualTo(\"hello, Apache HttpClient 5.x\")\n }\n\n val recorded = server.takeRequest()\n assertThat(recorded.headers[\"Accept\"]).isEqualTo(\"text/plain\")\n assertThat(\n recorded.headers[\"Accept-Encoding\"]?.split(\", \").orEmpty(),\n ).containsExactlyInAnyOrder(\n \"gzip\",\n \"x-gzip\",\n \"deflate\",\n )\n assertThat(recorded.headers[\"User-Agent\"]!!).startsWith(\"Apache-HttpClient/\")\n }"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/JavaHttpClientTest.kt","line":41,"symbol":"JavaHttpClientTest","kind":"class","lang":"kotlin","doc":"Java HTTP Client. https://openjdk.java.net/groups/net/httpclient/intro.html Baseline test if we ned to validate OkHttp behaviour against other popular clients.","code":"class JavaHttpClientTest {\n @JvmField @RegisterExtension\n val platform = PlatformRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @Test fun get() {\n // Not available\n platform.expectFailureOnJdkVersion(8)\n\n val httpClient =\n HttpClient\n .newBuilder()\n .followRedirects(NORMAL)\n .build()\n\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"hello, Java HTTP Client\")\n .build(),\n )\n\n val request =\n HttpRequest\n .newBuilder(server.url(\"/\").toUri())\n .header(\"Accept\", \"text/plain\")\n .build()\n\n val response = httpClient.send(request, BodyHandlers.ofString())\n assertThat(response.statusCode()).isEqualTo(200)\n assertThat(response.body()).isEqualTo(\"hello, Java HTTP Client\")\n\n val recorded = server.takeRequest()\n assertThat(recorded.headers[\"Accept\"]).isEqualTo(\"text/plain\")\n assertThat(recorded.headers[\"Accept-Encoding\"]).isNull() // No built-in gzip.\n assertThat(recorded.headers[\"Connection\"]).isEqualTo(\"Upgrade, HTTP2-Settings\")\n assertThat(recorded.headers[\"HTTP2-Settings\"]).isNotNull()\n assertThat(recorded.headers[\"Upgrade\"]).isEqualTo(\"h2c\") // HTTP/2"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/JavaHttpClientTest.kt","line":48,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test fun get() {\n // Not available\n platform.expectFailureOnJdkVersion(8)\n\n val httpClient =\n HttpClient\n .newBuilder()\n .followRedirects(NORMAL)\n .build()\n\n server.enqueue(\n MockResponse\n .Builder()\n .body(\"hello, Java HTTP Client\")\n .build(),\n )\n\n val request =\n HttpRequest\n .newBuilder(server.url(\"/\").toUri())\n .header(\"Accept\", \"text/plain\")\n .build()\n\n val response = httpClient.send(request, BodyHandlers.ofString())\n assertThat(response.statusCode()).isEqualTo(200)\n assertThat(response.body()).isEqualTo(\"hello, Java HTTP Client\")\n\n val recorded = server.takeRequest()\n assertThat(recorded.headers[\"Accept\"]).isEqualTo(\"text/plain\")\n assertThat(recorded.headers[\"Accept-Encoding\"]).isNull() // No built-in gzip.\n assertThat(recorded.headers[\"Connection\"]).isEqualTo(\"Upgrade, HTTP2-Settings\")\n assertThat(recorded.headers[\"HTTP2-Settings\"]).isNotNull()\n assertThat(recorded.headers[\"Upgrade\"]).isEqualTo(\"h2c\") // HTTP/2 over plaintext!\n assertThat(recorded.headers[\"User-Agent\"]!!).matches(Regex(\"Java-http-client/.*\"))\n }"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/JettyHttpClientTest.kt","line":37,"symbol":"JettyHttpClientTest","kind":"class","lang":"kotlin","doc":"Jetty HTTP client. https://www.eclipse.org/jetty/documentation/current/http-client.html Baseline test if we ned to validate OkHttp behaviour against other popular clients.","code":"class JettyHttpClientTest {\n private val client = HttpClient()\n\n @StartStop\n private val server = MockWebServer()\n\n @BeforeEach fun setUp() {\n client.start()\n }\n\n @AfterEach fun tearDown() {\n client.stop()\n }\n\n @Test fun get() {\n server.enqueue(MockResponse(body = \"hello, Jetty HTTP Client\"))\n\n val request =\n client\n .newRequest(server.url(\"/\").toUri())\n .header(\"Accept\", \"text/plain\")\n val response = request.send()\n assertThat(response.status).isEqualTo(200)\n assertThat(response.contentAsString).isEqualTo(\"hello, Jetty HTTP Client\")\n\n val recorded = server.takeRequest()\n assertThat(recorded.headers[\"Accept\"]).isEqualTo(\"text/plain\")\n assertThat(recorded.headers[\"Accept-Encoding\"]).isEqualTo(\"gzip\")\n assertThat(recorded.headers[\"Connection\"]).isNull()\n assertThat(recorded.headers[\"User-Agent\"]!!).matches(Regex(\"Jetty/.*\"))\n }\n}"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/JettyHttpClientTest.kt","line":43,"symbol":"setUp","kind":"function","lang":"kotlin","code":"@BeforeEach fun setUp() {\n client.start()\n }"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/JettyHttpClientTest.kt","line":47,"symbol":"tearDown","kind":"function","lang":"kotlin","code":"@AfterEach fun tearDown() {\n client.stop()\n }"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/JettyHttpClientTest.kt","line":51,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test fun get() {\n server.enqueue(MockResponse(body = \"hello, Jetty HTTP Client\"))\n\n val request =\n client\n .newRequest(server.url(\"/\").toUri())\n .header(\"Accept\", \"text/plain\")\n val response = request.send()\n assertThat(response.status).isEqualTo(200)\n assertThat(response.contentAsString).isEqualTo(\"hello, Jetty HTTP Client\")\n\n val recorded = server.takeRequest()\n assertThat(recorded.headers[\"Accept\"]).isEqualTo(\"text/plain\")\n assertThat(recorded.headers[\"Accept-Encoding\"]).isEqualTo(\"gzip\")\n assertThat(recorded.headers[\"Connection\"]).isNull()\n assertThat(recorded.headers[\"User-Agent\"]!!).matches(Regex(\"Jetty/.*\"))\n }"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/OkHttpClientTest.kt","line":35,"symbol":"OkHttpClientTest","kind":"class","lang":"kotlin","doc":"OkHttp. https://lysine.dev/okhttp/","code":"class OkHttpClientTest {\n @JvmField @RegisterExtension\n val platform = PlatformRule()\n\n @StartStop\n private val server = MockWebServer()\n\n @Test fun get() {\n server.enqueue(MockResponse(body = \"hello, OkHttp\"))\n\n val client = OkHttpClient()\n\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"Accept\", \"text/plain\")\n .build()\n val response = client.newCall(request).execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"hello, OkHttp\")\n\n val recorded = server.takeRequest()\n assertThat(recorded.headers[\"Accept\"]).isEqualTo(\"text/plain\")\n assertThat(recorded.headers[\"Accept-Encoding\"]).isEqualTo(\"gzip\")\n assertThat(recorded.headers[\"Connection\"]).isEqualTo(\"Keep-Alive\")\n assertThat(recorded.headers[\"User-Agent\"]!!).matches(Regex(\"okhttp/.*\"))\n }\n}"} {"repo":"okhttp","file":"samples/compare/src/test/kotlin/okhttp3/compare/OkHttpClientTest.kt","line":42,"symbol":"get","kind":"function","lang":"kotlin","code":"@Test fun get() {\n server.enqueue(MockResponse(body = \"hello, OkHttp\"))\n\n val client = OkHttpClient()\n\n val request =\n Request\n .Builder()\n .url(server.url(\"/\"))\n .header(\"Accept\", \"text/plain\")\n .build()\n val response = client.newCall(request).execute()\n assertThat(response.code).isEqualTo(200)\n assertThat(response.body.string()).isEqualTo(\"hello, OkHttp\")\n\n val recorded = server.takeRequest()\n assertThat(recorded.headers[\"Accept\"]).isEqualTo(\"text/plain\")\n assertThat(recorded.headers[\"Accept-Encoding\"]).isEqualTo(\"gzip\")\n assertThat(recorded.headers[\"Connection\"]).isEqualTo(\"Keep-Alive\")\n assertThat(recorded.headers[\"User-Agent\"]!!).matches(Regex(\"okhttp/.*\"))\n }"} {"repo":"okhttp","file":"samples/crawler/src/main/java/okhttp3/sample/Crawler.java","line":43,"symbol":"Crawler","kind":"class","lang":"java","doc":"Fetches HTML from a requested URL, follows the links, and repeats.","code":"public final class Crawler {\n private final OkHttpClient client;\n private final Set fetchedUrls = Collections.synchronizedSet(new LinkedHashSet<>());\n private final BlockingQueue queue;\n private final ConcurrentHashMap hostnames = new ConcurrentHashMap<>();\n private final int hostLimit;\n\n public Crawler(OkHttpClient client, int queueLimit, int hostLimit) {\n this.client = client;\n this.queue = new LinkedBlockingQueue<>(queueLimit);\n this.hostLimit = hostLimit;\n }\n\n private void parallelDrainQueue(int threadCount) {\n ExecutorService executor = Executors.newFixedThreadPool(threadCount);\n for (int i = 0; i < threadCount; i++) {\n executor.execute(() -> {\n try {\n drainQueue();\n } catch (Throwable e) {\n e.printStackTrace();\n }\n });\n }\n executor.shutdown();\n }\n\n private void drainQueue() throws Exception {\n for (HttpUrl url; (url = queue.take()) != null; ) {\n if (!fetchedUrls.add(url)) {\n continue;\n }\n\n Thread currentThread = Thread.currentThread();\n String originalName = currentThread.getName();\n currentThread.setName(\"Crawler \" + url)"} {"repo":"okhttp","file":"samples/crawler/src/main/java/okhttp3/sample/Crawler.java","line":50,"symbol":"Crawler","kind":"constructor","lang":"java","code":"public Crawler(OkHttpClient client, int queueLimit, int hostLimit) {\n this.client = client;\n this.queue = new LinkedBlockingQueue<>(queueLimit);\n this.hostLimit = hostLimit;\n }"} {"repo":"okhttp","file":"samples/crawler/src/main/java/okhttp3/sample/Crawler.java","line":56,"symbol":"parallelDrainQueue","kind":"method","lang":"java","code":"private void parallelDrainQueue(int threadCount) {\n ExecutorService executor = Executors.newFixedThreadPool(threadCount);\n for (int i = 0; i < threadCount; i++) {\n executor.execute(() -> {\n try {\n drainQueue();\n } catch (Throwable e) {\n e.printStackTrace();\n }\n });\n }\n executor.shutdown();\n }"} {"repo":"okhttp","file":"samples/crawler/src/main/java/okhttp3/sample/Crawler.java","line":70,"symbol":"drainQueue","kind":"method","lang":"java","code":"private void drainQueue() throws Exception {\n for (HttpUrl url; (url = queue.take()) != null; ) {\n if (!fetchedUrls.add(url)) {\n continue;\n }\n\n Thread currentThread = Thread.currentThread();\n String originalName = currentThread.getName();\n currentThread.setName(\"Crawler \" + url);\n try {\n fetch(url);\n } catch (IOException e) {\n System.out.printf(\"XXX: %s %s%n\", url, e);\n } finally {\n currentThread.setName(originalName);\n }\n }\n }"} {"repo":"okhttp","file":"samples/crawler/src/main/java/okhttp3/sample/Crawler.java","line":89,"symbol":"fetch","kind":"method","lang":"java","code":"public void fetch(HttpUrl url) throws IOException {\n // Skip hosts that we've visited many times.\n AtomicInteger hostnameCount = new AtomicInteger();\n AtomicInteger previous = hostnames.putIfAbsent(url.host(), hostnameCount);\n if (previous != null) hostnameCount = previous;\n if (hostnameCount.getAndIncrement() >= hostLimit) return;\n\n Request request = new Request.Builder()\n .url(url)\n .build();\n try (Response response = client.newCall(request).execute()) {\n String responseSource = response.networkResponse() != null ? (\"(network: \"\n + response.networkResponse().code()\n + \" over \"\n + response.protocol()\n + \")\") : \"(cache)\";\n int responseCode = response.code();\n\n System.out.printf(\"%03d: %s %s%n\", responseCode, url, responseSource);\n\n String contentType = response.header(\"Content-Type\");\n if (responseCode != 200 || contentType == null) {\n return;\n }\n\n MediaType mediaType = MediaType.parse(contentType);\n if (mediaType == null || !mediaType.subtype().equalsIgnoreCase(\"html\")) {\n return;\n }\n\n Document document = Jsoup.parse(response.body().string(), url.t"} {"repo":"okhttp","file":"samples/crawler/src/main/java/okhttp3/sample/Crawler.java","line":130,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String[] args) throws IOException {\n if (args.length != 2) {\n System.out.println(\"Usage: Crawler \");\n return;\n }\n\n int threadCount = 20;\n int queueLimit = 1000;\n int hostLimit = 25;\n long cacheByteCount = 1024L * 1024L * 100L;\n\n Cache cache = new Cache(new File(args[0]), cacheByteCount);\n OkHttpClient client = new OkHttpClient.Builder()\n .cache(cache)\n .callTimeout(5, TimeUnit.SECONDS)\n .build();\n\n Crawler crawler = new Crawler(client, queueLimit, hostLimit);\n crawler.queue.add(HttpUrl.get(args[1]));\n crawler.parallelDrainQueue(threadCount);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/guide/GetExample.java","line":23,"symbol":"GetExample","kind":"class","lang":"java","code":"public class GetExample {\n final OkHttpClient client = new OkHttpClient();\n\n String run(String url) throws IOException {\n Request request = new Request.Builder()\n .url(url)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n return response.body().string();\n }\n }\n\n public static void main(String[] args) throws IOException {\n GetExample example = new GetExample();\n String response = example.run(\"https://raw.github.com/lysine-dev/okhttp/master/README.md\");\n System.out.println(response);\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/guide/GetExample.java","line":26,"symbol":"run","kind":"method","lang":"java","code":"String run(String url) throws IOException {\n Request request = new Request.Builder()\n .url(url)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n return response.body().string();\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/guide/GetExample.java","line":36,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String[] args) throws IOException {\n GetExample example = new GetExample();\n String response = example.run(\"https://raw.github.com/lysine-dev/okhttp/master/README.md\");\n System.out.println(response);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/guide/PostExample.java","line":25,"symbol":"PostExample","kind":"class","lang":"java","code":"public class PostExample {\n public static final MediaType JSON = MediaType.get(\"application/json; charset=utf-8\");\n\n final OkHttpClient client = new OkHttpClient();\n\n String post(String url, String json) throws IOException {\n RequestBody body = RequestBody.create(json, JSON);\n Request request = new Request.Builder()\n .url(url)\n .post(body)\n .build();\n try (Response response = client.newCall(request).execute()) {\n return response.body().string();\n }\n }\n\n String bowlingJson(String player1, String player2) {\n return \"{'winCondition':'HIGH_SCORE',\"\n + \"'name':'Bowling',\"\n + \"'round':4,\"\n + \"'lastSaved':1367702411696,\"\n + \"'dateStarted':1367702378785,\"\n + \"'players':[\"\n + \"{'name':'\" + player1 + \"','history':[10,8,6,7,8],'color':-13388315,'total':39},\"\n + \"{'name':'\" + player2 + \"','history':[6,10,5,10,10],'color':-48060,'total':41}\"\n + \"]}\";\n }\n\n public static void main(String[] args) throws IOException {\n PostExample example = new PostExample();\n String json = example.bowlingJson(\"Jesse\", \"Jake\");\n String response = example.post(\"http://www.roundsapp.com/post\", json);\n S"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/guide/PostExample.java","line":30,"symbol":"post","kind":"method","lang":"java","code":"String post(String url, String json) throws IOException {\n RequestBody body = RequestBody.create(json, JSON);\n Request request = new Request.Builder()\n .url(url)\n .post(body)\n .build();\n try (Response response = client.newCall(request).execute()) {\n return response.body().string();\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/guide/PostExample.java","line":41,"symbol":"bowlingJson","kind":"method","lang":"java","code":"String bowlingJson(String player1, String player2) {\n return \"{'winCondition':'HIGH_SCORE',\"\n + \"'name':'Bowling',\"\n + \"'round':4,\"\n + \"'lastSaved':1367702411696,\"\n + \"'dateStarted':1367702378785,\"\n + \"'players':[\"\n + \"{'name':'\" + player1 + \"','history':[10,8,6,7,8],'color':-13388315,'total':39},\"\n + \"{'name':'\" + player2 + \"','history':[6,10,5,10,10],'color':-48060,'total':41}\"\n + \"]}\";\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/guide/PostExample.java","line":53,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String[] args) throws IOException {\n PostExample example = new PostExample();\n String json = example.bowlingJson(\"Jesse\", \"Jake\");\n String response = example.post(\"http://www.roundsapp.com/post\", json);\n System.out.println(response);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/AccessHeaders.java","line":23,"symbol":"AccessHeaders","kind":"class","lang":"java","code":"public final class AccessHeaders {\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://api.github.com/repos/lysine-dev/okhttp/issues\")\n .header(\"User-Agent\", \"OkHttp Headers.java\")\n .addHeader(\"Accept\", \"application/json; q=0.5\")\n .addHeader(\"Accept\", \"application/vnd.github.v3+json\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(\"Server: \" + response.header(\"Server\"));\n System.out.println(\"Date: \" + response.header(\"Date\"));\n System.out.println(\"Vary: \" + response.headers(\"Vary\"));\n }\n }\n\n public static void main(String... args) throws Exception {\n new AccessHeaders().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/AccessHeaders.java","line":26,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://api.github.com/repos/lysine-dev/okhttp/issues\")\n .header(\"User-Agent\", \"OkHttp Headers.java\")\n .addHeader(\"Accept\", \"application/json; q=0.5\")\n .addHeader(\"Accept\", \"application/vnd.github.v3+json\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(\"Server: \" + response.header(\"Server\"));\n System.out.println(\"Date: \" + response.header(\"Date\"));\n System.out.println(\"Vary: \" + response.headers(\"Vary\"));\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/AccessHeaders.java","line":43,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new AccessHeaders().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java","line":27,"symbol":"AsynchronousGet","kind":"class","lang":"java","code":"public final class AsynchronousGet {\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build();\n\n client.newCall(request).enqueue(new Callback() {\n @Override public void onFailure(Call call, IOException e) {\n e.printStackTrace();\n }\n\n @Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody responseBody = response.body()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n Headers responseHeaders = response.headers();\n for (int i = 0, size = responseHeaders.size(); i < size; i++) {\n System.out.println(responseHeaders.name(i) + \": \" + responseHeaders.value(i));\n }\n\n System.out.println(responseBody.string());\n }\n }\n });\n }\n\n public static void main(String... args) throws Exception {\n new AsynchronousGet().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java","line":30,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build();\n\n client.newCall(request).enqueue(new Callback() {\n @Override public void onFailure(Call call, IOException e) {\n e.printStackTrace();\n }\n\n @Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody responseBody = response.body()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n Headers responseHeaders = response.headers();\n for (int i = 0, size = responseHeaders.size(); i < size; i++) {\n System.out.println(responseHeaders.name(i) + \": \" + responseHeaders.value(i));\n }\n\n System.out.println(responseBody.string());\n }\n }\n });\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java","line":36,"symbol":"onFailure","kind":"method","lang":"java","code":"@Override public void onFailure(Call call, IOException e) {\n e.printStackTrace();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java","line":40,"symbol":"onResponse","kind":"method","lang":"java","code":"@Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody responseBody = response.body()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n Headers responseHeaders = response.headers();\n for (int i = 0, size = responseHeaders.size(); i < size; i++) {\n System.out.println(responseHeaders.name(i) + \": \" + responseHeaders.value(i));\n }\n\n System.out.println(responseBody.string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java","line":55,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new AsynchronousGet().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Authenticate.java","line":24,"symbol":"Authenticate","kind":"class","lang":"java","code":"public final class Authenticate {\n private final OkHttpClient client;\n\n public Authenticate() {\n client = new OkHttpClient.Builder()\n .authenticator((route, response) -> {\n if (response.request().header(\"Authorization\") != null) {\n return null; // Give up, we've already attempted to authenticate.\n }\n\n System.out.println(\"Authenticating for response: \" + response);\n System.out.println(\"Challenges: \" + response.challenges());\n String credential = Credentials.basic(\"jesse\", \"password1\");\n return response.request().newBuilder()\n .header(\"Authorization\", credential)\n .build();\n })\n .build();\n }\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://publicobject.com/secrets/hellosecret.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }\n\n public static void main(String... args) throws Exception {\n new Authenticate().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Authenticate.java","line":27,"symbol":"Authenticate","kind":"constructor","lang":"java","code":"public Authenticate() {\n client = new OkHttpClient.Builder()\n .authenticator((route, response) -> {\n if (response.request().header(\"Authorization\") != null) {\n return null; // Give up, we've already attempted to authenticate.\n }\n\n System.out.println(\"Authenticating for response: \" + response);\n System.out.println(\"Challenges: \" + response.challenges());\n String credential = Credentials.basic(\"jesse\", \"password1\");\n return response.request().newBuilder()\n .header(\"Authorization\", credential)\n .build();\n })\n .build();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Authenticate.java","line":44,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://publicobject.com/secrets/hellosecret.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Authenticate.java","line":56,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new Authenticate().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CacheResponse.java","line":25,"symbol":"CacheResponse","kind":"class","lang":"java","code":"public final class CacheResponse {\n private final OkHttpClient client;\n\n public CacheResponse(File cacheDirectory) throws Exception {\n int cacheSize = 10 * 1024 * 1024; // 10 MiB\n Cache cache = new Cache(cacheDirectory, cacheSize);\n\n client = new OkHttpClient.Builder()\n .cache(cache)\n .build();\n }\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build();\n\n String response1Body;\n try (Response response1 = client.newCall(request).execute()) {\n if (!response1.isSuccessful()) throw new IOException(\"Unexpected code \" + response1);\n\n response1Body = response1.body().string();\n System.out.println(\"Response 1 response: \" + response1);\n System.out.println(\"Response 1 cache response: \" + response1.cacheResponse());\n System.out.println(\"Response 1 network response: \" + response1.networkResponse());\n }\n\n String response2Body;\n try (Response response2 = client.newCall(request).execute()) {\n if (!response2.isSuccessful()) throw new IOException(\"Unexpected code \" + response2);\n\n response2Body = response2.body()."} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CacheResponse.java","line":28,"symbol":"CacheResponse","kind":"constructor","lang":"java","code":"public CacheResponse(File cacheDirectory) throws Exception {\n int cacheSize = 10 * 1024 * 1024; // 10 MiB\n Cache cache = new Cache(cacheDirectory, cacheSize);\n\n client = new OkHttpClient.Builder()\n .cache(cache)\n .build();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CacheResponse.java","line":37,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build();\n\n String response1Body;\n try (Response response1 = client.newCall(request).execute()) {\n if (!response1.isSuccessful()) throw new IOException(\"Unexpected code \" + response1);\n\n response1Body = response1.body().string();\n System.out.println(\"Response 1 response: \" + response1);\n System.out.println(\"Response 1 cache response: \" + response1.cacheResponse());\n System.out.println(\"Response 1 network response: \" + response1.networkResponse());\n }\n\n String response2Body;\n try (Response response2 = client.newCall(request).execute()) {\n if (!response2.isSuccessful()) throw new IOException(\"Unexpected code \" + response2);\n\n response2Body = response2.body().string();\n System.out.println(\"Response 2 response: \" + response2);\n System.out.println(\"Response 2 cache response: \" + response2.cacheResponse());\n System.out.println(\"Response 2 network response: \" + response2.networkResponse());\n }\n\n System.out.println(\"Response 2 equals Response 1? \" + res"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CacheResponse.java","line":65,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new CacheResponse(new File(\"CacheResponse.tmp\")).run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CancelCall.java","line":27,"symbol":"CancelCall","kind":"class","lang":"java","code":"public class CancelCall {\n private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://httpbin.org/delay/2\") // This URL is served with a 2 second delay.\n .build();\n\n final long startNanos = System.nanoTime();\n final Call call = client.newCall(request);\n\n // Schedule a job to cancel the call in 1 second.\n executor.schedule(() -> {\n System.out.printf(\"%.2f Canceling call.%n\", (System.nanoTime() - startNanos) / 1e9f);\n call.cancel();\n System.out.printf(\"%.2f Canceled call.%n\", (System.nanoTime() - startNanos) / 1e9f);\n }, 1, TimeUnit.SECONDS);\n\n System.out.printf(\"%.2f Executing call.%n\", (System.nanoTime() - startNanos) / 1e9f);\n try (Response response = call.execute()) {\n System.out.printf(\"%.2f Call was expected to fail, but completed: %s%n\",\n (System.nanoTime() - startNanos) / 1e9f, response);\n } catch (IOException e) {\n System.out.printf(\"%.2f Call failed as expected: %s%n\",\n (System.nanoTime() - startNanos) / 1e9f, e)"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CancelCall.java","line":31,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://httpbin.org/delay/2\") // This URL is served with a 2 second delay.\n .build();\n\n final long startNanos = System.nanoTime();\n final Call call = client.newCall(request);\n\n // Schedule a job to cancel the call in 1 second.\n executor.schedule(() -> {\n System.out.printf(\"%.2f Canceling call.%n\", (System.nanoTime() - startNanos) / 1e9f);\n call.cancel();\n System.out.printf(\"%.2f Canceled call.%n\", (System.nanoTime() - startNanos) / 1e9f);\n }, 1, TimeUnit.SECONDS);\n\n System.out.printf(\"%.2f Executing call.%n\", (System.nanoTime() - startNanos) / 1e9f);\n try (Response response = call.execute()) {\n System.out.printf(\"%.2f Call was expected to fail, but completed: %s%n\",\n (System.nanoTime() - startNanos) / 1e9f, response);\n } catch (IOException e) {\n System.out.printf(\"%.2f Call failed as expected: %s%n\",\n (System.nanoTime() - startNanos) / 1e9f, e);\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CancelCall.java","line":56,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new CancelCall().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CertificatePinning.java","line":25,"symbol":"CertificatePinning","kind":"class","lang":"java","code":"public final class CertificatePinning {\n private final OkHttpClient client = new OkHttpClient.Builder()\n .certificatePinner(\n new CertificatePinner.Builder()\n .add(\"publicobject.com\", \"sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=\")\n .build())\n .build();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/robots.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n for (Certificate certificate : response.handshake().peerCertificates()) {\n System.out.println(CertificatePinner.pin(certificate));\n }\n }\n }\n\n public static void main(String... args) throws Exception {\n new CertificatePinning().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CertificatePinning.java","line":33,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/robots.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n for (Certificate certificate : response.handshake().peerCertificates()) {\n System.out.println(CertificatePinner.pin(certificate));\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CertificatePinning.java","line":47,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new CertificatePinning().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CheckHandshake.java","line":28,"symbol":"CheckHandshake","kind":"class","lang":"java","code":"public final class CheckHandshake {\n /** Rejects otherwise-trusted certificates. */\n private static final Interceptor CHECK_HANDSHAKE_INTERCEPTOR = new Interceptor() {\n final Set denylist = Collections.singleton(\n \"sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=\");\n\n @Override public Response intercept(Chain chain) throws IOException {\n for (Certificate certificate : chain.connection().handshake().peerCertificates()) {\n String pin = CertificatePinner.pin(certificate);\n if (denylist.contains(pin)) {\n throw new IOException(\"Denylisted peer certificate: \" + pin);\n }\n }\n return chain.proceed(chain.request());\n }\n };\n\n private final OkHttpClient client = new OkHttpClient.Builder()\n .addNetworkInterceptor(CHECK_HANDSHAKE_INTERCEPTOR)\n .build();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string("} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CheckHandshake.java","line":34,"symbol":"intercept","kind":"method","lang":"java","code":"@Override public Response intercept(Chain chain) throws IOException {\n for (Certificate certificate : chain.connection().handshake().peerCertificates()) {\n String pin = CertificatePinner.pin(certificate);\n if (denylist.contains(pin)) {\n throw new IOException(\"Denylisted peer certificate: \" + pin);\n }\n }\n return chain.proceed(chain.request());\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CheckHandshake.java","line":49,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CheckHandshake.java","line":61,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new CheckHandshake().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ConfigureTimeouts.java","line":23,"symbol":"ConfigureTimeouts","kind":"class","lang":"java","code":"public final class ConfigureTimeouts {\n private final OkHttpClient client;\n\n public ConfigureTimeouts() throws Exception {\n client = new OkHttpClient.Builder()\n .connectTimeout(5, TimeUnit.SECONDS)\n .writeTimeout(5, TimeUnit.SECONDS)\n .readTimeout(5, TimeUnit.SECONDS)\n .callTimeout(10, TimeUnit.SECONDS)\n .build();\n }\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://httpbin.org/delay/2\") // This URL is served with a 2 second delay.\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n System.out.println(\"Response completed: \" + response);\n }\n }\n\n public static void main(String... args) throws Exception {\n new ConfigureTimeouts().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ConfigureTimeouts.java","line":26,"symbol":"ConfigureTimeouts","kind":"constructor","lang":"java","code":"public ConfigureTimeouts() throws Exception {\n client = new OkHttpClient.Builder()\n .connectTimeout(5, TimeUnit.SECONDS)\n .writeTimeout(5, TimeUnit.SECONDS)\n .readTimeout(5, TimeUnit.SECONDS)\n .callTimeout(10, TimeUnit.SECONDS)\n .build();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ConfigureTimeouts.java","line":35,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://httpbin.org/delay/2\") // This URL is served with a 2 second delay.\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n System.out.println(\"Response completed: \" + response);\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ConfigureTimeouts.java","line":45,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new ConfigureTimeouts().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CurrentDateHeader.java","line":26,"symbol":"CurrentDateHeader","kind":"class","lang":"java","code":"public final class CurrentDateHeader {\n private final OkHttpClient client = new OkHttpClient.Builder()\n .addInterceptor(new CurrentDateInterceptor())\n .build();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n System.out.println(response.request().header(\"Date\"));\n }\n }\n\n static class CurrentDateInterceptor implements Interceptor {\n @Override public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n Headers newHeaders = request.headers()\n .newBuilder()\n .add(\"Date\", new Date())\n .build();\n Request newRequest = request.newBuilder()\n .headers(newHeaders)\n .build();\n return chain.proceed(newRequest);\n }\n }\n\n public static void main(String... args) throws Exception {\n new CurrentDateHeader().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CurrentDateHeader.java","line":31,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n System.out.println(response.request().header(\"Date\"));\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CurrentDateHeader.java","line":41,"symbol":"CurrentDateInterceptor","kind":"class","lang":"java","code":"static class CurrentDateInterceptor implements Interceptor {\n @Override public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n Headers newHeaders = request.headers()\n .newBuilder()\n .add(\"Date\", new Date())\n .build();\n Request newRequest = request.newBuilder()\n .headers(newHeaders)\n .build();\n return chain.proceed(newRequest);\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CurrentDateHeader.java","line":42,"symbol":"intercept","kind":"method","lang":"java","code":"@Override public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n Headers newHeaders = request.headers()\n .newBuilder()\n .add(\"Date\", new Date())\n .build();\n Request newRequest = request.newBuilder()\n .headers(newHeaders)\n .build();\n return chain.proceed(newRequest);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CurrentDateHeader.java","line":55,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new CurrentDateHeader().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":42,"symbol":"CustomCipherSuites","kind":"class","lang":"java","code":"public final class CustomCipherSuites {\n private final OkHttpClient client;\n\n public CustomCipherSuites() throws GeneralSecurityException {\n // Configure cipher suites to demonstrate how to customize which cipher suites will be used for\n // an OkHttp request. In order to be selected a cipher suite must be included in both OkHttp's\n // connection spec and in the SSLSocket's enabled cipher suites array. Most applications should\n // not customize the cipher suites list.\n List customCipherSuites = asList(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);\n final ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)\n .cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))\n .build();\n\n X509TrustManager trustManager = defaultTrustManager();\n SSLSocketFactory sslSocketFactory = defaultSslSocketFactory(trustManager);\n SSLSocketFactory customSslSocketFactory = new DelegatingSSLSocketFactory(sslSocketFactory) {\n @Overr"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":45,"symbol":"CustomCipherSuites","kind":"constructor","lang":"java","code":"public CustomCipherSuites() throws GeneralSecurityException {\n // Configure cipher suites to demonstrate how to customize which cipher suites will be used for\n // an OkHttp request. In order to be selected a cipher suite must be included in both OkHttp's\n // connection spec and in the SSLSocket's enabled cipher suites array. Most applications should\n // not customize the cipher suites list.\n List customCipherSuites = asList(\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);\n final ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)\n .cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))\n .build();\n\n X509TrustManager trustManager = defaultTrustManager();\n SSLSocketFactory sslSocketFactory = defaultSslSocketFactory(trustManager);\n SSLSocketFactory customSslSocketFactory = new DelegatingSSLSocketFactory(sslSocketFactory) {\n @Override protected SSLSocket configureSocket(SSLSocket socket) throws IOException {\n "} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":62,"symbol":"configureSocket","kind":"method","lang":"java","code":"@Override protected SSLSocket configureSocket(SSLSocket socket) throws IOException {\n socket.setEnabledCipherSuites(javaNames(spec.cipherSuites()));\n return socket;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":78,"symbol":"defaultSslSocketFactory","kind":"method","lang":"java","doc":"Returns the VM's default SSL socket factory, using {@code trustManager} for trusted root certificates.","code":"private SSLSocketFactory defaultSslSocketFactory(X509TrustManager trustManager)\n throws NoSuchAlgorithmException, KeyManagementException {\n SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n sslContext.init(null, new TrustManager[] { trustManager }, null);\n\n return sslContext.getSocketFactory();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":87,"symbol":"defaultTrustManager","kind":"method","lang":"java","doc":"Returns a trust manager that trusts the VM's default certificate authorities.","code":"private X509TrustManager defaultTrustManager() throws GeneralSecurityException {\n TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(\n TrustManagerFactory.getDefaultAlgorithm());\n trustManagerFactory.init((KeyStore) null);\n TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();\n if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {\n throw new IllegalStateException(\"Unexpected default trust managers:\"\n + Arrays.toString(trustManagers));\n }\n return (X509TrustManager) trustManagers[0];\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":99,"symbol":"javaNames","kind":"method","lang":"java","code":"private String[] javaNames(List cipherSuites) {\n String[] result = new String[cipherSuites.size()];\n for (int i = 0; i < result.length; i++) {\n result[i] = cipherSuites.get(i).javaName();\n }\n return result;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":111,"symbol":"DelegatingSSLSocketFactory","kind":"class","lang":"java","doc":"An SSL socket factory that forwards all calls to a delegate. Override {@link #configureSocket} to customize a created socket before it is returned.","code":"static class DelegatingSSLSocketFactory extends SSLSocketFactory {\n protected final SSLSocketFactory delegate;\n\n DelegatingSSLSocketFactory(SSLSocketFactory delegate) {\n this.delegate = delegate;\n }\n\n @Override public String[] getDefaultCipherSuites() {\n return delegate.getDefaultCipherSuites();\n }\n\n @Override public String[] getSupportedCipherSuites() {\n return delegate.getSupportedCipherSuites();\n }\n\n @Override public Socket createSocket(\n Socket socket, String host, int port, boolean autoClose) throws IOException {\n return configureSocket((SSLSocket) delegate.createSocket(socket, host, port, autoClose));\n }\n\n @Override public Socket createSocket(String host, int port) throws IOException {\n return configureSocket((SSLSocket) delegate.createSocket(host, port));\n }\n\n @Override public Socket createSocket(\n String host, int port, InetAddress localHost, int localPort) throws IOException {\n return configureSocket((SSLSocket) delegate.createSocket(host, port, localHost, localPort));\n }\n\n @Override public Socket createSocket(InetAddress host, int port) throws IOException {\n return configureSocket(("} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":114,"symbol":"DelegatingSSLSocketFactory","kind":"constructor","lang":"java","code":"DelegatingSSLSocketFactory(SSLSocketFactory delegate) {\n this.delegate = delegate;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":118,"symbol":"getDefaultCipherSuites","kind":"method","lang":"java","code":"@Override public String[] getDefaultCipherSuites() {\n return delegate.getDefaultCipherSuites();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":122,"symbol":"getSupportedCipherSuites","kind":"method","lang":"java","code":"@Override public String[] getSupportedCipherSuites() {\n return delegate.getSupportedCipherSuites();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":126,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(\n Socket socket, String host, int port, boolean autoClose) throws IOException {\n return configureSocket((SSLSocket) delegate.createSocket(socket, host, port, autoClose));\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":131,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(String host, int port) throws IOException {\n return configureSocket((SSLSocket) delegate.createSocket(host, port));\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":135,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(\n String host, int port, InetAddress localHost, int localPort) throws IOException {\n return configureSocket((SSLSocket) delegate.createSocket(host, port, localHost, localPort));\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":140,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(InetAddress host, int port) throws IOException {\n return configureSocket((SSLSocket) delegate.createSocket(host, port));\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":144,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(\n InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {\n return configureSocket((SSLSocket) delegate.createSocket(\n address, port, localAddress, localPort));\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":150,"symbol":"configureSocket","kind":"method","lang":"java","code":"protected SSLSocket configureSocket(SSLSocket socket) throws IOException {\n return socket;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":155,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.handshake().cipherSuite());\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomCipherSuites.java","line":168,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new CustomCipherSuites().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java","line":27,"symbol":"CustomTrust","kind":"class","lang":"java","code":"public final class CustomTrust {\n // PEM files for root certificates of Comodo and Entrust. These two CAs are sufficient to view\n // https://publicobject.com (Comodo) and https://squareup.com (Entrust). But they aren't\n // sufficient to connect to most HTTPS sites including https://godaddy.com and https://visa.com.\n // Typically developers will need to get a PEM file from their organization's TLS administrator.\n final X509Certificate comodoRsaCertificationAuthority = Certificates.decodeCertificatePem(\"\"\n + \"-----BEGIN CERTIFICATE-----\\n\"\n + \"MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB\\n\"\n + \"hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\\n\"\n + \"A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV\\n\"\n + \"BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5\\n\"\n + \"MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT\\n\"\n + \"EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR\\n\"\n + \"Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh\\n\"\n + \"dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR\\n\"\n + \"6FSS0gpWsawNJN3Fz0Rnd"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java","line":128,"symbol":"CustomTrust","kind":"constructor","lang":"java","code":"public CustomTrust() {\n // This implementation just embeds the PEM files in Java strings; most applications will\n // instead read this from a resource file that gets bundled with the application.\n\n HandshakeCertificates certificates = new HandshakeCertificates.Builder()\n .addTrustedCertificate(letsEncryptCertificateAuthority)\n .addTrustedCertificate(entrustRootCertificateAuthority)\n .addTrustedCertificate(comodoRsaCertificationAuthority)\n // Uncomment if standard certificates are also required.\n //.addPlatformTrustedCertificates()\n .build();\n\n client = new OkHttpClient.Builder()\n .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager())\n .build();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java","line":145,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) {\n Headers responseHeaders = response.headers();\n for (int i = 0; i < responseHeaders.size(); i++) {\n System.out.println(responseHeaders.name(i) + \": \" + responseHeaders.value(i));\n }\n\n throw new IOException(\"Unexpected code \" + response);\n }\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java","line":164,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new CustomTrust().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/HttpsServer.java","line":31,"symbol":"HttpsServer","kind":"class","lang":"java","doc":"Create an HTTPS server with a self-signed certificate that OkHttp trusts.","code":"public class HttpsServer {\n public void run() throws Exception {\n HeldCertificate localhostCertificate = new HeldCertificate.Builder()\n .addSubjectAlternativeName(\"localhost\")\n .build();\n\n HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder()\n .heldCertificate(localhostCertificate)\n .build();\n MockWebServer server = new MockWebServer();\n server.useHttps(serverCertificates.sslSocketFactory(), false);\n server.enqueue(new MockResponse());\n\n HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder()\n .addTrustedCertificate(localhostCertificate.certificate())\n .build();\n OkHttpClient client = new OkHttpClient.Builder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager())\n .build();\n\n Call call = client.newCall(new Request.Builder()\n .url(server.url(\"/\"))\n .build());\n Response response = call.execute();\n System.out.println(response.handshake().tlsVersion());\n }\n\n public static void main(String... args) throws Exception {\n new HttpsServer().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/HttpsServer.java","line":32,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n HeldCertificate localhostCertificate = new HeldCertificate.Builder()\n .addSubjectAlternativeName(\"localhost\")\n .build();\n\n HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder()\n .heldCertificate(localhostCertificate)\n .build();\n MockWebServer server = new MockWebServer();\n server.useHttps(serverCertificates.sslSocketFactory(), false);\n server.enqueue(new MockResponse());\n\n HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder()\n .addTrustedCertificate(localhostCertificate.certificate())\n .build();\n OkHttpClient client = new OkHttpClient.Builder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager())\n .build();\n\n Call call = client.newCall(new Request.Builder()\n .url(server.url(\"/\"))\n .build());\n Response response = call.execute();\n System.out.println(response.handshake().tlsVersion());\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/HttpsServer.java","line":58,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new HttpsServer().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/LoggingInterceptors.java","line":25,"symbol":"LoggingInterceptors","kind":"class","lang":"java","code":"public final class LoggingInterceptors {\n private static final Logger logger = Logger.getLogger(LoggingInterceptors.class.getName());\n private final OkHttpClient client = new OkHttpClient.Builder()\n .addInterceptor(new LoggingInterceptor())\n .build();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n Response response = client.newCall(request).execute();\n response.body().close();\n }\n\n private static class LoggingInterceptor implements Interceptor {\n @Override public Response intercept(Chain chain) throws IOException {\n long t1 = System.nanoTime();\n Request request = chain.request();\n logger.info(String.format(\"Sending request %s on %s%n%s\",\n request.url(), chain.connection(), request.headers()));\n Response response = chain.proceed(request);\n\n long t2 = System.nanoTime();\n logger.info(String.format(\"Received response for %s in %.1fms%n%s\",\n request.url(), (t2 - t1) / 1e6d, response.headers()));\n return response;\n }\n }\n\n public static void main(String... args) throws Exception {\n new LoggingIn"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/LoggingInterceptors.java","line":31,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n Response response = client.newCall(request).execute();\n response.body().close();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/LoggingInterceptors.java","line":40,"symbol":"LoggingInterceptor","kind":"class","lang":"java","code":"private static class LoggingInterceptor implements Interceptor {\n @Override public Response intercept(Chain chain) throws IOException {\n long t1 = System.nanoTime();\n Request request = chain.request();\n logger.info(String.format(\"Sending request %s on %s%n%s\",\n request.url(), chain.connection(), request.headers()));\n Response response = chain.proceed(request);\n\n long t2 = System.nanoTime();\n logger.info(String.format(\"Received response for %s in %.1fms%n%s\",\n request.url(), (t2 - t1) / 1e6d, response.headers()));\n return response;\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/LoggingInterceptors.java","line":41,"symbol":"intercept","kind":"method","lang":"java","code":"@Override public Response intercept(Chain chain) throws IOException {\n long t1 = System.nanoTime();\n Request request = chain.request();\n logger.info(String.format(\"Sending request %s on %s%n%s\",\n request.url(), chain.connection(), request.headers()));\n Response response = chain.proceed(request);\n\n long t2 = System.nanoTime();\n logger.info(String.format(\"Received response for %s in %.1fms%n%s\",\n request.url(), (t2 - t1) / 1e6d, response.headers()));\n return response;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/LoggingInterceptors.java","line":55,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new LoggingInterceptors().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ParseResponseWithMoshi.java","line":26,"symbol":"ParseResponseWithMoshi","kind":"class","lang":"java","code":"public final class ParseResponseWithMoshi {\n private final OkHttpClient client = new OkHttpClient();\n private final Moshi moshi = new Moshi.Builder().build();\n private final JsonAdapter gistJsonAdapter = moshi.adapter(Gist.class);\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://api.github.com/gists/c2a7c39532239ff261be\")\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n Gist gist = gistJsonAdapter.fromJson(response.body().source());\n\n for (Map.Entry entry : gist.files.entrySet()) {\n System.out.println(entry.getKey());\n System.out.println(entry.getValue().content);\n }\n }\n }\n\n static class Gist {\n Map files;\n }\n\n static class GistFile {\n String content;\n }\n\n public static void main(String... args) throws Exception {\n new ParseResponseWithMoshi().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ParseResponseWithMoshi.java","line":31,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://api.github.com/gists/c2a7c39532239ff261be\")\n .build();\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n Gist gist = gistJsonAdapter.fromJson(response.body().source());\n\n for (Map.Entry entry : gist.files.entrySet()) {\n System.out.println(entry.getKey());\n System.out.println(entry.getValue().content);\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ParseResponseWithMoshi.java","line":47,"symbol":"Gist","kind":"class","lang":"java","code":"static class Gist {\n Map files;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ParseResponseWithMoshi.java","line":51,"symbol":"GistFile","kind":"class","lang":"java","code":"static class GistFile {\n String content;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/ParseResponseWithMoshi.java","line":55,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new ParseResponseWithMoshi().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PerCallSettings.java","line":24,"symbol":"PerCallSettings","kind":"class","lang":"java","code":"public final class PerCallSettings {\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://httpbin.org/delay/1\") // This URL is served with a 1 second delay.\n .build();\n\n // Copy to customize OkHttp for this request.\n OkHttpClient client1 = client.newBuilder()\n .readTimeout(500, TimeUnit.MILLISECONDS)\n .build();\n try (Response response = client1.newCall(request).execute()) {\n System.out.println(\"Response 1 succeeded: \" + response);\n } catch (IOException e) {\n System.out.println(\"Response 1 failed: \" + e);\n }\n\n // Copy to customize OkHttp for this request.\n OkHttpClient client2 = client.newBuilder()\n .readTimeout(3000, TimeUnit.MILLISECONDS)\n .build();\n try (Response response = client2.newCall(request).execute()) {\n System.out.println(\"Response 2 succeeded: \" + response);\n } catch (IOException e) {\n System.out.println(\"Response 2 failed: \" + e);\n }\n }\n\n public static void main(String... args) throws Exception {\n new PerCallSettings().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PerCallSettings.java","line":27,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"http://httpbin.org/delay/1\") // This URL is served with a 1 second delay.\n .build();\n\n // Copy to customize OkHttp for this request.\n OkHttpClient client1 = client.newBuilder()\n .readTimeout(500, TimeUnit.MILLISECONDS)\n .build();\n try (Response response = client1.newCall(request).execute()) {\n System.out.println(\"Response 1 succeeded: \" + response);\n } catch (IOException e) {\n System.out.println(\"Response 1 failed: \" + e);\n }\n\n // Copy to customize OkHttp for this request.\n OkHttpClient client2 = client.newBuilder()\n .readTimeout(3000, TimeUnit.MILLISECONDS)\n .build();\n try (Response response = client2.newCall(request).execute()) {\n System.out.println(\"Response 2 succeeded: \" + response);\n } catch (IOException e) {\n System.out.println(\"Response 2 failed: \" + e);\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PerCallSettings.java","line":53,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PerCallSettings().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostFile.java","line":26,"symbol":"PostFile","kind":"class","lang":"java","code":"public final class PostFile {\n public static final MediaType MEDIA_TYPE_MARKDOWN\n = MediaType.get(\"text/x-markdown; charset=utf-8\");\n\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n File file = new File(\"README.md\");\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/markdown/raw\")\n .post(RequestBody.create(file, MEDIA_TYPE_MARKDOWN))\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }\n\n public static void main(String... args) throws Exception {\n new PostFile().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostFile.java","line":32,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n File file = new File(\"README.md\");\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/markdown/raw\")\n .post(RequestBody.create(file, MEDIA_TYPE_MARKDOWN))\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostFile.java","line":47,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PostFile().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostForm.java","line":25,"symbol":"PostForm","kind":"class","lang":"java","code":"public final class PostForm {\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n RequestBody formBody = new FormBody.Builder()\n .add(\"search\", \"Jurassic Park\")\n .build();\n Request request = new Request.Builder()\n .url(\"https://en.wikipedia.org/w/index.php\")\n .post(formBody)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }\n\n public static void main(String... args) throws Exception {\n new PostForm().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostForm.java","line":28,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n RequestBody formBody = new FormBody.Builder()\n .add(\"search\", \"Jurassic Park\")\n .build();\n Request request = new Request.Builder()\n .url(\"https://en.wikipedia.org/w/index.php\")\n .post(formBody)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostForm.java","line":44,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PostForm().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java","line":27,"symbol":"PostMultipart","kind":"class","lang":"java","code":"public final class PostMultipart {\n /**\n * The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running\n * these examples, please request your own client ID! https://api.imgur.com/oauth2\n */\n private static final String IMGUR_CLIENT_ID = \"9199fdef135c122\";\n private static final MediaType MEDIA_TYPE_PNG = MediaType.get(\"image/png\");\n\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image\n RequestBody requestBody = new MultipartBody.Builder()\n .setType(MultipartBody.FORM)\n .addFormDataPart(\"title\", \"Square Logo\")\n .addFormDataPart(\"image\", \"logo-square.png\",\n RequestBody.create(\n new File(\"docs/images/logo-square.png\"),\n MEDIA_TYPE_PNG))\n .build();\n\n Request request = new Request.Builder()\n .header(\"Authorization\", \"Client-ID \" + IMGUR_CLIENT_ID)\n .url(\"https://api.imgur.com/3/image\")\n .post(requestBody)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSucce"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java","line":37,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image\n RequestBody requestBody = new MultipartBody.Builder()\n .setType(MultipartBody.FORM)\n .addFormDataPart(\"title\", \"Square Logo\")\n .addFormDataPart(\"image\", \"logo-square.png\",\n RequestBody.create(\n new File(\"docs/images/logo-square.png\"),\n MEDIA_TYPE_PNG))\n .build();\n\n Request request = new Request.Builder()\n .header(\"Authorization\", \"Client-ID \" + IMGUR_CLIENT_ID)\n .url(\"https://api.imgur.com/3/image\")\n .post(requestBody)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java","line":61,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PostMultipart().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreaming.java","line":26,"symbol":"PostStreaming","kind":"class","lang":"java","code":"public final class PostStreaming {\n public static final MediaType MEDIA_TYPE_MARKDOWN\n = MediaType.get(\"text/x-markdown; charset=utf-8\");\n\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n RequestBody requestBody = new RequestBody() {\n @Override public MediaType contentType() {\n return MEDIA_TYPE_MARKDOWN;\n }\n\n @Override public void writeTo(BufferedSink sink) throws IOException {\n sink.writeUtf8(\"Numbers\\n\");\n sink.writeUtf8(\"-------\\n\");\n for (int i = 2; i <= 997; i++) {\n sink.writeUtf8(String.format(\" * %s = %s\\n\", i, factor(i)));\n }\n }\n\n private String factor(int n) {\n for (int i = 2; i < n; i++) {\n int x = n / i;\n if (x * i == n) return factor(x) + \" × \" + i;\n }\n return Integer.toString(n);\n }\n };\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/markdown/raw\")\n .post(requestBody)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.ou"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreaming.java","line":32,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n RequestBody requestBody = new RequestBody() {\n @Override public MediaType contentType() {\n return MEDIA_TYPE_MARKDOWN;\n }\n\n @Override public void writeTo(BufferedSink sink) throws IOException {\n sink.writeUtf8(\"Numbers\\n\");\n sink.writeUtf8(\"-------\\n\");\n for (int i = 2; i <= 997; i++) {\n sink.writeUtf8(String.format(\" * %s = %s\\n\", i, factor(i)));\n }\n }\n\n private String factor(int n) {\n for (int i = 2; i < n; i++) {\n int x = n / i;\n if (x * i == n) return factor(x) + \" × \" + i;\n }\n return Integer.toString(n);\n }\n };\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/markdown/raw\")\n .post(requestBody)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreaming.java","line":34,"symbol":"contentType","kind":"method","lang":"java","code":"@Override public MediaType contentType() {\n return MEDIA_TYPE_MARKDOWN;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreaming.java","line":38,"symbol":"writeTo","kind":"method","lang":"java","code":"@Override public void writeTo(BufferedSink sink) throws IOException {\n sink.writeUtf8(\"Numbers\\n\");\n sink.writeUtf8(\"-------\\n\");\n for (int i = 2; i <= 997; i++) {\n sink.writeUtf8(String.format(\" * %s = %s\\n\", i, factor(i)));\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreaming.java","line":46,"symbol":"factor","kind":"method","lang":"java","code":"private String factor(int n) {\n for (int i = 2; i < n; i++) {\n int x = n / i;\n if (x * i == n) return factor(x) + \" × \" + i;\n }\n return Integer.toString(n);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreaming.java","line":67,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PostStreaming().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":28,"symbol":"PostStreamingWithPipe","kind":"class","lang":"java","code":"public final class PostStreamingWithPipe {\n public static final MediaType MEDIA_TYPE_MARKDOWN\n = MediaType.get(\"text/x-markdown; charset=utf-8\");\n\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n final PipeBody pipeBody = new PipeBody();\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/markdown/raw\")\n .post(pipeBody)\n .build();\n\n streamPrimesToSinkAsynchronously(pipeBody.sink());\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }\n\n private void streamPrimesToSinkAsynchronously(final BufferedSink sink) {\n Thread thread = new Thread(\"writer\") {\n @Override public void run() {\n try {\n sink.writeUtf8(\"Numbers\\n\");\n sink.writeUtf8(\"-------\\n\");\n for (int i = 2; i <= 997; i++) {\n System.out.println(i);\n Thread.sleep(10);\n sink.writeUtf8(String.format(\" * %s = %s\\n\", i, factor(i)));\n }\n sink.close();\n } catch (IOExcep"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":34,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n final PipeBody pipeBody = new PipeBody();\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/markdown/raw\")\n .post(pipeBody)\n .build();\n\n streamPrimesToSinkAsynchronously(pipeBody.sink());\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":51,"symbol":"streamPrimesToSinkAsynchronously","kind":"method","lang":"java","code":"private void streamPrimesToSinkAsynchronously(final BufferedSink sink) {\n Thread thread = new Thread(\"writer\") {\n @Override public void run() {\n try {\n sink.writeUtf8(\"Numbers\\n\");\n sink.writeUtf8(\"-------\\n\");\n for (int i = 2; i <= 997; i++) {\n System.out.println(i);\n Thread.sleep(10);\n sink.writeUtf8(String.format(\" * %s = %s\\n\", i, factor(i)));\n }\n sink.close();\n } catch (IOException | InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n private String factor(int n) {\n for (int i = 2; i < n; i++) {\n int x = n / i;\n if (x * i == n) return factor(x) + \" × \" + i;\n }\n return Integer.toString(n);\n }\n };\n\n thread.start();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":53,"symbol":"run","kind":"method","lang":"java","code":"@Override public void run() {\n try {\n sink.writeUtf8(\"Numbers\\n\");\n sink.writeUtf8(\"-------\\n\");\n for (int i = 2; i <= 997; i++) {\n System.out.println(i);\n Thread.sleep(10);\n sink.writeUtf8(String.format(\" * %s = %s\\n\", i, factor(i)));\n }\n sink.close();\n } catch (IOException | InterruptedException e) {\n e.printStackTrace();\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":68,"symbol":"factor","kind":"method","lang":"java","code":"private String factor(int n) {\n for (int i = 2; i < n; i++) {\n int x = n / i;\n if (x * i == n) return factor(x) + \" × \" + i;\n }\n return Integer.toString(n);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":85,"symbol":"PipeBody","kind":"class","lang":"java","doc":"This request body makes it possible for another thread to stream data to the uploading request. This is potentially useful for posting live event streams like video capture. Callers should write to {@code sink()} and close it to complete the post.","code":"static final class PipeBody extends RequestBody {\n private final Pipe pipe = new Pipe(8192);\n private final BufferedSink sink = Okio.buffer(pipe.sink());\n\n public BufferedSink sink() {\n return sink;\n }\n\n @Override public MediaType contentType() {\n return MEDIA_TYPE_MARKDOWN;\n }\n\n @Override public void writeTo(BufferedSink sink) throws IOException {\n sink.writeAll(pipe.source());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":89,"symbol":"sink","kind":"method","lang":"java","code":"public BufferedSink sink() {\n return sink;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":93,"symbol":"contentType","kind":"method","lang":"java","code":"@Override public MediaType contentType() {\n return MEDIA_TYPE_MARKDOWN;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":97,"symbol":"writeTo","kind":"method","lang":"java","code":"@Override public void writeTo(BufferedSink sink) throws IOException {\n sink.writeAll(pipe.source());\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostStreamingWithPipe.java","line":102,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PostStreamingWithPipe().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostString.java","line":25,"symbol":"PostString","kind":"class","lang":"java","code":"public final class PostString {\n public static final MediaType MEDIA_TYPE_MARKDOWN\n = MediaType.get(\"text/x-markdown; charset=utf-8\");\n\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n String postBody = \"\"\n + \"Releases\\n\"\n + \"--------\\n\"\n + \"\\n\"\n + \" * _1.0_ May 6, 2013\\n\"\n + \" * _1.1_ June 15, 2013\\n\"\n + \" * _1.2_ August 11, 2013\\n\";\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/markdown/raw\")\n .post(RequestBody.create(postBody, MEDIA_TYPE_MARKDOWN))\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }\n\n public static void main(String... args) throws Exception {\n new PostString().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostString.java","line":31,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n String postBody = \"\"\n + \"Releases\\n\"\n + \"--------\\n\"\n + \"\\n\"\n + \" * _1.0_ May 6, 2013\\n\"\n + \" * _1.1_ June 15, 2013\\n\"\n + \" * _1.2_ August 11, 2013\\n\";\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/markdown/raw\")\n .post(RequestBody.create(postBody, MEDIA_TYPE_MARKDOWN))\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PostString.java","line":52,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PostString().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PreemptiveAuth.java","line":25,"symbol":"PreemptiveAuth","kind":"class","lang":"java","code":"public final class PreemptiveAuth {\n private final OkHttpClient client;\n\n public PreemptiveAuth() {\n client = new OkHttpClient.Builder()\n .addInterceptor(\n new BasicAuthInterceptor(\"publicobject.com\", \"jesse\", \"password1\"))\n .build();\n }\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/secrets/hellosecret.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }\n\n public static void main(String... args) throws Exception {\n new PreemptiveAuth().run();\n }\n\n static final class BasicAuthInterceptor implements Interceptor {\n private final String credentials;\n private final String host;\n\n BasicAuthInterceptor(String host, String username, String password) {\n this.credentials = Credentials.basic(username, password);\n this.host = host;\n }\n\n @Override public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n if (request.url()."} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PreemptiveAuth.java","line":28,"symbol":"PreemptiveAuth","kind":"constructor","lang":"java","code":"public PreemptiveAuth() {\n client = new OkHttpClient.Builder()\n .addInterceptor(\n new BasicAuthInterceptor(\"publicobject.com\", \"jesse\", \"password1\"))\n .build();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PreemptiveAuth.java","line":35,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/secrets/hellosecret.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PreemptiveAuth.java","line":47,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PreemptiveAuth().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PreemptiveAuth.java","line":51,"symbol":"BasicAuthInterceptor","kind":"class","lang":"java","code":"static final class BasicAuthInterceptor implements Interceptor {\n private final String credentials;\n private final String host;\n\n BasicAuthInterceptor(String host, String username, String password) {\n this.credentials = Credentials.basic(username, password);\n this.host = host;\n }\n\n @Override public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n if (request.url().host().equals(host)) {\n request = request.newBuilder()\n .header(\"Authorization\", credentials)\n .build();\n }\n return chain.proceed(request);\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PreemptiveAuth.java","line":55,"symbol":"BasicAuthInterceptor","kind":"constructor","lang":"java","code":"BasicAuthInterceptor(String host, String username, String password) {\n this.credentials = Credentials.basic(username, password);\n this.host = host;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PreemptiveAuth.java","line":60,"symbol":"intercept","kind":"method","lang":"java","code":"@Override public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n if (request.url().host().equals(host)) {\n request = request.newBuilder()\n .header(\"Authorization\", credentials)\n .build();\n }\n return chain.proceed(request);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":36,"symbol":"PrintEvents","kind":"class","lang":"java","code":"public final class PrintEvents {\n private final OkHttpClient client = new OkHttpClient.Builder()\n .eventListenerFactory(PrintingEventListener.FACTORY)\n .build();\n\n public void run() throws Exception {\n Request washingtonPostRequest = new Request.Builder()\n .url(\"https://www.washingtonpost.com/\")\n .build();\n client.newCall(washingtonPostRequest).enqueue(new Callback() {\n @Override public void onFailure(Call call, IOException e) {\n }\n\n @Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody body = response.body()) {\n // Consume and discard the response body.\n body.source().readByteString();\n }\n }\n });\n\n Request newYorkTimesRequest = new Request.Builder()\n .url(\"https://www.nytimes.com/\")\n .build();\n client.newCall(newYorkTimesRequest).enqueue(new Callback() {\n @Override public void onFailure(Call call, IOException e) {\n }\n\n @Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody body = response.body()) {\n // Consume and discard the response body.\n "} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":41,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request washingtonPostRequest = new Request.Builder()\n .url(\"https://www.washingtonpost.com/\")\n .build();\n client.newCall(washingtonPostRequest).enqueue(new Callback() {\n @Override public void onFailure(Call call, IOException e) {\n }\n\n @Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody body = response.body()) {\n // Consume and discard the response body.\n body.source().readByteString();\n }\n }\n });\n\n Request newYorkTimesRequest = new Request.Builder()\n .url(\"https://www.nytimes.com/\")\n .build();\n client.newCall(newYorkTimesRequest).enqueue(new Callback() {\n @Override public void onFailure(Call call, IOException e) {\n }\n\n @Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody body = response.body()) {\n // Consume and discard the response body.\n body.source().readByteString();\n }\n }\n });\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":46,"symbol":"onFailure","kind":"method","lang":"java","code":"@Override public void onFailure(Call call, IOException e) {\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":49,"symbol":"onResponse","kind":"method","lang":"java","code":"@Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody body = response.body()) {\n // Consume and discard the response body.\n body.source().readByteString();\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":61,"symbol":"onFailure","kind":"method","lang":"java","code":"@Override public void onFailure(Call call, IOException e) {\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":64,"symbol":"onResponse","kind":"method","lang":"java","code":"@Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody body = response.body()) {\n // Consume and discard the response body.\n body.source().readByteString();\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":73,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PrintEvents().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":77,"symbol":"PrintingEventListener","kind":"class","lang":"java","code":"private static final class PrintingEventListener extends EventListener {\n private static final Factory FACTORY = new Factory() {\n final AtomicLong nextCallId = new AtomicLong(1L);\n\n @Override public EventListener create(Call call) {\n long callId = nextCallId.getAndIncrement();\n System.out.printf(\"%04d %s%n\", callId, call.request().url());\n return new PrintingEventListener(callId, System.nanoTime());\n }\n };\n\n final long callId;\n final long callStartNanos;\n\n PrintingEventListener(long callId, long callStartNanos) {\n this.callId = callId;\n this.callStartNanos = callStartNanos;\n }\n\n private void printEvent(String name) {\n long elapsedNanos = System.nanoTime() - callStartNanos;\n System.out.printf(\"%04d %.3f %s%n\", callId, elapsedNanos / 1000000000d, name);\n }\n\n @Override public void proxySelectStart(Call call, HttpUrl url) {\n printEvent(\"proxySelectStart\");\n }\n\n @Override public void proxySelectEnd(Call call, HttpUrl url, List proxies) {\n printEvent(\"proxySelectEnd\");\n }\n\n @Override public void callStart(Call call) {\n printEvent(\"callStart\");\n }\n\n @Override public v"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":81,"symbol":"create","kind":"method","lang":"java","code":"@Override public EventListener create(Call call) {\n long callId = nextCallId.getAndIncrement();\n System.out.printf(\"%04d %s%n\", callId, call.request().url());\n return new PrintingEventListener(callId, System.nanoTime());\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":91,"symbol":"PrintingEventListener","kind":"constructor","lang":"java","code":"PrintingEventListener(long callId, long callStartNanos) {\n this.callId = callId;\n this.callStartNanos = callStartNanos;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":96,"symbol":"printEvent","kind":"method","lang":"java","code":"private void printEvent(String name) {\n long elapsedNanos = System.nanoTime() - callStartNanos;\n System.out.printf(\"%04d %.3f %s%n\", callId, elapsedNanos / 1000000000d, name);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":101,"symbol":"proxySelectStart","kind":"method","lang":"java","code":"@Override public void proxySelectStart(Call call, HttpUrl url) {\n printEvent(\"proxySelectStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":105,"symbol":"proxySelectEnd","kind":"method","lang":"java","code":"@Override public void proxySelectEnd(Call call, HttpUrl url, List proxies) {\n printEvent(\"proxySelectEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":109,"symbol":"callStart","kind":"method","lang":"java","code":"@Override public void callStart(Call call) {\n printEvent(\"callStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":113,"symbol":"dnsStart","kind":"method","lang":"java","code":"@Override public void dnsStart(Call call, String domainName) {\n printEvent(\"dnsStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":117,"symbol":"dnsEnd","kind":"method","lang":"java","code":"@Override public void dnsEnd(Call call, String domainName, List inetAddressList) {\n printEvent(\"dnsEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":121,"symbol":"connectStart","kind":"method","lang":"java","code":"@Override public void connectStart(\n Call call, InetSocketAddress inetSocketAddress, Proxy proxy) {\n printEvent(\"connectStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":126,"symbol":"secureConnectStart","kind":"method","lang":"java","code":"@Override public void secureConnectStart(Call call) {\n printEvent(\"secureConnectStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":130,"symbol":"secureConnectEnd","kind":"method","lang":"java","code":"@Override public void secureConnectEnd(Call call, Handshake handshake) {\n printEvent(\"secureConnectEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":134,"symbol":"connectEnd","kind":"method","lang":"java","code":"@Override public void connectEnd(\n Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol) {\n printEvent(\"connectEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":139,"symbol":"connectFailed","kind":"method","lang":"java","code":"@Override public void connectFailed(Call call, InetSocketAddress inetSocketAddress, Proxy proxy,\n Protocol protocol, IOException ioe) {\n printEvent(\"connectFailed\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":144,"symbol":"connectionAcquired","kind":"method","lang":"java","code":"@Override public void connectionAcquired(Call call, Connection connection) {\n printEvent(\"connectionAcquired\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":148,"symbol":"connectionReleased","kind":"method","lang":"java","code":"@Override public void connectionReleased(Call call, Connection connection) {\n printEvent(\"connectionReleased\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":152,"symbol":"requestHeadersStart","kind":"method","lang":"java","code":"@Override public void requestHeadersStart(Call call) {\n printEvent(\"requestHeadersStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":156,"symbol":"requestHeadersEnd","kind":"method","lang":"java","code":"@Override public void requestHeadersEnd(Call call, Request request) {\n printEvent(\"requestHeadersEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":160,"symbol":"requestBodyStart","kind":"method","lang":"java","code":"@Override public void requestBodyStart(Call call) {\n printEvent(\"requestBodyStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":164,"symbol":"requestBodyEnd","kind":"method","lang":"java","code":"@Override public void requestBodyEnd(Call call, long byteCount) {\n printEvent(\"requestBodyEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":168,"symbol":"requestFailed","kind":"method","lang":"java","code":"@Override public void requestFailed(Call call, IOException ioe) {\n printEvent(\"requestFailed\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":172,"symbol":"responseHeadersStart","kind":"method","lang":"java","code":"@Override public void responseHeadersStart(Call call) {\n printEvent(\"responseHeadersStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":176,"symbol":"responseHeadersEnd","kind":"method","lang":"java","code":"@Override public void responseHeadersEnd(Call call, Response response) {\n printEvent(\"responseHeadersEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":180,"symbol":"responseBodyStart","kind":"method","lang":"java","code":"@Override public void responseBodyStart(Call call) {\n printEvent(\"responseBodyStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":184,"symbol":"responseBodyEnd","kind":"method","lang":"java","code":"@Override public void responseBodyEnd(Call call, long byteCount) {\n printEvent(\"responseBodyEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":188,"symbol":"responseFailed","kind":"method","lang":"java","code":"@Override public void responseFailed(Call call, IOException ioe) {\n printEvent(\"responseFailed\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":192,"symbol":"callEnd","kind":"method","lang":"java","code":"@Override public void callEnd(Call call) {\n printEvent(\"callEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":196,"symbol":"callFailed","kind":"method","lang":"java","code":"@Override public void callFailed(Call call, IOException ioe) {\n printEvent(\"callFailed\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEvents.java","line":200,"symbol":"canceled","kind":"method","lang":"java","code":"@Override public void canceled(Call call) {\n printEvent(\"canceled\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":37,"symbol":"PrintEventsNonConcurrent","kind":"class","lang":"java","doc":"This prints events for a single in-flight call. It won't work for multiple concurrent calls because we don't know what callStartNanos refers to.","code":"public final class PrintEventsNonConcurrent {\n private final OkHttpClient client = new OkHttpClient.Builder()\n .eventListener(new PrintingEventListener())\n .build();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n System.out.println(\"REQUEST 1 (new connection)\");\n try (Response response = client.newCall(request).execute()) {\n // Consume and discard the response body.\n response.body().source().readByteString();\n }\n\n System.out.println(\"REQUEST 2 (pooled connection)\");\n try (Response response = client.newCall(request).execute()) {\n // Consume and discard the response body.\n response.body().source().readByteString();\n }\n }\n\n public static void main(String... args) throws Exception {\n new PrintEventsNonConcurrent().run();\n }\n\n private static final class PrintingEventListener extends EventListener {\n long callStartNanos;\n\n private void printEvent(String name) {\n long nowNanos = System.nanoTime();\n if (name.equals(\"callStart\")) {\n callStartNanos = nowNanos;\n }\n long elapsedNanos = nowNanos "} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":42,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n System.out.println(\"REQUEST 1 (new connection)\");\n try (Response response = client.newCall(request).execute()) {\n // Consume and discard the response body.\n response.body().source().readByteString();\n }\n\n System.out.println(\"REQUEST 2 (pooled connection)\");\n try (Response response = client.newCall(request).execute()) {\n // Consume and discard the response body.\n response.body().source().readByteString();\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":60,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new PrintEventsNonConcurrent().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":64,"symbol":"PrintingEventListener","kind":"class","lang":"java","code":"private static final class PrintingEventListener extends EventListener {\n long callStartNanos;\n\n private void printEvent(String name) {\n long nowNanos = System.nanoTime();\n if (name.equals(\"callStart\")) {\n callStartNanos = nowNanos;\n }\n long elapsedNanos = nowNanos - callStartNanos;\n System.out.printf(\"%.3f %s%n\", elapsedNanos / 1000000000d, name);\n }\n\n @Override public void callStart(Call call) {\n printEvent(\"callStart\");\n }\n\n @Override public void proxySelectStart(Call call, HttpUrl url) {\n printEvent(\"proxySelectStart\");\n }\n\n @Override public void proxySelectEnd(Call call, HttpUrl url, List proxies) {\n printEvent(\"proxySelectEnd\");\n }\n\n @Override public void dnsStart(Call call, String domainName) {\n printEvent(\"dnsStart\");\n }\n\n @Override public void dnsEnd(Call call, String domainName, List inetAddressList) {\n printEvent(\"dnsEnd\");\n }\n\n @Override public void connectStart(\n Call call, InetSocketAddress inetSocketAddress, Proxy proxy) {\n printEvent(\"connectStart\");\n }\n\n @Override public void secureConnectStart(Call call) {\n printEvent(\"secur"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":67,"symbol":"printEvent","kind":"method","lang":"java","code":"private void printEvent(String name) {\n long nowNanos = System.nanoTime();\n if (name.equals(\"callStart\")) {\n callStartNanos = nowNanos;\n }\n long elapsedNanos = nowNanos - callStartNanos;\n System.out.printf(\"%.3f %s%n\", elapsedNanos / 1000000000d, name);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":76,"symbol":"callStart","kind":"method","lang":"java","code":"@Override public void callStart(Call call) {\n printEvent(\"callStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":80,"symbol":"proxySelectStart","kind":"method","lang":"java","code":"@Override public void proxySelectStart(Call call, HttpUrl url) {\n printEvent(\"proxySelectStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":84,"symbol":"proxySelectEnd","kind":"method","lang":"java","code":"@Override public void proxySelectEnd(Call call, HttpUrl url, List proxies) {\n printEvent(\"proxySelectEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":88,"symbol":"dnsStart","kind":"method","lang":"java","code":"@Override public void dnsStart(Call call, String domainName) {\n printEvent(\"dnsStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":92,"symbol":"dnsEnd","kind":"method","lang":"java","code":"@Override public void dnsEnd(Call call, String domainName, List inetAddressList) {\n printEvent(\"dnsEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":96,"symbol":"connectStart","kind":"method","lang":"java","code":"@Override public void connectStart(\n Call call, InetSocketAddress inetSocketAddress, Proxy proxy) {\n printEvent(\"connectStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":101,"symbol":"secureConnectStart","kind":"method","lang":"java","code":"@Override public void secureConnectStart(Call call) {\n printEvent(\"secureConnectStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":105,"symbol":"secureConnectEnd","kind":"method","lang":"java","code":"@Override public void secureConnectEnd(Call call, Handshake handshake) {\n printEvent(\"secureConnectEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":109,"symbol":"connectEnd","kind":"method","lang":"java","code":"@Override public void connectEnd(\n Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol) {\n printEvent(\"connectEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":114,"symbol":"connectFailed","kind":"method","lang":"java","code":"@Override public void connectFailed(Call call, InetSocketAddress inetSocketAddress, Proxy proxy,\n Protocol protocol, IOException ioe) {\n printEvent(\"connectFailed\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":119,"symbol":"connectionAcquired","kind":"method","lang":"java","code":"@Override public void connectionAcquired(Call call, Connection connection) {\n printEvent(\"connectionAcquired\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":123,"symbol":"connectionReleased","kind":"method","lang":"java","code":"@Override public void connectionReleased(Call call, Connection connection) {\n printEvent(\"connectionReleased\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":127,"symbol":"requestHeadersStart","kind":"method","lang":"java","code":"@Override public void requestHeadersStart(Call call) {\n printEvent(\"requestHeadersStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":131,"symbol":"requestHeadersEnd","kind":"method","lang":"java","code":"@Override public void requestHeadersEnd(Call call, Request request) {\n printEvent(\"requestHeadersEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":135,"symbol":"requestBodyStart","kind":"method","lang":"java","code":"@Override public void requestBodyStart(Call call) {\n printEvent(\"requestBodyStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":139,"symbol":"requestBodyEnd","kind":"method","lang":"java","code":"@Override public void requestBodyEnd(Call call, long byteCount) {\n printEvent(\"requestBodyEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":143,"symbol":"requestFailed","kind":"method","lang":"java","code":"@Override public void requestFailed(Call call, IOException ioe) {\n printEvent(\"requestFailed\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":147,"symbol":"responseHeadersStart","kind":"method","lang":"java","code":"@Override public void responseHeadersStart(Call call) {\n printEvent(\"responseHeadersStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":151,"symbol":"responseHeadersEnd","kind":"method","lang":"java","code":"@Override public void responseHeadersEnd(Call call, Response response) {\n printEvent(\"responseHeadersEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":155,"symbol":"responseBodyStart","kind":"method","lang":"java","code":"@Override public void responseBodyStart(Call call) {\n printEvent(\"responseBodyStart\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":159,"symbol":"responseBodyEnd","kind":"method","lang":"java","code":"@Override public void responseBodyEnd(Call call, long byteCount) {\n printEvent(\"responseBodyEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":163,"symbol":"responseFailed","kind":"method","lang":"java","code":"@Override public void responseFailed(Call call, IOException ioe) {\n printEvent(\"responseFailed\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":167,"symbol":"callEnd","kind":"method","lang":"java","code":"@Override public void callEnd(Call call) {\n printEvent(\"callEnd\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":171,"symbol":"callFailed","kind":"method","lang":"java","code":"@Override public void callFailed(Call call, IOException ioe) {\n printEvent(\"callFailed\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/PrintEventsNonConcurrent.java","line":175,"symbol":"canceled","kind":"method","lang":"java","code":"@Override public void canceled(Call call) {\n printEvent(\"canceled\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":30,"symbol":"Progress","kind":"class","lang":"java","code":"public final class Progress {\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n final ProgressListener progressListener = new ProgressListener() {\n boolean firstUpdate = true;\n\n @Override public void update(long bytesRead, long contentLength, boolean done) {\n if (done) {\n System.out.println(\"completed\");\n } else {\n if (firstUpdate) {\n firstUpdate = false;\n if (contentLength == -1) {\n System.out.println(\"content-length: unknown\");\n } else {\n System.out.format(\"content-length: %d\\n\", contentLength);\n }\n }\n\n System.out.println(bytesRead);\n\n if (contentLength != -1) {\n System.out.format(\"%d%% done\\n\", (100 * bytesRead) / contentLength);\n }\n }\n }\n };\n\n OkHttpClient client = new OkHttpClient.Builder()\n .addNetworkInterceptor(chain -> {\n Response originalResponse = chain.proceed(chain.request());\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(o"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":32,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n final ProgressListener progressListener = new ProgressListener() {\n boolean firstUpdate = true;\n\n @Override public void update(long bytesRead, long contentLength, boolean done) {\n if (done) {\n System.out.println(\"completed\");\n } else {\n if (firstUpdate) {\n firstUpdate = false;\n if (contentLength == -1) {\n System.out.println(\"content-length: unknown\");\n } else {\n System.out.format(\"content-length: %d\\n\", contentLength);\n }\n }\n\n System.out.println(bytesRead);\n\n if (contentLength != -1) {\n System.out.format(\"%d%% done\\n\", (100 * bytesRead) / contentLength);\n }\n }\n }\n };\n\n OkHttpClient client = new OkHttpClient.Builder()\n .addNetworkInterceptor(chain -> {\n Response originalResponse = chain.proceed(chain.request());\n return originalResponse.newBuilder()\n .body(new ProgressResponseBody(originalResponse.body(), progressL"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":40,"symbol":"update","kind":"method","lang":"java","code":"@Override public void update(long bytesRead, long contentLength, boolean done) {\n if (done) {\n System.out.println(\"completed\");\n } else {\n if (firstUpdate) {\n firstUpdate = false;\n if (contentLength == -1) {\n System.out.println(\"content-length: unknown\");\n } else {\n System.out.format(\"content-length: %d\\n\", contentLength);\n }\n }\n\n System.out.println(bytesRead);\n\n if (contentLength != -1) {\n System.out.format(\"%d%% done\\n\", (100 * bytesRead) / contentLength);\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":78,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new Progress().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":82,"symbol":"ProgressResponseBody","kind":"class","lang":"java","code":"private static class ProgressResponseBody extends ResponseBody {\n\n private final ResponseBody responseBody;\n private final ProgressListener progressListener;\n private BufferedSource bufferedSource;\n\n ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {\n this.responseBody = responseBody;\n this.progressListener = progressListener;\n }\n\n @Override public MediaType contentType() {\n return responseBody.contentType();\n }\n\n @Override public long contentLength() {\n return responseBody.contentLength();\n }\n\n @Override public BufferedSource source() {\n if (bufferedSource == null) {\n bufferedSource = Okio.buffer(source(responseBody.source()));\n }\n return bufferedSource;\n }\n\n private Source source(Source source) {\n return new ForwardingSource(source) {\n long totalBytesRead = 0L;\n\n @Override public long read(Buffer sink, long byteCount) throws IOException {\n long bytesRead = super.read(sink, byteCount);\n // read() returns the number of bytes read, or -1 if this source is exhausted.\n totalBytesRead += bytesRead != -1 ? bytesRead : 0;\n "} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":88,"symbol":"ProgressResponseBody","kind":"constructor","lang":"java","code":"ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {\n this.responseBody = responseBody;\n this.progressListener = progressListener;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":93,"symbol":"contentType","kind":"method","lang":"java","code":"@Override public MediaType contentType() {\n return responseBody.contentType();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":97,"symbol":"contentLength","kind":"method","lang":"java","code":"@Override public long contentLength() {\n return responseBody.contentLength();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":101,"symbol":"source","kind":"method","lang":"java","code":"@Override public BufferedSource source() {\n if (bufferedSource == null) {\n bufferedSource = Okio.buffer(source(responseBody.source()));\n }\n return bufferedSource;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":108,"symbol":"source","kind":"method","lang":"java","code":"private Source source(Source source) {\n return new ForwardingSource(source) {\n long totalBytesRead = 0L;\n\n @Override public long read(Buffer sink, long byteCount) throws IOException {\n long bytesRead = super.read(sink, byteCount);\n // read() returns the number of bytes read, or -1 if this source is exhausted.\n totalBytesRead += bytesRead != -1 ? bytesRead : 0;\n progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);\n return bytesRead;\n }\n };\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":112,"symbol":"read","kind":"method","lang":"java","code":"@Override public long read(Buffer sink, long byteCount) throws IOException {\n long bytesRead = super.read(sink, byteCount);\n // read() returns the number of bytes read, or -1 if this source is exhausted.\n totalBytesRead += bytesRead != -1 ? bytesRead : 0;\n progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);\n return bytesRead;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":123,"symbol":"ProgressListener","kind":"interface","lang":"java","code":"interface ProgressListener {\n void update(long bytesRead, long contentLength, boolean done);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/Progress.java","line":124,"symbol":"update","kind":"method","lang":"java","code":"void update(long bytesRead, long contentLength, boolean done);"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RequestBodyCompression.java","line":31,"symbol":"RequestBodyCompression","kind":"class","lang":"java","code":"public final class RequestBodyCompression {\n /**\n * The Google API KEY for OkHttp recipes. If you're using Google APIs for anything other than\n * running these examples, please request your own client ID!\n *\n * https://console.developers.google.com/project\n */\n public static final String GOOGLE_API_KEY = \"AIzaSyAx2WZYe0My0i-uGurpvraYJxO7XNbwiGs\";\n public static final MediaType MEDIA_TYPE_JSON = MediaType.get(\"application/json\");\n\n private final OkHttpClient client = new OkHttpClient.Builder()\n .addInterceptor(new GzipRequestInterceptor())\n .build();\n private final Moshi moshi = new Moshi.Builder().build();\n private final JsonAdapter> mapJsonAdapter = moshi.adapter(\n Types.newParameterizedType(Map.class, String.class, String.class));\n\n public void run() throws Exception {\n Map requestBody = new LinkedHashMap<>();\n requestBody.put(\"longUrl\", \"https://publicobject.com/2014/12/04/html-formatting-javadocs/\");\n RequestBody jsonRequestBody = RequestBody.create(\n mapJsonAdapter.toJson(requestBody), MEDIA_TYPE_JSON);\n Request request = new Request.Builder()\n .url(\"https://www.googleapis.com/urlshor"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RequestBodyCompression.java","line":48,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Map requestBody = new LinkedHashMap<>();\n requestBody.put(\"longUrl\", \"https://publicobject.com/2014/12/04/html-formatting-javadocs/\");\n RequestBody jsonRequestBody = RequestBody.create(\n mapJsonAdapter.toJson(requestBody), MEDIA_TYPE_JSON);\n Request request = new Request.Builder()\n .url(\"https://www.googleapis.com/urlshortener/v1/url?key=\" + GOOGLE_API_KEY)\n .post(jsonRequestBody)\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RequestBodyCompression.java","line":65,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new RequestBodyCompression().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RequestBodyCompression.java","line":70,"symbol":"GzipRequestInterceptor","kind":"class","lang":"java","doc":"This interceptor compresses the HTTP request body. Many webservers can't handle this!","code":"static class GzipRequestInterceptor implements Interceptor {\n @Override public Response intercept(Chain chain) throws IOException {\n Request originalRequest = chain.request();\n if (originalRequest.body() == null || originalRequest.header(\"Content-Encoding\") != null) {\n return chain.proceed(originalRequest);\n }\n\n Request compressedRequest = originalRequest.newBuilder()\n .gzip()\n .build();\n return chain.proceed(compressedRequest);\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RequestBodyCompression.java","line":71,"symbol":"intercept","kind":"method","lang":"java","code":"@Override public Response intercept(Chain chain) throws IOException {\n Request originalRequest = chain.request();\n if (originalRequest.body() == null || originalRequest.header(\"Content-Encoding\") != null) {\n return chain.proceed(originalRequest);\n }\n\n Request compressedRequest = originalRequest.newBuilder()\n .gzip()\n .build();\n return chain.proceed(compressedRequest);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RewriteResponseCacheControl.java","line":26,"symbol":"RewriteResponseCacheControl","kind":"class","lang":"java","code":"public final class RewriteResponseCacheControl {\n /** Dangerous interceptor that rewrites the server's cache-control header. */\n private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = chain -> {\n Response originalResponse = chain.proceed(chain.request());\n return originalResponse.newBuilder()\n .header(\"Cache-Control\", \"max-age=60\")\n .build();\n };\n\n private final OkHttpClient client;\n\n public RewriteResponseCacheControl(File cacheDirectory) throws Exception {\n Cache cache = new Cache(cacheDirectory, 1024 * 1024);\n cache.evictAll();\n\n client = new OkHttpClient.Builder()\n .cache(cache)\n .build();\n }\n\n public void run() throws Exception {\n for (int i = 0; i < 5; i++) {\n System.out.println(\" Request: \" + i);\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/search/repositories?q=http\")\n .build();\n\n OkHttpClient clientForCall;\n if (i == 2) {\n // Force this request's response to be written to the cache. This way, subsequent responses\n // can be read from the cache.\n System.out.println(\"Force cache: true\");\n clientForCall = client.new"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RewriteResponseCacheControl.java","line":37,"symbol":"RewriteResponseCacheControl","kind":"constructor","lang":"java","code":"public RewriteResponseCacheControl(File cacheDirectory) throws Exception {\n Cache cache = new Cache(cacheDirectory, 1024 * 1024);\n cache.evictAll();\n\n client = new OkHttpClient.Builder()\n .cache(cache)\n .build();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RewriteResponseCacheControl.java","line":46,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n for (int i = 0; i < 5; i++) {\n System.out.println(\" Request: \" + i);\n\n Request request = new Request.Builder()\n .url(\"https://api.github.com/search/repositories?q=http\")\n .build();\n\n OkHttpClient clientForCall;\n if (i == 2) {\n // Force this request's response to be written to the cache. This way, subsequent responses\n // can be read from the cache.\n System.out.println(\"Force cache: true\");\n clientForCall = client.newBuilder()\n .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)\n .build();\n } else {\n System.out.println(\"Force cache: false\");\n clientForCall = client;\n }\n\n try (Response response = clientForCall.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n System.out.println(\" Network: \" + (response.networkResponse() != null));\n System.out.println();\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/RewriteResponseCacheControl.java","line":76,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new RewriteResponseCacheControl(new File(\"RewriteResponseCacheControl.tmp\")).run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/SynchronousGet.java","line":24,"symbol":"SynchronousGet","kind":"class","lang":"java","code":"public final class SynchronousGet {\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n Headers responseHeaders = response.headers();\n for (int i = 0; i < responseHeaders.size(); i++) {\n System.out.println(responseHeaders.name(i) + \": \" + responseHeaders.value(i));\n }\n\n System.out.println(response.body().string());\n }\n }\n\n public static void main(String... args) throws Exception {\n new SynchronousGet().run();\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/SynchronousGet.java","line":27,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n Request request = new Request.Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n Headers responseHeaders = response.headers();\n for (int i = 0; i < responseHeaders.size(); i++) {\n System.out.println(responseHeaders.name(i) + \": \" + responseHeaders.value(i));\n }\n\n System.out.println(response.body().string());\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/SynchronousGet.java","line":44,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new SynchronousGet().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":31,"symbol":"UploadProgress","kind":"class","lang":"java","code":"public final class UploadProgress {\n private static final String IMGUR_CLIENT_ID = \"9199fdef135c122\";\n private static final MediaType MEDIA_TYPE_PNG = MediaType.get(\"image/png\");\n\n private final OkHttpClient client = new OkHttpClient();\n\n public void run() throws Exception {\n // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image\n final ProgressListener progressListener = new ProgressListener() {\n boolean firstUpdate = true;\n\n @Override public void update(long bytesWritten, long contentLength, boolean done) {\n if (done) {\n System.out.println(\"completed\");\n } else {\n if (firstUpdate) {\n firstUpdate = false;\n if (contentLength == -1) {\n System.out.println(\"content-length: unknown\");\n } else {\n System.out.format(\"content-length: %d\\n\", contentLength);\n }\n }\n\n System.out.println(bytesWritten);\n\n if (contentLength != -1) {\n System.out.format(\"%d%% done\\n\", (100 * bytesWritten) / contentLength);\n }\n }\n }\n };\n\n RequestBody requestBody = RequestBody.create(\n new File("} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":37,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image\n final ProgressListener progressListener = new ProgressListener() {\n boolean firstUpdate = true;\n\n @Override public void update(long bytesWritten, long contentLength, boolean done) {\n if (done) {\n System.out.println(\"completed\");\n } else {\n if (firstUpdate) {\n firstUpdate = false;\n if (contentLength == -1) {\n System.out.println(\"content-length: unknown\");\n } else {\n System.out.format(\"content-length: %d\\n\", contentLength);\n }\n }\n\n System.out.println(bytesWritten);\n\n if (contentLength != -1) {\n System.out.format(\"%d%% done\\n\", (100 * bytesWritten) / contentLength);\n }\n }\n }\n };\n\n RequestBody requestBody = RequestBody.create(\n new File(\"docs/images/logo-square.png\"),\n MEDIA_TYPE_PNG);\n\n Request request = new Request.Builder()\n .header(\"Authorization\", \"Client-ID \" + IMGUR_CLIENT_ID)\n .url(\"https://api.imgur.com/3/image\")\n .post(new ProgressRequestBody("} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":42,"symbol":"update","kind":"method","lang":"java","code":"@Override public void update(long bytesWritten, long contentLength, boolean done) {\n if (done) {\n System.out.println(\"completed\");\n } else {\n if (firstUpdate) {\n firstUpdate = false;\n if (contentLength == -1) {\n System.out.println(\"content-length: unknown\");\n } else {\n System.out.format(\"content-length: %d\\n\", contentLength);\n }\n }\n\n System.out.println(bytesWritten);\n\n if (contentLength != -1) {\n System.out.format(\"%d%% done\\n\", (100 * bytesWritten) / contentLength);\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":80,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new UploadProgress().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":84,"symbol":"ProgressRequestBody","kind":"class","lang":"java","code":"private static class ProgressRequestBody extends RequestBody {\n\n private final ProgressListener progressListener;\n private final RequestBody delegate;\n\n public ProgressRequestBody(RequestBody delegate, ProgressListener progressListener) {\n this.delegate = delegate;\n this.progressListener = progressListener;\n }\n\n @Override\n public MediaType contentType() {\n return delegate.contentType();\n }\n\n @Override\n public long contentLength() throws IOException {\n return delegate.contentLength();\n }\n\n @Override\n public void writeTo(BufferedSink sink) throws IOException {\n BufferedSink bufferedSink = Okio.buffer(sink(sink));\n delegate.writeTo(bufferedSink);\n bufferedSink.flush();\n }\n\n public Sink sink(Sink sink) {\n return new ForwardingSink(sink) {\n private long totalBytesWritten = 0L;\n private boolean completed = false;\n\n @Override\n public void write(Buffer source, long byteCount) throws IOException {\n super.write(source, byteCount);\n totalBytesWritten += byteCount;\n progressListener.update(totalBytesWritten, contentLength(), completed);\n }\n\n @Ov"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":89,"symbol":"ProgressRequestBody","kind":"constructor","lang":"java","code":"public ProgressRequestBody(RequestBody delegate, ProgressListener progressListener) {\n this.delegate = delegate;\n this.progressListener = progressListener;\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":94,"symbol":"contentType","kind":"method","lang":"java","code":"@Override\n public MediaType contentType() {\n return delegate.contentType();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":99,"symbol":"contentLength","kind":"method","lang":"java","code":"@Override\n public long contentLength() throws IOException {\n return delegate.contentLength();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":104,"symbol":"writeTo","kind":"method","lang":"java","code":"@Override\n public void writeTo(BufferedSink sink) throws IOException {\n BufferedSink bufferedSink = Okio.buffer(sink(sink));\n delegate.writeTo(bufferedSink);\n bufferedSink.flush();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":111,"symbol":"sink","kind":"method","lang":"java","code":"public Sink sink(Sink sink) {\n return new ForwardingSink(sink) {\n private long totalBytesWritten = 0L;\n private boolean completed = false;\n\n @Override\n public void write(Buffer source, long byteCount) throws IOException {\n super.write(source, byteCount);\n totalBytesWritten += byteCount;\n progressListener.update(totalBytesWritten, contentLength(), completed);\n }\n\n @Override\n public void close() throws IOException {\n super.close();\n if (!completed) {\n completed = true;\n progressListener.update(totalBytesWritten, contentLength(), completed);\n }\n }\n };\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":116,"symbol":"write","kind":"method","lang":"java","code":"@Override\n public void write(Buffer source, long byteCount) throws IOException {\n super.write(source, byteCount);\n totalBytesWritten += byteCount;\n progressListener.update(totalBytesWritten, contentLength(), completed);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":123,"symbol":"close","kind":"method","lang":"java","code":"@Override\n public void close() throws IOException {\n super.close();\n if (!completed) {\n completed = true;\n progressListener.update(totalBytesWritten, contentLength(), completed);\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":135,"symbol":"ProgressListener","kind":"interface","lang":"java","code":"interface ProgressListener {\n void update(long bytesWritten, long contentLength, boolean done);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","line":136,"symbol":"update","kind":"method","lang":"java","code":"void update(long bytesWritten, long contentLength, boolean done);"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java","line":11,"symbol":"WebSocketEcho","kind":"class","lang":"java","code":"public final class WebSocketEcho extends WebSocketListener {\n private void run() {\n OkHttpClient client = new OkHttpClient.Builder()\n .readTimeout(0, TimeUnit.MILLISECONDS)\n .build();\n\n Request request = new Request.Builder()\n .url(\"ws://echo.websocket.org\")\n .build();\n client.newWebSocket(request, this);\n\n // Trigger shutdown of the dispatcher's executor so this process exits immediately.\n client.dispatcher().executorService().shutdown();\n }\n\n @Override public void onOpen(WebSocket webSocket, Response response) {\n webSocket.send(\"Hello...\");\n webSocket.send(\"...World!\");\n webSocket.send(ByteString.decodeHex(\"deadbeef\"));\n webSocket.close(1000, \"Goodbye, World!\");\n }\n\n @Override public void onMessage(WebSocket webSocket, String text) {\n System.out.println(\"MESSAGE: \" + text);\n }\n\n @Override public void onMessage(WebSocket webSocket, ByteString bytes) {\n System.out.println(\"MESSAGE: \" + bytes.hex());\n }\n\n @Override public void onClosing(WebSocket webSocket, int code, String reason) {\n webSocket.close(1000, null);\n System.out.println(\"CLOSE: \" + code + \" \" + reason);\n }\n\n @Override public void onFailure(We"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java","line":12,"symbol":"run","kind":"method","lang":"java","code":"private void run() {\n OkHttpClient client = new OkHttpClient.Builder()\n .readTimeout(0, TimeUnit.MILLISECONDS)\n .build();\n\n Request request = new Request.Builder()\n .url(\"ws://echo.websocket.org\")\n .build();\n client.newWebSocket(request, this);\n\n // Trigger shutdown of the dispatcher's executor so this process exits immediately.\n client.dispatcher().executorService().shutdown();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java","line":26,"symbol":"onOpen","kind":"method","lang":"java","code":"@Override public void onOpen(WebSocket webSocket, Response response) {\n webSocket.send(\"Hello...\");\n webSocket.send(\"...World!\");\n webSocket.send(ByteString.decodeHex(\"deadbeef\"));\n webSocket.close(1000, \"Goodbye, World!\");\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java","line":33,"symbol":"onMessage","kind":"method","lang":"java","code":"@Override public void onMessage(WebSocket webSocket, String text) {\n System.out.println(\"MESSAGE: \" + text);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java","line":37,"symbol":"onMessage","kind":"method","lang":"java","code":"@Override public void onMessage(WebSocket webSocket, ByteString bytes) {\n System.out.println(\"MESSAGE: \" + bytes.hex());\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java","line":41,"symbol":"onClosing","kind":"method","lang":"java","code":"@Override public void onClosing(WebSocket webSocket, int code, String reason) {\n webSocket.close(1000, null);\n System.out.println(\"CLOSE: \" + code + \" \" + reason);\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java","line":46,"symbol":"onFailure","kind":"method","lang":"java","code":"@Override public void onFailure(WebSocket webSocket, Throwable t, Response response) {\n t.printStackTrace();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java","line":50,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) {\n new WebSocketEcho().run();\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/AccessHeaders.kt","line":22,"symbol":"AccessHeaders","kind":"class","lang":"kotlin","code":"class AccessHeaders {\n private val client = OkHttpClient()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"https://api.github.com/repos/lysine-dev/okhttp/issues\")\n .header(\"User-Agent\", \"OkHttp Headers.java\")\n .addHeader(\"Accept\", \"application/json; q=0.5\")\n .addHeader(\"Accept\", \"application/vnd.github.v3+json\")\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(\"Server: ${response.header(\"Server\")}\")\n println(\"Date: ${response.header(\"Date\")}\")\n println(\"Vary: ${response.headers(\"Vary\")}\")\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/AccessHeaders.kt","line":25,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"https://api.github.com/repos/lysine-dev/okhttp/issues\")\n .header(\"User-Agent\", \"OkHttp Headers.java\")\n .addHeader(\"Accept\", \"application/json; q=0.5\")\n .addHeader(\"Accept\", \"application/vnd.github.v3+json\")\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(\"Server: ${response.header(\"Server\")}\")\n println(\"Date: ${response.header(\"Date\")}\")\n println(\"Vary: ${response.headers(\"Vary\")}\")\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/AccessHeaders.kt","line":45,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n AccessHeaders().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/AsynchronousGet.kt","line":25,"symbol":"AsynchronousGet","kind":"class","lang":"kotlin","code":"class AsynchronousGet {\n private val client = OkHttpClient()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build()\n\n client.newCall(request).enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n e.printStackTrace()\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.use {\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n for ((name, value) in response.headers) {\n println(\"$name: $value\")\n }\n\n println(response.body.string())\n }\n }\n },\n )\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/AsynchronousGet.kt","line":28,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build()\n\n client.newCall(request).enqueue(\n object : Callback {\n override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n e.printStackTrace()\n }\n\n override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.use {\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n for ((name, value) in response.headers) {\n println(\"$name: $value\")\n }\n\n println(response.body.string())\n }\n }\n },\n )\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/AsynchronousGet.kt","line":37,"symbol":"onFailure","kind":"function","lang":"kotlin","code":"override fun onFailure(\n call: Call,\n e: IOException,\n ) {\n e.printStackTrace()\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/AsynchronousGet.kt","line":44,"symbol":"onResponse","kind":"function","lang":"kotlin","code":"override fun onResponse(\n call: Call,\n response: Response,\n ) {\n response.use {\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n for ((name, value) in response.headers) {\n println(\"$name: $value\")\n }\n\n println(response.body.string())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/AsynchronousGet.kt","line":63,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n AsynchronousGet().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/Authenticate.kt","line":26,"symbol":"Authenticate","kind":"class","lang":"kotlin","code":"class Authenticate {\n private val client =\n OkHttpClient\n .Builder()\n .authenticator(\n object : Authenticator {\n @Throws(IOException::class)\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? {\n if (response.request.header(\"Authorization\") != null) {\n return null // Give up, we've already attempted to authenticate.\n }\n\n println(\"Authenticating for response: $response\")\n println(\"Challenges: ${response.challenges()}\")\n val credential = Credentials.basic(\"jesse\", \"password1\")\n return response.request\n .newBuilder()\n .header(\"Authorization\", credential)\n .build()\n }\n },\n ).build()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://publicobject.com/secrets/hellosecret.txt\")\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/Authenticate.kt","line":32,"symbol":"authenticate","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun authenticate(\n route: Route?,\n response: Response,\n ): Request? {\n if (response.request.header(\"Authorization\") != null) {\n return null // Give up, we've already attempted to authenticate.\n }\n\n println(\"Authenticating for response: $response\")\n println(\"Challenges: ${response.challenges()}\")\n val credential = Credentials.basic(\"jesse\", \"password1\")\n return response.request\n .newBuilder()\n .header(\"Authorization\", credential)\n .build()\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/Authenticate.kt","line":52,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://publicobject.com/secrets/hellosecret.txt\")\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/Authenticate.kt","line":67,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n Authenticate().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CacheResponse.kt","line":24,"symbol":"CacheResponse","kind":"class","lang":"kotlin","code":"class CacheResponse(\n cacheDirectory: File,\n) {\n private val client: OkHttpClient =\n OkHttpClient\n .Builder()\n .cache(\n Cache(\n directory = cacheDirectory,\n // 1 MiB.\n maxSize = 10L * 1024L * 1024L,\n ),\n ).build()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build()\n\n val response1Body =\n client.newCall(request).execute().use {\n if (!it.isSuccessful) throw IOException(\"Unexpected code $it\")\n\n println(\"Response 1 response: $it\")\n println(\"Response 1 cache response: ${it.cacheResponse}\")\n println(\"Response 1 network response: ${it.networkResponse}\")\n return@use it.body.string()\n }\n\n val response2Body =\n client.newCall(request).execute().use {\n if (!it.isSuccessful) throw IOException(\"Unexpected code $it\")\n\n println(\"Response 2 response: $it\")\n println(\"Response 2 cache response: ${it.cacheResponse}\")\n println(\"Response 2 network response: ${it.networkResponse}\")\n return@use it.body.string()\n }\n\n println(\"Response 2 eq"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CacheResponse.kt","line":38,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build()\n\n val response1Body =\n client.newCall(request).execute().use {\n if (!it.isSuccessful) throw IOException(\"Unexpected code $it\")\n\n println(\"Response 1 response: $it\")\n println(\"Response 1 cache response: ${it.cacheResponse}\")\n println(\"Response 1 network response: ${it.networkResponse}\")\n return@use it.body.string()\n }\n\n val response2Body =\n client.newCall(request).execute().use {\n if (!it.isSuccessful) throw IOException(\"Unexpected code $it\")\n\n println(\"Response 2 response: $it\")\n println(\"Response 2 cache response: ${it.cacheResponse}\")\n println(\"Response 2 network response: ${it.networkResponse}\")\n return@use it.body.string()\n }\n\n println(\"Response 2 equals Response 1? \" + (response1Body == response2Body))\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CacheResponse.kt","line":69,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n CacheResponse(File(\"CacheResponse.tmp\")).run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CancelCall.kt","line":24,"symbol":"CancelCall","kind":"class","lang":"kotlin","code":"class CancelCall {\n private val executor = Executors.newScheduledThreadPool(1)\n private val client = OkHttpClient()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://httpbin.org/delay/2\") // This URL is served with a 2 second delay.\n .build()\n\n val startNanos = System.nanoTime()\n val call = client.newCall(request)\n\n // Schedule a job to cancel the call in 1 second.\n executor.schedule({\n System.out.printf(\"%.2f Canceling call.%n\", (System.nanoTime() - startNanos) / 1e9f)\n call.cancel()\n System.out.printf(\"%.2f Canceled call.%n\", (System.nanoTime() - startNanos) / 1e9f)\n }, 1, TimeUnit.SECONDS)\n\n System.out.printf(\"%.2f Executing call.%n\", (System.nanoTime() - startNanos) / 1e9f)\n try {\n call.execute().use { response ->\n System.out.printf(\n \"%.2f Call was expected to fail, but completed: %s%n\",\n (System.nanoTime() - startNanos) / 1e9f,\n response,\n )\n }\n } catch (e: IOException) {\n System.out.printf(\n \"%.2f Call failed as expected: %s%n\",\n (System.nanoTime() - startNanos) / 1e9f,\n e,\n )\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CancelCall.kt","line":28,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://httpbin.org/delay/2\") // This URL is served with a 2 second delay.\n .build()\n\n val startNanos = System.nanoTime()\n val call = client.newCall(request)\n\n // Schedule a job to cancel the call in 1 second.\n executor.schedule({\n System.out.printf(\"%.2f Canceling call.%n\", (System.nanoTime() - startNanos) / 1e9f)\n call.cancel()\n System.out.printf(\"%.2f Canceled call.%n\", (System.nanoTime() - startNanos) / 1e9f)\n }, 1, TimeUnit.SECONDS)\n\n System.out.printf(\"%.2f Executing call.%n\", (System.nanoTime() - startNanos) / 1e9f)\n try {\n call.execute().use { response ->\n System.out.printf(\n \"%.2f Call was expected to fail, but completed: %s%n\",\n (System.nanoTime() - startNanos) / 1e9f,\n response,\n )\n }\n } catch (e: IOException) {\n System.out.printf(\n \"%.2f Call failed as expected: %s%n\",\n (System.nanoTime() - startNanos) / 1e9f,\n e,\n )\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CancelCall.kt","line":64,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n CancelCall().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CertificatePinning.kt","line":23,"symbol":"CertificatePinning","kind":"class","lang":"kotlin","code":"class CertificatePinning {\n private val client =\n OkHttpClient\n .Builder()\n .certificatePinner(\n CertificatePinner\n .Builder()\n .add(\"publicobject.com\", \"sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=\")\n .build(),\n ).build()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"https://publicobject.com/robots.txt\")\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n for (certificate in response.handshake!!.peerCertificates) {\n println(CertificatePinner.pin(certificate))\n }\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CertificatePinning.kt","line":34,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"https://publicobject.com/robots.txt\")\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n for (certificate in response.handshake!!.peerCertificates) {\n println(CertificatePinner.pin(certificate))\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CertificatePinning.kt","line":51,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n CertificatePinning().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/ConfigureTimeouts.kt","line":22,"symbol":"ConfigureTimeouts","kind":"class","lang":"kotlin","code":"class ConfigureTimeouts {\n private val client: OkHttpClient =\n OkHttpClient\n .Builder()\n .connectTimeout(5, TimeUnit.SECONDS)\n .writeTimeout(5, TimeUnit.SECONDS)\n .readTimeout(5, TimeUnit.SECONDS)\n .callTimeout(10, TimeUnit.SECONDS)\n .build()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://httpbin.org/delay/2\") // This URL is served with a 2 second delay.\n .build()\n\n client.newCall(request).execute().use { response ->\n println(\"Response completed: $response\")\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/ConfigureTimeouts.kt","line":32,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://httpbin.org/delay/2\") // This URL is served with a 2 second delay.\n .build()\n\n client.newCall(request).execute().use { response ->\n println(\"Response completed: $response\")\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/ConfigureTimeouts.kt","line":45,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n ConfigureTimeouts().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CustomTrust.kt","line":25,"symbol":"CustomTrust","kind":"class","lang":"kotlin","code":"class CustomTrust {\n // PEM files for root certificates of Comodo and Entrust. These two CAs are sufficient to view\n // https://publicobject.com (Comodo) and https://squareup.com (Entrust). But they aren't\n // sufficient to connect to most HTTPS sites including https://godaddy.com and https://visa.com.\n // Typically developers will need to get a PEM file from their organization's TLS administrator.\n val comodoRsaCertificationAuthority =\n \"\"\"\n -----BEGIN CERTIFICATE-----\n MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB\n hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\n A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV\n BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5\n MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT\n EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR\n Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh\n dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR\n 6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X\n pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC\n 9BR++b7Epi9Pf5l/tfxn"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CustomTrust.kt","line":153,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n showUrl(\"https://squareup.com/robots.txt\")\n showUrl(\"https://publicobject.com/helloworld.txt\")\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CustomTrust.kt","line":158,"symbol":"showUrl","kind":"function","lang":"kotlin","code":"private fun showUrl(url: String) {\n val request = Builder().url(url).build()\n client\n .newCall(request)\n .execute()\n .use { response ->\n if (!response.isSuccessful) {\n val responseHeaders = response.headers\n for (i in 0 until responseHeaders.size) {\n println(responseHeaders.name(i) + \": \" + responseHeaders.value(i))\n }\n throw IOException(\"Unexpected code $response\")\n }\n println(response.body.string())\n\n for (peerCertificate in response.handshake?.peerCertificates.orEmpty()) {\n println((peerCertificate as X509Certificate).subjectDN)\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/CustomTrust.kt","line":180,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n CustomTrust().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/DevServer.kt","line":27,"symbol":"DevServer","kind":"class","lang":"kotlin","code":"class DevServer {\n val handshakeCertificates = TlsUtil.localhost()\n\n val server =\n MockWebServer().apply {\n useHttps(handshakeCertificates.sslSocketFactory(), false)\n\n enqueue(\n MockResponse()\n .setResponseCode(HTTP_MOVED_TEMP)\n .setHeader(\"Location\", \"https://www.google.com/robots.txt\"),\n )\n }\n\n val clientCertificates =\n HandshakeCertificates\n .Builder()\n .addPlatformTrustedCertificates()\n .addInsecureHost(server.hostName)\n .build()\n\n val client =\n OkHttpClient\n .Builder()\n .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager)\n .build()\n\n fun run() {\n try {\n val request = Request(server.url(\"/\"))\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.request.url)\n }\n } finally {\n server.shutdown()\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/DevServer.kt","line":54,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n try {\n val request = Request(server.url(\"/\"))\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.request.url)\n }\n } finally {\n server.shutdown()\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/DevServer.kt","line":69,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n DevServer().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/ParseResponseWithMoshi.kt","line":24,"symbol":"ParseResponseWithMoshi","kind":"class","lang":"kotlin","code":"class ParseResponseWithMoshi {\n private val client = OkHttpClient()\n private val moshi = Moshi.Builder().build()\n private val gistJsonAdapter = moshi.adapter(Gist::class.java)\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"https://api.github.com/gists/c2a7c39532239ff261be\")\n .build()\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n val gist = gistJsonAdapter.fromJson(response.body!!.source())\n\n for ((key, value) in gist!!.files!!) {\n println(key)\n println(value.content)\n }\n }\n }\n\n @JsonClass(generateAdapter = true)\n data class Gist(\n var files: Map?,\n )\n\n @JsonClass(generateAdapter = true)\n data class GistFile(\n var content: String?,\n )\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/ParseResponseWithMoshi.kt","line":29,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"https://api.github.com/gists/c2a7c39532239ff261be\")\n .build()\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n val gist = gistJsonAdapter.fromJson(response.body!!.source())\n\n for ((key, value) in gist!!.files!!) {\n println(key)\n println(value.content)\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/ParseResponseWithMoshi.kt","line":58,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n ParseResponseWithMoshi().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PerCallSettings.kt","line":23,"symbol":"PerCallSettings","kind":"class","lang":"kotlin","code":"class PerCallSettings {\n private val client = OkHttpClient()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://httpbin.org/delay/1\") // This URL is served with a 1 second delay.\n .build()\n\n // Copy to customize OkHttp for this request.\n val client1 =\n client\n .newBuilder()\n .readTimeout(500, TimeUnit.MILLISECONDS)\n .build()\n try {\n client1.newCall(request).execute().use { response ->\n println(\"Response 1 succeeded: $response\")\n }\n } catch (e: IOException) {\n println(\"Response 1 failed: $e\")\n }\n\n // Copy to customize OkHttp for this request.\n val client2 =\n client\n .newBuilder()\n .readTimeout(3000, TimeUnit.MILLISECONDS)\n .build()\n try {\n client2.newCall(request).execute().use { response ->\n println(\"Response 2 succeeded: $response\")\n }\n } catch (e: IOException) {\n println(\"Response 2 failed: $e\")\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PerCallSettings.kt","line":26,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"http://httpbin.org/delay/1\") // This URL is served with a 1 second delay.\n .build()\n\n // Copy to customize OkHttp for this request.\n val client1 =\n client\n .newBuilder()\n .readTimeout(500, TimeUnit.MILLISECONDS)\n .build()\n try {\n client1.newCall(request).execute().use { response ->\n println(\"Response 1 succeeded: $response\")\n }\n } catch (e: IOException) {\n println(\"Response 1 failed: $e\")\n }\n\n // Copy to customize OkHttp for this request.\n val client2 =\n client\n .newBuilder()\n .readTimeout(3000, TimeUnit.MILLISECONDS)\n .build()\n try {\n client2.newCall(request).execute().use { response ->\n println(\"Response 2 succeeded: $response\")\n }\n } catch (e: IOException) {\n println(\"Response 2 failed: $e\")\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PerCallSettings.kt","line":63,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n PerCallSettings().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostFile.kt","line":26,"symbol":"PostFile","kind":"class","lang":"kotlin","code":"class PostFile {\n private val client = OkHttpClient()\n\n fun run() {\n val file = File(\"README.md\")\n\n val request =\n Request(\n url = \"https://api.github.com/markdown/raw\".toHttpUrl(),\n body = file.asRequestBody(MEDIA_TYPE_MARKDOWN),\n )\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }\n\n companion object {\n val MEDIA_TYPE_MARKDOWN = \"text/x-markdown; charset=utf-8\".toMediaType()\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostFile.kt","line":29,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val file = File(\"README.md\")\n\n val request =\n Request(\n url = \"https://api.github.com/markdown/raw\".toHttpUrl(),\n body = file.asRequestBody(MEDIA_TYPE_MARKDOWN),\n )\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostFile.kt","line":50,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n PostFile().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostForm.kt","line":24,"symbol":"PostForm","kind":"class","lang":"kotlin","code":"class PostForm {\n private val client = OkHttpClient()\n\n fun run() {\n val formBody =\n FormBody\n .Builder()\n .add(\"search\", \"Jurassic Park\")\n .build()\n val request =\n Request(\n url = \"https://en.wikipedia.org/w/index.php\".toHttpUrl(),\n body = formBody,\n )\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostForm.kt","line":27,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val formBody =\n FormBody\n .Builder()\n .add(\"search\", \"Jurassic Park\")\n .build()\n val request =\n Request(\n url = \"https://en.wikipedia.org/w/index.php\".toHttpUrl(),\n body = formBody,\n )\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostForm.kt","line":47,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n PostForm().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostMultipart.kt","line":26,"symbol":"PostMultipart","kind":"class","lang":"kotlin","code":"class PostMultipart {\n private val client = OkHttpClient()\n\n fun run() {\n // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image\n val requestBody =\n MultipartBody\n .Builder()\n .setType(MultipartBody.FORM)\n .addFormDataPart(\"title\", \"Square Logo\")\n .addFormDataPart(\n \"image\",\n \"logo-square.png\",\n File(\"docs/images/logo-square.png\").asRequestBody(MEDIA_TYPE_PNG),\n ).build()\n\n val request =\n Request\n .Builder()\n .header(\"Authorization\", \"Client-ID $IMGUR_CLIENT_ID\")\n .url(\"https://api.imgur.com/3/image\")\n .post(requestBody)\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }\n\n companion object {\n /**\n * The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running\n * these examples, please request your own client ID! https://api.imgur.com/oauth2\n */\n private const val IMGUR_CLIENT_ID = \"9199fdef135c122\"\n private val MEDIA_TYPE_PNG = \"image/"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostMultipart.kt","line":29,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image\n val requestBody =\n MultipartBody\n .Builder()\n .setType(MultipartBody.FORM)\n .addFormDataPart(\"title\", \"Square Logo\")\n .addFormDataPart(\n \"image\",\n \"logo-square.png\",\n File(\"docs/images/logo-square.png\").asRequestBody(MEDIA_TYPE_PNG),\n ).build()\n\n val request =\n Request\n .Builder()\n .header(\"Authorization\", \"Client-ID $IMGUR_CLIENT_ID\")\n .url(\"https://api.imgur.com/3/image\")\n .post(requestBody)\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostMultipart.kt","line":67,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n PostMultipart().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostPath.kt","line":27,"symbol":"PostPath","kind":"class","lang":"kotlin","code":"class PostPath {\n private val client = OkHttpClient()\n private val fileSystem = FakeFileSystem()\n val path = \"test.json\".toPath()\n\n fun run() {\n fileSystem.write(path) {\n writeUtf8(\"{}\")\n }\n\n val request =\n Request\n .Builder()\n .url(\"https://httpbin.org/anything\")\n .put(path.asRequestBody(fileSystem, MEDIA_TYPE_JSON))\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n fileSystem.sink(path).use {\n response.body.source().readAll(it)\n }\n\n println(fileSystem.source(path).buffer().readUtf8())\n }\n }\n\n companion object {\n val MEDIA_TYPE_JSON = \"application/json\".toMediaType()\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostPath.kt","line":32,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n fileSystem.write(path) {\n writeUtf8(\"{}\")\n }\n\n val request =\n Request\n .Builder()\n .url(\"https://httpbin.org/anything\")\n .put(path.asRequestBody(fileSystem, MEDIA_TYPE_JSON))\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n fileSystem.sink(path).use {\n response.body.source().readAll(it)\n }\n\n println(fileSystem.source(path).buffer().readUtf8())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostPath.kt","line":60,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n PostPath().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostStreaming.kt","line":26,"symbol":"PostStreaming","kind":"class","lang":"kotlin","code":"class PostStreaming {\n private val client = OkHttpClient()\n\n fun run() {\n val requestBody =\n object : RequestBody() {\n override fun contentType() = MEDIA_TYPE_MARKDOWN\n\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"Numbers\\n\")\n sink.writeUtf8(\"-------\\n\")\n for (i in 2..997) {\n sink.writeUtf8(String.format(\" * $i = ${factor(i)}\\n\"))\n }\n }\n\n private fun factor(n: Int): String {\n for (i in 2 until n) {\n val x = n / i\n if (x * i == n) return \"${factor(x)} × $i\"\n }\n return n.toString()\n }\n }\n\n val request =\n Request(\n url = \"https://api.github.com/markdown/raw\".toHttpUrl(),\n body = requestBody,\n )\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }\n\n companion object {\n val MEDIA_TYPE_MARKDOWN = \"text/x-markdown; charset=utf-8\".toMediaType()\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostStreaming.kt","line":29,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val requestBody =\n object : RequestBody() {\n override fun contentType() = MEDIA_TYPE_MARKDOWN\n\n override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"Numbers\\n\")\n sink.writeUtf8(\"-------\\n\")\n for (i in 2..997) {\n sink.writeUtf8(String.format(\" * $i = ${factor(i)}\\n\"))\n }\n }\n\n private fun factor(n: Int): String {\n for (i in 2 until n) {\n val x = n / i\n if (x * i == n) return \"${factor(x)} × $i\"\n }\n return n.toString()\n }\n }\n\n val request =\n Request(\n url = \"https://api.github.com/markdown/raw\".toHttpUrl(),\n body = requestBody,\n )\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostStreaming.kt","line":32,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = MEDIA_TYPE_MARKDOWN"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostStreaming.kt","line":34,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"override fun writeTo(sink: BufferedSink) {\n sink.writeUtf8(\"Numbers\\n\")\n sink.writeUtf8(\"-------\\n\")\n for (i in 2..997) {\n sink.writeUtf8(String.format(\" * $i = ${factor(i)}\\n\"))\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostStreaming.kt","line":42,"symbol":"factor","kind":"function","lang":"kotlin","code":"private fun factor(n: Int): String {\n for (i in 2 until n) {\n val x = n / i\n if (x * i == n) return \"${factor(x)} × $i\"\n }\n return n.toString()\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostStreaming.kt","line":69,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n PostStreaming().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostString.kt","line":25,"symbol":"PostString","kind":"class","lang":"kotlin","code":"class PostString {\n private val client = OkHttpClient()\n\n fun run() {\n val postBody =\n \"\"\"\n |Releases\n |--------\n |\n | * _1.0_ May 6, 2013\n | * _1.1_ June 15, 2013\n | * _1.2_ August 11, 2013\n |\n \"\"\".trimMargin()\n\n val request =\n Request(\n url = \"https://api.github.com/markdown/raw\".toHttpUrl(),\n body = postBody.toRequestBody(MEDIA_TYPE_MARKDOWN),\n )\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }\n\n companion object {\n val MEDIA_TYPE_MARKDOWN = \"text/x-markdown; charset=utf-8\".toMediaType()\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostString.kt","line":28,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val postBody =\n \"\"\"\n |Releases\n |--------\n |\n | * _1.0_ May 6, 2013\n | * _1.1_ June 15, 2013\n | * _1.2_ August 11, 2013\n |\n \"\"\".trimMargin()\n\n val request =\n Request(\n url = \"https://api.github.com/markdown/raw\".toHttpUrl(),\n body = postBody.toRequestBody(MEDIA_TYPE_MARKDOWN),\n )\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n println(response.body.string())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/PostString.kt","line":58,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n PostString().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/SynchronousGet.kt","line":22,"symbol":"SynchronousGet","kind":"class","lang":"kotlin","code":"class SynchronousGet {\n private val client = OkHttpClient()\n\n fun run() {\n val request =\n Request\n .Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n for ((name, value) in response.headers) {\n println(\"$name: $value\")\n }\n\n println(response.body.string())\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/SynchronousGet.kt","line":25,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n val request =\n Request\n .Builder()\n .url(\"https://publicobject.com/helloworld.txt\")\n .build()\n\n client.newCall(request).execute().use { response ->\n if (!response.isSuccessful) throw IOException(\"Unexpected code $response\")\n\n for ((name, value) in response.headers) {\n println(\"$name: $value\")\n }\n\n println(response.body.string())\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/SynchronousGet.kt","line":44,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n SynchronousGet().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":30,"symbol":"UploadProgress","kind":"class","lang":"kotlin","code":"class UploadProgress {\n companion object {\n private const val IMGUR_CLIENT_ID = \"9199fdef135c122\"\n private val MEDIA_TYPE_PNG = \"image/png\".toMediaType()\n }\n\n private val client = OkHttpClient()\n\n @Throws(Exception::class)\n fun run() {\n val progressListener =\n object : ProgressListener {\n private var firstUpdate = true\n\n override fun update(\n bytesWritten: Long,\n contentLength: Long,\n done: Boolean,\n ) {\n if (done) {\n println(\"completed\")\n } else {\n if (firstUpdate) {\n firstUpdate = false\n if (contentLength == -1L) {\n println(\"content-length: unknown\")\n } else {\n println(\"content-length: $contentLength\")\n }\n }\n println(bytesWritten)\n if (contentLength != -1L) {\n println(\"${100 * bytesWritten / contentLength}% done\")\n }\n }\n }\n }\n\n val file = File(\"docs/images/logo-square.png\")\n val requestBody: RequestBody = file.asRequestBody(MEDIA_TYPE_PNG)\n\n val request =\n Request\n .Builder()\n .header(\"Auth"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":38,"symbol":"run","kind":"function","lang":"kotlin","code":"@Throws(Exception::class)\n fun run() {\n val progressListener =\n object : ProgressListener {\n private var firstUpdate = true\n\n override fun update(\n bytesWritten: Long,\n contentLength: Long,\n done: Boolean,\n ) {\n if (done) {\n println(\"completed\")\n } else {\n if (firstUpdate) {\n firstUpdate = false\n if (contentLength == -1L) {\n println(\"content-length: unknown\")\n } else {\n println(\"content-length: $contentLength\")\n }\n }\n println(bytesWritten)\n if (contentLength != -1L) {\n println(\"${100 * bytesWritten / contentLength}% done\")\n }\n }\n }\n }\n\n val file = File(\"docs/images/logo-square.png\")\n val requestBody: RequestBody = file.asRequestBody(MEDIA_TYPE_PNG)\n\n val request =\n Request\n .Builder()\n .header(\"Authorization\", \"Client-ID $IMGUR_CLIENT_ID\")\n .url(\"https://api.imgur.com/3/image\")\n .post(ProgressRequestBody(requestBody, progressListener))\n .build()\n\n client.newCall(request).execute"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":44,"symbol":"update","kind":"function","lang":"kotlin","code":"override fun update(\n bytesWritten: Long,\n contentLength: Long,\n done: Boolean,\n ) {\n if (done) {\n println(\"completed\")\n } else {\n if (firstUpdate) {\n firstUpdate = false\n if (contentLength == -1L) {\n println(\"content-length: unknown\")\n } else {\n println(\"content-length: $contentLength\")\n }\n }\n println(bytesWritten)\n if (contentLength != -1L) {\n println(\"${100 * bytesWritten / contentLength}% done\")\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":85,"symbol":"ProgressRequestBody","kind":"class","lang":"kotlin","code":"private class ProgressRequestBody(\n private val delegate: RequestBody,\n private val progressListener: ProgressListener,\n ) : RequestBody() {\n override fun contentType() = delegate.contentType()\n\n @Throws(IOException::class)\n override fun contentLength(): Long = delegate.contentLength()\n\n @Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n val forwardingSink =\n object : ForwardingSink(sink) {\n private var totalBytesWritten: Long = 0\n private var completed = false\n\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n super.write(source, byteCount)\n totalBytesWritten += byteCount\n progressListener.update(totalBytesWritten, contentLength(), completed)\n }\n\n override fun close() {\n super.close()\n if (!completed) {\n completed = true\n progressListener.update(totalBytesWritten, contentLength(), completed)\n }\n }\n }\n\n val bufferedSink = forwardingSink.buffer()\n delegate.writeTo(bufferedSink)\n bufferedSink.flush()\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":89,"symbol":"contentType","kind":"function","lang":"kotlin","code":"override fun contentType() = delegate.contentType()"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":91,"symbol":"contentLength","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun contentLength(): Long = delegate.contentLength()"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":94,"symbol":"writeTo","kind":"function","lang":"kotlin","code":"@Throws(IOException::class)\n override fun writeTo(sink: BufferedSink) {\n val forwardingSink =\n object : ForwardingSink(sink) {\n private var totalBytesWritten: Long = 0\n private var completed = false\n\n override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n super.write(source, byteCount)\n totalBytesWritten += byteCount\n progressListener.update(totalBytesWritten, contentLength(), completed)\n }\n\n override fun close() {\n super.close()\n if (!completed) {\n completed = true\n progressListener.update(totalBytesWritten, contentLength(), completed)\n }\n }\n }\n\n val bufferedSink = forwardingSink.buffer()\n delegate.writeTo(bufferedSink)\n bufferedSink.flush()\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":101,"symbol":"write","kind":"function","lang":"kotlin","code":"override fun write(\n source: Buffer,\n byteCount: Long,\n ) {\n super.write(source, byteCount)\n totalBytesWritten += byteCount\n progressListener.update(totalBytesWritten, contentLength(), completed)\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":110,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {\n super.close()\n if (!completed) {\n completed = true\n progressListener.update(totalBytesWritten, contentLength(), completed)\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":125,"symbol":"ProgressListener","kind":"interface","lang":"kotlin","code":"fun interface ProgressListener {\n fun update(\n bytesWritten: Long,\n contentLength: Long,\n done: Boolean,\n )\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":126,"symbol":"update","kind":"function","lang":"kotlin","code":"fun update(\n bytesWritten: Long,\n contentLength: Long,\n done: Boolean,\n )"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/UploadProgress.kt","line":134,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n UploadProgress().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":66,"symbol":"WireSharkListenerFactory","kind":"class","lang":"kotlin","doc":"3. Register with `client.eventListenerFactory(eventListenerFactory)` 4. Launch wireshark if not done externally `val process = eventListenerFactory.launchWireShark()`","code":"@SuppressSignatureCheck\nclass WireSharkListenerFactory(\n private val logFile: File,\n private val tlsVersions: List,\n private val launch: Launch? = null,\n) : EventListener.Factory {\n override fun create(call: Call): EventListener = WireSharkKeyLoggerListener(logFile, launch == null)\n\n fun launchWireShark(): Process? {\n when (launch) {\n null -> {\n if (tlsVersions.contains(TLS_1_2)) {\n println(\"TLSv1.2 traffic will be logged automatically and available via wireshark\")\n }\n\n if (tlsVersions.contains(TLS_1_3)) {\n println(\"TLSv1.3 requires an external command run before first traffic is sent\")\n println(\"Follow instructions at https://github.com/neykov/extract-tls-secrets for TLSv1.3\")\n println(\"Pid: ${ProcessHandle.current().pid()}\")\n\n Thread.sleep(10000)\n }\n }\n\n CommandLine -> {\n return ProcessBuilder(\n \"tshark\",\n \"-l\",\n \"-V\",\n \"-o\",\n \"tls.keylog_file:$logFile\",\n \"-Y\",\n \"http2\",\n \"-O\",\n \"http2,tls\",\n ).redirectInput(File(\"/dev/null\"))\n .redirectOutput(Redirect.INHERIT)\n "} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":72,"symbol":"create","kind":"function","lang":"kotlin","code":"override fun create(call: Call): EventListener = WireSharkKeyLoggerListener(logFile, launch == null)"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":74,"symbol":"launchWireShark","kind":"function","lang":"kotlin","code":"fun launchWireShark(): Process? {\n when (launch) {\n null -> {\n if (tlsVersions.contains(TLS_1_2)) {\n println(\"TLSv1.2 traffic will be logged automatically and available via wireshark\")\n }\n\n if (tlsVersions.contains(TLS_1_3)) {\n println(\"TLSv1.3 requires an external command run before first traffic is sent\")\n println(\"Follow instructions at https://github.com/neykov/extract-tls-secrets for TLSv1.3\")\n println(\"Pid: ${ProcessHandle.current().pid()}\")\n\n Thread.sleep(10000)\n }\n }\n\n CommandLine -> {\n return ProcessBuilder(\n \"tshark\",\n \"-l\",\n \"-V\",\n \"-o\",\n \"tls.keylog_file:$logFile\",\n \"-Y\",\n \"http2\",\n \"-O\",\n \"http2,tls\",\n ).redirectInput(File(\"/dev/null\"))\n .redirectOutput(Redirect.INHERIT)\n .redirectError(Redirect.INHERIT)\n .start()\n }\n\n Gui -> {\n return ProcessBuilder(\n \"nohup\",\n \"wireshark\",\n \"-o\",\n \"tls.keylog_file:$logFile\",\n \"-S\",\n \"-l\",\n \"-Y\",\n \"http2\",\n \"-k\",\n ).redire"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":132,"symbol":"WireSharkKeyLoggerListener","kind":"class","lang":"kotlin","code":"class WireSharkKeyLoggerListener(\n private val logFile: File,\n private val verbose: Boolean = false,\n ) : EventListener() {\n var random: String? = null\n lateinit var currentThread: Thread\n\n private val loggerHandler =\n object : Handler() {\n override fun publish(record: LogRecord) {\n // Try to avoid multi threading issues with concurrent requests\n if (Thread.currentThread() != currentThread) {\n return\n }\n\n // https://timothybasanov.com/2016/05/26/java-pre-master-secret.html\n // https://security.stackexchange.com/questions/35639/decrypting-tls-in-wireshark-when-using-dhe-rsa-ciphersuites\n // https://stackoverflow.com/questions/36240279/how-do-i-extract-the-pre-master-secret-using-an-openssl-based-client\n\n // TLSv1.2 Events\n // Produced ClientHello handshake message\n // Consuming ServerHello handshake message\n // Consuming server Certificate handshake message\n // Consuming server CertificateStatus handshake message\n // Found trusted certificate\n // Consuming ECDH ServerKeyExchange handshake message\n // Consuming ServerHell"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":141,"symbol":"publish","kind":"function","lang":"kotlin","code":"override fun publish(record: LogRecord) {\n // Try to avoid multi threading issues with concurrent requests\n if (Thread.currentThread() != currentThread) {\n return\n }\n\n // https://timothybasanov.com/2016/05/26/java-pre-master-secret.html\n // https://security.stackexchange.com/questions/35639/decrypting-tls-in-wireshark-when-using-dhe-rsa-ciphersuites\n // https://stackoverflow.com/questions/36240279/how-do-i-extract-the-pre-master-secret-using-an-openssl-based-client\n\n // TLSv1.2 Events\n // Produced ClientHello handshake message\n // Consuming ServerHello handshake message\n // Consuming server Certificate handshake message\n // Consuming server CertificateStatus handshake message\n // Found trusted certificate\n // Consuming ECDH ServerKeyExchange handshake message\n // Consuming ServerHelloDone handshake message\n // Produced ECDHE ClientKeyExchange handshake message\n // Produced client Finished handshake message\n // Consuming server Finished handshake message\n // Produced ClientHello handshake message\n //\n "} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":186,"symbol":"flush","kind":"function","lang":"kotlin","code":"override fun flush() {}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":188,"symbol":"close","kind":"function","lang":"kotlin","code":"override fun close() {}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":191,"symbol":"readClientRandom","kind":"function","lang":"kotlin","code":"private fun readClientRandom(param: String): String? {\n val matchResult = randomRegex.find(param)\n\n return if (matchResult != null) {\n matchResult.groupValues[1].replace(\" \", \"\")\n } else {\n null\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":201,"symbol":"secureConnectStart","kind":"function","lang":"kotlin","code":"override fun secureConnectStart(call: Call) {\n // Register to capture \"Produced ClientHello handshake message\".\n currentThread = Thread.currentThread()\n logger.addHandler(loggerHandler)\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":207,"symbol":"secureConnectEnd","kind":"function","lang":"kotlin","code":"override fun secureConnectEnd(\n call: Call,\n handshake: Handshake?,\n ) {\n logger.removeHandler(loggerHandler)\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":214,"symbol":"callEnd","kind":"function","lang":"kotlin","code":"override fun callEnd(call: Call) {\n // Cleanup log handler if failed.\n logger.removeHandler(loggerHandler)\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":219,"symbol":"connectionAcquired","kind":"function","lang":"kotlin","code":"override fun connectionAcquired(\n call: Call,\n connection: Connection,\n ) {\n if (random != null) {\n val sslSocket = connection.socket() as SSLSocket\n val session = sslSocket.session\n\n val masterSecretHex =\n session.masterSecret\n ?.encoded\n ?.toByteString()\n ?.hex()\n\n if (masterSecretHex != null) {\n val keyLog = \"CLIENT_RANDOM $random $masterSecretHex\"\n\n if (verbose) {\n println(keyLog)\n }\n logFile.appendText(\"$keyLog\\n\")\n }\n }\n\n random = null\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":246,"symbol":"Launch","kind":"enum","lang":"kotlin","code":"enum class Launch {\n Gui,\n CommandLine,\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":247,"symbol":"Gui","kind":"enum_member","lang":"kotlin","code":"Gui"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":248,"symbol":"CommandLine","kind":"enum_member","lang":"kotlin","code":"CommandLine"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":280,"symbol":"WiresharkExample","kind":"class","lang":"kotlin","code":"class WiresharkExample(\n tlsVersions: List,\n private val launch: Launch? = null,\n) {\n private val connectionSpec =\n ConnectionSpec\n .Builder(ConnectionSpec.RESTRICTED_TLS)\n .tlsVersions(*tlsVersions.toTypedArray())\n .build()\n\n private val eventListenerFactory =\n WireSharkListenerFactory(\n logFile = File(\"/tmp/key.log\"),\n tlsVersions = tlsVersions,\n launch = launch,\n )\n\n val client =\n OkHttpClient\n .Builder()\n .connectionSpecs(listOf(connectionSpec))\n .eventListenerFactory(eventListenerFactory)\n .build()\n\n fun run() {\n // Launch wireshark in the background\n val process = eventListenerFactory.launchWireShark()\n\n val fbRequest =\n Request\n .Builder()\n .url(\"https://graph.facebook.com/robots.txt?s=fb\")\n .build()\n val twitterRequest =\n Request\n .Builder()\n .url(\"https://api.twitter.com/robots.txt?s=tw\")\n .build()\n val googleRequest =\n Request\n .Builder()\n .url(\"https://www.google.com/robots.txt?s=g\")\n .build()\n\n try {\n for (i in 1..2) {\n // Space out traffic to make it easier to demarcate.\n sendT"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":304,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n // Launch wireshark in the background\n val process = eventListenerFactory.launchWireShark()\n\n val fbRequest =\n Request\n .Builder()\n .url(\"https://graph.facebook.com/robots.txt?s=fb\")\n .build()\n val twitterRequest =\n Request\n .Builder()\n .url(\"https://api.twitter.com/robots.txt?s=tw\")\n .build()\n val googleRequest =\n Request\n .Builder()\n .url(\"https://www.google.com/robots.txt?s=g\")\n .build()\n\n try {\n for (i in 1..2) {\n // Space out traffic to make it easier to demarcate.\n sendTestRequest(fbRequest)\n Thread.sleep(1000)\n sendTestRequest(twitterRequest)\n Thread.sleep(1000)\n sendTestRequest(googleRequest)\n Thread.sleep(2000)\n }\n } finally {\n client.connectionPool.evictAll()\n client.dispatcher.executorService.shutdownNow()\n\n if (launch == CommandLine) {\n process?.destroyForcibly()\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":344,"symbol":"sendTestRequest","kind":"function","lang":"kotlin","code":"private fun sendTestRequest(request: Request) {\n try {\n if (this.launch != CommandLine) {\n println(request.url)\n }\n\n client\n .newCall(request)\n .execute()\n .use {\n val firstLine =\n it.body\n .string()\n .lines()\n .first()\n if (this.launch != CommandLine) {\n println(\"${it.code} ${it.request.url.host} $firstLine\")\n }\n Unit\n }\n } catch (e: IOException) {\n System.err.println(e)\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/WiresharkExample.kt","line":370,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n // Call this before anything else initialises the JSSE stack.\n WireSharkListenerFactory.register()\n\n val example = WiresharkExample(tlsVersions = listOf(TLS_1_2), launch = CommandLine)\n example.run()\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/YubikeyClientAuth.kt","line":50,"symbol":"YubikeyClientAuth","kind":"class","lang":"kotlin","doc":"Using PKCS11 support in the JDK. https://tersesystems.com/blog/2018/09/08/keymanagers-and-keystores/ Install OpenSC separately. On a mac `brew cast install opensc`.","code":"@SuppressSignatureCheck\nclass YubikeyClientAuth {\n fun run() {\n // The typical PKCS11 slot, may vary with different hardware.\n val slot = 0\n\n val config = \"--name=OpenSC\\nlibrary=/Library/OpenSC/lib/opensc-pkcs11.so\\nslot=$slot\\n\"\n\n // May fail with ProviderException with root cause like\n // sun.security.pkcs11.wrapper.PKCS11Exception: CKR_SLOT_ID_INVALID\n val pkcs11 = Security.getProvider(\"SunPKCS11\").configure(config)\n Security.addProvider(pkcs11)\n\n val callbackHandler = ConsoleCallbackHandler\n\n val builderList: List =\n listOf(\n KeyStore.Builder.newInstance(\"PKCS11\", null, KeyStore.CallbackHandlerProtection(callbackHandler)),\n // Example if you want to combine multiple keystore types\n // KeyStore.Builder.newInstance(\"PKCS12\", null, File(\"keystore.p12\"), PasswordProtection(\"rosebud\".toCharArray()))\n )\n\n val keyManagerFactory = KeyManagerFactory.getInstance(\"NewSunX509\")\n keyManagerFactory.init(KeyStoreBuilderParameters(builderList))\n val keyManager = keyManagerFactory.keyManagers[0] as X509ExtendedKeyManager\n\n val trustManager = Platform.get().platformTrustManager()\n\n val sslContext = SSLCo"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/YubikeyClientAuth.kt","line":52,"symbol":"run","kind":"function","lang":"kotlin","code":"fun run() {\n // The typical PKCS11 slot, may vary with different hardware.\n val slot = 0\n\n val config = \"--name=OpenSC\\nlibrary=/Library/OpenSC/lib/opensc-pkcs11.so\\nslot=$slot\\n\"\n\n // May fail with ProviderException with root cause like\n // sun.security.pkcs11.wrapper.PKCS11Exception: CKR_SLOT_ID_INVALID\n val pkcs11 = Security.getProvider(\"SunPKCS11\").configure(config)\n Security.addProvider(pkcs11)\n\n val callbackHandler = ConsoleCallbackHandler\n\n val builderList: List =\n listOf(\n KeyStore.Builder.newInstance(\"PKCS11\", null, KeyStore.CallbackHandlerProtection(callbackHandler)),\n // Example if you want to combine multiple keystore types\n // KeyStore.Builder.newInstance(\"PKCS12\", null, File(\"keystore.p12\"), PasswordProtection(\"rosebud\".toCharArray()))\n )\n\n val keyManagerFactory = KeyManagerFactory.getInstance(\"NewSunX509\")\n keyManagerFactory.init(KeyStoreBuilderParameters(builderList))\n val keyManager = keyManagerFactory.keyManagers[0] as X509ExtendedKeyManager\n\n val trustManager = Platform.get().platformTrustManager()\n\n val sslContext = SSLContext.getInstance(\"TLS\")\n sslContext.init(arrayOf"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/YubikeyClientAuth.kt","line":102,"symbol":"ConsoleCallbackHandler","kind":"object","lang":"kotlin","code":"object ConsoleCallbackHandler : CallbackHandler {\n override fun handle(callbacks: Array) {\n for (callback in callbacks) {\n if (callback is PasswordCallback) {\n val console = System.console()\n\n if (console != null) {\n callback.password = console.readPassword(callback.prompt)\n } else {\n System.err.println(callback.prompt)\n callback.password =\n System.`in`\n .bufferedReader()\n .readLine()\n .toCharArray()\n }\n } else {\n throw UnsupportedCallbackException(callback)\n }\n }\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/YubikeyClientAuth.kt","line":103,"symbol":"handle","kind":"function","lang":"kotlin","code":"override fun handle(callbacks: Array) {\n for (callback in callbacks) {\n if (callback is PasswordCallback) {\n val console = System.console()\n\n if (console != null) {\n callback.password = console.readPassword(callback.prompt)\n } else {\n System.err.println(callback.prompt)\n callback.password =\n System.`in`\n .bufferedReader()\n .readLine()\n .toCharArray()\n }\n } else {\n throw UnsupportedCallbackException(callback)\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/main/java/okhttp3/recipes/kt/YubikeyClientAuth.kt","line":125,"symbol":"main","kind":"function","lang":"kotlin","code":"fun main() {\n YubikeyClientAuth().run()\n}"} {"repo":"okhttp","file":"samples/guide/src/test/kotlin/okhttp3/AllMainsTest.kt","line":27,"symbol":"mainFiles","kind":"function","lang":"kotlin","code":"private fun mainFiles(): List {\n val directories =\n listOf(\n \"$prefix/samples/guide/src/main/java/okhttp3/guide\",\n \"$prefix/samples/guide/src/main/java/okhttp3/recipes\",\n \"$prefix/samples/guide/src/main/java/okhttp3/recipes/kt\",\n ).map { File(it) }\n\n return directories.flatMap {\n it\n .listFiles()\n .orEmpty()\n .filter { f -> f.isFile }\n .toList()\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/test/kotlin/okhttp3/AllMainsTest.kt","line":44,"symbol":"MainTestProvider","kind":"class","lang":"kotlin","code":"internal class MainTestProvider : SimpleProvider() {\n override fun arguments(): List {\n val mainFiles = mainFiles()\n return mainFiles\n .map {\n val suffix = it.path.replace(\"${prefix}samples/guide/src/main/java/\", \"\")\n suffix\n .replace(\"(.*)\\\\.java\".toRegex()) { mr ->\n mr.groupValues[1].replace('/', '.')\n }.replace(\"(.*)\\\\.kt\".toRegex()) { mr ->\n mr.groupValues[1].replace('/', '.') + \"Kt\"\n }\n }.sorted()\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/test/kotlin/okhttp3/AllMainsTest.kt","line":45,"symbol":"arguments","kind":"function","lang":"kotlin","code":"override fun arguments(): List {\n val mainFiles = mainFiles()\n return mainFiles\n .map {\n val suffix = it.path.replace(\"${prefix}samples/guide/src/main/java/\", \"\")\n suffix\n .replace(\"(.*)\\\\.java\".toRegex()) { mr ->\n mr.groupValues[1].replace('/', '.')\n }.replace(\"(.*)\\\\.kt\".toRegex()) { mr ->\n mr.groupValues[1].replace('/', '.') + \"Kt\"\n }\n }.sorted()\n }"} {"repo":"okhttp","file":"samples/guide/src/test/kotlin/okhttp3/AllMainsTest.kt","line":60,"symbol":"AllMainsTest","kind":"class","lang":"kotlin","code":"@Disabled(\"Don't run by default\")\n@Tag(\"Slow\")\nclass AllMainsTest {\n @ParameterizedTest\n @ArgumentsSource(MainTestProvider::class)\n fun runMain(className: String) {\n val mainMethod =\n Class\n .forName(className)\n .methods\n .find { it.name == \"main\" }\n try {\n if (mainMethod != null) {\n if (mainMethod.parameters.isEmpty()) {\n mainMethod.invoke(null)\n } else {\n mainMethod.invoke(null, arrayOf())\n }\n } else {\n System.err.println(\"No main for $className\")\n }\n } catch (ite: InvocationTargetException) {\n if (!expectedFailure(className, ite.cause!!)) {\n throw ite.cause!!\n }\n }\n }\n\n @Suppress(\"UNUSED_PARAMETER\")\n private fun expectedFailure(\n className: String,\n cause: Throwable,\n ): Boolean =\n when (className) {\n \"okhttp3.recipes.CheckHandshake\" -> true\n\n // by design\n \"okhttp3.recipes.RequestBodyCompression\" -> true\n\n // expired token\n else -> false\n }\n}"} {"repo":"okhttp","file":"samples/guide/src/test/kotlin/okhttp3/AllMainsTest.kt","line":63,"symbol":"runMain","kind":"function","lang":"kotlin","code":"@ParameterizedTest\n @ArgumentsSource(MainTestProvider::class)\n fun runMain(className: String) {\n val mainMethod =\n Class\n .forName(className)\n .methods\n .find { it.name == \"main\" }\n try {\n if (mainMethod != null) {\n if (mainMethod.parameters.isEmpty()) {\n mainMethod.invoke(null)\n } else {\n mainMethod.invoke(null, arrayOf())\n }\n } else {\n System.err.println(\"No main for $className\")\n }\n } catch (ite: InvocationTargetException) {\n if (!expectedFailure(className, ite.cause!!)) {\n throw ite.cause!!\n }\n }\n }"} {"repo":"okhttp","file":"samples/guide/src/test/kotlin/okhttp3/AllMainsTest.kt","line":88,"symbol":"expectedFailure","kind":"function","lang":"kotlin","code":"@Suppress(\"UNUSED_PARAMETER\")\n private fun expectedFailure(\n className: String,\n cause: Throwable,\n ): Boolean =\n when (className) {\n \"okhttp3.recipes.CheckHandshake\" -> true\n\n // by design\n \"okhttp3.recipes.RequestBodyCompression\" -> true\n\n // expired token\n else -> false\n }"} {"repo":"okhttp","file":"samples/simple-client/src/main/java/okhttp3/sample/OkHttpContributors.java","line":28,"symbol":"OkHttpContributors","kind":"class","lang":"java","code":"public class OkHttpContributors {\n private static final String ENDPOINT = \"https://api.github.com/repos/lysine-dev/okhttp/contributors\";\n private static final Moshi MOSHI = new Moshi.Builder().build();\n private static final JsonAdapter> CONTRIBUTORS_JSON_ADAPTER = MOSHI.adapter(\n Types.newParameterizedType(List.class, Contributor.class));\n\n static class Contributor {\n String login;\n int contributions;\n }\n\n public static void main(String... args) throws Exception {\n OkHttpClient client = new OkHttpClient();\n\n // Create request for remote resource.\n Request request = new Request.Builder()\n .url(ENDPOINT)\n .build();\n\n // Execute the request and retrieve the response.\n try (Response response = client.newCall(request).execute()) {\n // Deserialize HTTP response to concrete type.\n ResponseBody body = response.body();\n List contributors = CONTRIBUTORS_JSON_ADAPTER.fromJson(body.source());\n\n // Sort list by the most contributions.\n Collections.sort(contributors, (c1, c2) -> c2.contributions - c1.contributions);\n\n // Output list of contributors.\n for (Contributor contributor : cont"} {"repo":"okhttp","file":"samples/simple-client/src/main/java/okhttp3/sample/OkHttpContributors.java","line":34,"symbol":"Contributor","kind":"class","lang":"java","code":"static class Contributor {\n String login;\n int contributions;\n }"} {"repo":"okhttp","file":"samples/simple-client/src/main/java/okhttp3/sample/OkHttpContributors.java","line":39,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n OkHttpClient client = new OkHttpClient();\n\n // Create request for remote resource.\n Request request = new Request.Builder()\n .url(ENDPOINT)\n .build();\n\n // Execute the request and retrieve the response.\n try (Response response = client.newCall(request).execute()) {\n // Deserialize HTTP response to concrete type.\n ResponseBody body = response.body();\n List contributors = CONTRIBUTORS_JSON_ADAPTER.fromJson(body.source());\n\n // Sort list by the most contributions.\n Collections.sort(contributors, (c1, c2) -> c2.contributions - c1.contributions);\n\n // Output list of contributors.\n for (Contributor contributor : contributors) {\n System.out.println(contributor.login + \": \" + contributor.contributions);\n }\n }\n }"} {"repo":"okhttp","file":"samples/simple-client/src/main/java/okhttp3/sample/OkHttpContributors.java","line":63,"symbol":"OkHttpContributors","kind":"constructor","lang":"java","code":"private OkHttpContributors() {\n // No instances.\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSession.java","line":19,"symbol":"OAuthSession","kind":"class","lang":"java","doc":"Authorization for an application to make Slack API calls on behalf of a user.","code":"@SuppressWarnings(\"checkstyle:membername\")\npublic final class OAuthSession {\n public final boolean ok;\n public final String access_token;\n public final String scope;\n public final String user_id;\n public final String team_name;\n public final String team_id;\n\n public OAuthSession(\n boolean ok, String accessToken, String scope, String userId, String teamName, String teamId) {\n this.ok = ok;\n this.access_token = accessToken;\n this.scope = scope;\n this.user_id = userId;\n this.team_name = teamName;\n this.team_id = teamId;\n }\n\n @Override public String toString() {\n return String.format(\"(ok=%s, access_token=%s, scope=%s, user_id=%s, team_name=%s, team_id=%s)\",\n ok, access_token, scope, user_id, team_name, team_id);\n }\n}"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSession.java","line":28,"symbol":"OAuthSession","kind":"constructor","lang":"java","code":"public OAuthSession(\n boolean ok, String accessToken, String scope, String userId, String teamName, String teamId) {\n this.ok = ok;\n this.access_token = accessToken;\n this.scope = scope;\n this.user_id = userId;\n this.team_name = teamName;\n this.team_id = teamId;\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSession.java","line":38,"symbol":"toString","kind":"method","lang":"java","code":"@Override public String toString() {\n return String.format(\"(ok=%s, access_token=%s, scope=%s, user_id=%s, team_name=%s, team_id=%s)\",\n ok, access_token, scope, user_id, team_name, team_id);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":36,"symbol":"OAuthSessionFactory","kind":"class","lang":"java","doc":"Runs a MockWebServer on localhost and uses it as the backend to receive an OAuth session.

Clients should call {@link #start}, {@link #newAuthorizeUrl} and {@link #close} in that order. Clients may request multiple sessions.","code":"public final class OAuthSessionFactory extends Dispatcher implements Closeable {\n private final SecureRandom secureRandom = new SecureRandom();\n\n private final SlackApi slackApi;\n private MockWebServer mockWebServer;\n\n /** Guarded by this. */\n private final Map listeners = new LinkedHashMap<>();\n\n public OAuthSessionFactory(SlackApi slackApi) {\n this.slackApi = slackApi;\n }\n\n public void start() throws Exception {\n if (mockWebServer != null) throw new IllegalStateException();\n\n mockWebServer = new MockWebServer();\n mockWebServer.setDispatcher(this);\n mockWebServer.start(slackApi.port);\n }\n\n public HttpUrl newAuthorizeUrl(String scopes, String team, Listener listener) {\n if (mockWebServer == null) throw new IllegalStateException();\n\n ByteString state = randomToken();\n synchronized (this) {\n listeners.put(state, listener);\n }\n\n return slackApi.authorizeUrl(scopes, redirectUrl(), state, team);\n }\n\n private ByteString randomToken() {\n byte[] bytes = new byte[16];\n secureRandom.nextBytes(bytes);\n return ByteString.of(bytes);\n }\n\n private HttpUrl redirectUrl() {\n return mockWebServer.url(\"/oauth/\");\n }\n\n "} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":45,"symbol":"OAuthSessionFactory","kind":"constructor","lang":"java","code":"public OAuthSessionFactory(SlackApi slackApi) {\n this.slackApi = slackApi;\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":49,"symbol":"start","kind":"method","lang":"java","code":"public void start() throws Exception {\n if (mockWebServer != null) throw new IllegalStateException();\n\n mockWebServer = new MockWebServer();\n mockWebServer.setDispatcher(this);\n mockWebServer.start(slackApi.port);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":57,"symbol":"newAuthorizeUrl","kind":"method","lang":"java","code":"public HttpUrl newAuthorizeUrl(String scopes, String team, Listener listener) {\n if (mockWebServer == null) throw new IllegalStateException();\n\n ByteString state = randomToken();\n synchronized (this) {\n listeners.put(state, listener);\n }\n\n return slackApi.authorizeUrl(scopes, redirectUrl(), state, team);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":68,"symbol":"randomToken","kind":"method","lang":"java","code":"private ByteString randomToken() {\n byte[] bytes = new byte[16];\n secureRandom.nextBytes(bytes);\n return ByteString.of(bytes);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":74,"symbol":"redirectUrl","kind":"method","lang":"java","code":"private HttpUrl redirectUrl() {\n return mockWebServer.url(\"/oauth/\");\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":79,"symbol":"dispatch","kind":"method","lang":"java","doc":"When the browser hits the redirect URL, use the provided code to ask Slack for a session.","code":"@Override public MockResponse dispatch(RecordedRequest request) {\n HttpUrl requestUrl = mockWebServer.url(request.getPath());\n String code = requestUrl.queryParameter(\"code\");\n String stateString = requestUrl.queryParameter(\"state\");\n ByteString state = stateString != null ? ByteString.decodeBase64(stateString) : null;\n\n Listener listener;\n synchronized (this) {\n listener = listeners.get(state);\n }\n\n if (code == null || listener == null) {\n return new MockResponse()\n .setResponseCode(404)\n .setBody(\"unexpected request\");\n }\n\n try {\n OAuthSession session = slackApi.exchangeCode(code, redirectUrl());\n listener.sessionGranted(session);\n } catch (IOException e) {\n return new MockResponse()\n .setResponseCode(400)\n .setBody(\"code exchange failed: \" + e.getMessage());\n }\n\n synchronized (this) {\n listeners.remove(state);\n }\n\n // Success!\n return new MockResponse()\n .setResponseCode(302)\n .addHeader(\"Location\", \"https://twitter.com/CuteEmergency/status/789457462864863232\");\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":115,"symbol":"Listener","kind":"interface","lang":"java","code":"public interface Listener {\n void sessionGranted(OAuthSession session);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":116,"symbol":"sessionGranted","kind":"method","lang":"java","code":"void sessionGranted(OAuthSession session);"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/OAuthSessionFactory.java","line":119,"symbol":"close","kind":"method","lang":"java","code":"@Override public void close() {\n if (mockWebServer == null) throw new IllegalStateException();\n try {\n mockWebServer.close();\n } catch (IOException ignored) {\n }\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmSession.java","line":25,"symbol":"RtmSession","kind":"class","lang":"java","doc":"A realtime messaging session.","code":"public final class RtmSession extends WebSocketListener implements Closeable {\n private final SlackApi slackApi;\n\n /** Guarded by this. */\n private WebSocket webSocket;\n\n public RtmSession(SlackApi slackApi) {\n this.slackApi = slackApi;\n }\n\n public void open(String accessToken) throws IOException {\n if (webSocket != null) throw new IllegalStateException();\n\n RtmStartResponse rtmStartResponse = slackApi.rtmStart(accessToken);\n webSocket = slackApi.rtm(rtmStartResponse.url, this);\n }\n\n // TODO(jwilson): can I read the response body? Do I have to?\n // the body from slack is a 0-byte-buffer\n @Override public synchronized void onOpen(WebSocket webSocket, Response response) {\n System.out.println(\"onOpen: \" + response);\n }\n\n // TOOD(jwilson): decode incoming messages and dispatch them somewhere.\n @Override public void onMessage(WebSocket webSocket, String text) {\n System.out.println(\"onMessage: \" + text);\n }\n\n @Override public void onClosing(WebSocket webSocket, int code, String reason) {\n webSocket.close(1000, null);\n System.out.println(\"onClose (\" + code + \"): \" + reason);\n }\n\n @Override public void onFailure(WebSocket webSocket, T"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmSession.java","line":31,"symbol":"RtmSession","kind":"constructor","lang":"java","code":"public RtmSession(SlackApi slackApi) {\n this.slackApi = slackApi;\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmSession.java","line":35,"symbol":"open","kind":"method","lang":"java","code":"public void open(String accessToken) throws IOException {\n if (webSocket != null) throw new IllegalStateException();\n\n RtmStartResponse rtmStartResponse = slackApi.rtmStart(accessToken);\n webSocket = slackApi.rtm(rtmStartResponse.url, this);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmSession.java","line":44,"symbol":"onOpen","kind":"method","lang":"java","doc":"TODO(jwilson): can I read the response body? Do I have to? the body from slack is a 0-byte-buffer","code":"@Override public synchronized void onOpen(WebSocket webSocket, Response response) {\n System.out.println(\"onOpen: \" + response);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmSession.java","line":49,"symbol":"onMessage","kind":"method","lang":"java","doc":"TOOD(jwilson): decode incoming messages and dispatch them somewhere.","code":"@Override public void onMessage(WebSocket webSocket, String text) {\n System.out.println(\"onMessage: \" + text);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmSession.java","line":53,"symbol":"onClosing","kind":"method","lang":"java","code":"@Override public void onClosing(WebSocket webSocket, int code, String reason) {\n webSocket.close(1000, null);\n System.out.println(\"onClose (\" + code + \"): \" + reason);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmSession.java","line":58,"symbol":"onFailure","kind":"method","lang":"java","code":"@Override public void onFailure(WebSocket webSocket, Throwable t, Response response) {\n // TODO(jwilson): can I read the response body? Do I have to?\n System.out.println(\"onFailure \" + response);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmSession.java","line":63,"symbol":"close","kind":"method","lang":"java","code":"@Override public void close() throws IOException {\n if (webSocket == null) return;\n\n WebSocket webSocket;\n synchronized (this) {\n webSocket = this.webSocket;\n }\n\n if (webSocket != null) {\n webSocket.close(1000, \"bye\");\n }\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/RtmStartResponse.java","line":22,"symbol":"RtmStartResponse","kind":"class","lang":"java","doc":"See https://api.slack.com/methods/rtm.start.","code":"public final class RtmStartResponse {\n HttpUrl url;\n Object self;\n Object team;\n List users;\n List channels;\n List groups;\n List mpims;\n List ims;\n List bots;\n}"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":40,"symbol":"SlackApi","kind":"class","lang":"java","doc":"instance of this class may operate without a user, or on behalf of many users. Use the Slack API dashboard to create a client ID and secret for this application.

You must configure your Slack API OAuth and Permissions page with a localhost URL like {@code http://localhost:53203/oauth/}, passing the same port to this class’ constructor.","code":"public final class SlackApi {\n private final HttpUrl baseUrl = HttpUrl.get(\"https://slack.com/api/\");\n private final OkHttpClient httpClient;\n private final Moshi moshi;\n\n public final String clientId;\n public final String clientSecret;\n public final int port;\n\n public SlackApi(String clientId, String clientSecret, int port) {\n this.httpClient = new OkHttpClient.Builder()\n .build();\n this.moshi = new Moshi.Builder()\n .add(new SlackJsonAdapters())\n .build();\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n this.port = port;\n }\n\n /** See https://api.slack.com/docs/oauth. */\n public HttpUrl authorizeUrl(String scopes, HttpUrl redirectUrl, ByteString state, String team) {\n HttpUrl.Builder builder = baseUrl.newBuilder(\"/oauth/authorize\")\n .addQueryParameter(\"client_id\", clientId)\n .addQueryParameter(\"scope\", scopes)\n .addQueryParameter(\"redirect_uri\", redirectUrl.toString())\n .addQueryParameter(\"state\", state.base64());\n\n if (team != null) {\n builder.addQueryParameter(\"team\", team);\n }\n\n return builder.build();\n }\n\n /** See https://api.slack.com/methods/oauth.access. */\n public OA"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":49,"symbol":"SlackApi","kind":"constructor","lang":"java","code":"public SlackApi(String clientId, String clientSecret, int port) {\n this.httpClient = new OkHttpClient.Builder()\n .build();\n this.moshi = new Moshi.Builder()\n .add(new SlackJsonAdapters())\n .build();\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n this.port = port;\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":61,"symbol":"authorizeUrl","kind":"method","lang":"java","doc":"See https://api.slack.com/docs/oauth.","code":"public HttpUrl authorizeUrl(String scopes, HttpUrl redirectUrl, ByteString state, String team) {\n HttpUrl.Builder builder = baseUrl.newBuilder(\"/oauth/authorize\")\n .addQueryParameter(\"client_id\", clientId)\n .addQueryParameter(\"scope\", scopes)\n .addQueryParameter(\"redirect_uri\", redirectUrl.toString())\n .addQueryParameter(\"state\", state.base64());\n\n if (team != null) {\n builder.addQueryParameter(\"team\", team);\n }\n\n return builder.build();\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":76,"symbol":"exchangeCode","kind":"method","lang":"java","doc":"See https://api.slack.com/methods/oauth.access.","code":"public OAuthSession exchangeCode(String code, HttpUrl redirectUrl) throws IOException {\n HttpUrl url = baseUrl.newBuilder(\"oauth.access\")\n .addQueryParameter(\"client_id\", clientId)\n .addQueryParameter(\"client_secret\", clientSecret)\n .addQueryParameter(\"code\", code)\n .addQueryParameter(\"redirect_uri\", redirectUrl.toString())\n .build();\n Request request = new Request.Builder()\n .url(url)\n .build();\n Call call = httpClient.newCall(request);\n try (Response response = call.execute()) {\n JsonAdapter jsonAdapter = moshi.adapter(OAuthSession.class);\n return jsonAdapter.fromJson(response.body().source());\n }\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":94,"symbol":"rtmStart","kind":"method","lang":"java","doc":"See https://api.slack.com/methods/rtm.start.","code":"public RtmStartResponse rtmStart(String accessToken) throws IOException {\n HttpUrl url = baseUrl.newBuilder(\"rtm.start\")\n .addQueryParameter(\"token\", accessToken)\n .build();\n Request request = new Request.Builder()\n .url(url)\n .build();\n Call call = httpClient.newCall(request);\n try (Response response = call.execute()) {\n JsonAdapter jsonAdapter = moshi.adapter(RtmStartResponse.class);\n return jsonAdapter.fromJson(response.body().source());\n }\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":109,"symbol":"rtm","kind":"method","lang":"java","doc":"See https://api.slack.com/rtm.","code":"public WebSocket rtm(HttpUrl url, WebSocketListener listener) {\n return httpClient.newWebSocket(new Request.Builder()\n .url(url)\n .build(), listener);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":115,"symbol":"SlackJsonAdapters","kind":"class","lang":"java","code":"static final class SlackJsonAdapters {\n @ToJson String urlToJson(HttpUrl httpUrl) {\n return httpUrl.toString();\n }\n\n @FromJson HttpUrl urlFromJson(String urlString) {\n if (urlString.startsWith(\"wss:\")) urlString = \"https:\" + urlString.substring(4);\n if (urlString.startsWith(\"ws:\")) urlString = \"http:\" + urlString.substring(3);\n return HttpUrl.get(urlString);\n }\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":116,"symbol":"urlToJson","kind":"method","lang":"java","code":"@ToJson String urlToJson(HttpUrl httpUrl) {\n return httpUrl.toString();\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackApi.java","line":120,"symbol":"urlFromJson","kind":"method","lang":"java","code":"@FromJson HttpUrl urlFromJson(String urlString) {\n if (urlString.startsWith(\"wss:\")) urlString = \"https:\" + urlString.substring(4);\n if (urlString.startsWith(\"ws:\")) urlString = \"http:\" + urlString.substring(3);\n return HttpUrl.get(urlString);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackClient.java","line":24,"symbol":"SlackClient","kind":"class","lang":"java","doc":"A connection to Slack as a single user.","code":"public final class SlackClient {\n private final SlackApi slackApi;\n private OAuthSessionFactory sessionFactory;\n\n /** Guarded by this. */\n private OAuthSession session;\n\n public SlackClient(SlackApi slackApi) {\n this.slackApi = slackApi;\n }\n\n /** Shows a browser URL to authorize this app to act as this user. */\n public void requestOauthSession(String scopes, String team) throws Exception {\n if (sessionFactory == null) {\n sessionFactory = new OAuthSessionFactory(slackApi);\n sessionFactory.start();\n }\n\n HttpUrl authorizeUrl = sessionFactory.newAuthorizeUrl(scopes, team, session -> {\n initOauthSession(session);\n System.out.printf(\"session granted: %s\\n\", session);\n });\n\n System.out.printf(\"open this URL in a browser: %s\\n\", authorizeUrl);\n }\n\n /** Set the OAuth session for this client. */\n public synchronized void initOauthSession(OAuthSession session) {\n this.session = session;\n this.notifyAll();\n }\n\n /** Waits for an OAuth session for this client to be set. */\n public synchronized void awaitAccessToken(Timeout timeout) throws InterruptedIOException {\n while (session == null) {\n timeout.waitUntilNotified(this);\n }\n "} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackClient.java","line":31,"symbol":"SlackClient","kind":"constructor","lang":"java","code":"public SlackClient(SlackApi slackApi) {\n this.slackApi = slackApi;\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackClient.java","line":36,"symbol":"requestOauthSession","kind":"method","lang":"java","doc":"Shows a browser URL to authorize this app to act as this user.","code":"public void requestOauthSession(String scopes, String team) throws Exception {\n if (sessionFactory == null) {\n sessionFactory = new OAuthSessionFactory(slackApi);\n sessionFactory.start();\n }\n\n HttpUrl authorizeUrl = sessionFactory.newAuthorizeUrl(scopes, team, session -> {\n initOauthSession(session);\n System.out.printf(\"session granted: %s\\n\", session);\n });\n\n System.out.printf(\"open this URL in a browser: %s\\n\", authorizeUrl);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackClient.java","line":51,"symbol":"initOauthSession","kind":"method","lang":"java","doc":"Set the OAuth session for this client.","code":"public synchronized void initOauthSession(OAuthSession session) {\n this.session = session;\n this.notifyAll();\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackClient.java","line":57,"symbol":"awaitAccessToken","kind":"method","lang":"java","doc":"Waits for an OAuth session for this client to be set.","code":"public synchronized void awaitAccessToken(Timeout timeout) throws InterruptedIOException {\n while (session == null) {\n timeout.waitUntilNotified(this);\n }\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackClient.java","line":64,"symbol":"startRtm","kind":"method","lang":"java","doc":"Starts a real time messaging session.","code":"public void startRtm() throws IOException {\n String accessToken;\n synchronized (this) {\n accessToken = session.access_token;\n }\n\n RtmSession rtmSession = new RtmSession(slackApi);\n rtmSession.open(accessToken);\n }"} {"repo":"okhttp","file":"samples/slack/src/main/java/okhttp3/slack/SlackClient.java","line":74,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n String clientId = \"0000000000.00000000000\";\n String clientSecret = \"00000000000000000000000000000000\";\n int port = 53203;\n SlackApi slackApi = new SlackApi(clientId, clientSecret, port);\n\n SlackClient client = new SlackClient(slackApi);\n String scopes = \"channels:history channels:read channels:write chat:write:bot chat:write:user \"\n + \"dnd:read dnd:write emoji:read files:read files:write:user groups:history groups:read \"\n + \"groups:write im:history im:read im:write mpim:history mpim:read mpim:write pins:read \"\n + \"pins:write reactions:read reactions:write search:read stars:read stars:write team:read \"\n + \"usergroups:read usergroups:write users:read users:write identify\";\n\n if (true) {\n client.requestOauthSession(scopes, null);\n } else {\n OAuthSession session = new OAuthSession(true,\n \"xoxp-XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n scopes, \"UXXXXXXXX\", \"My Slack Group\", \"TXXXXXXXX\");\n client.initOauthSession(session);\n }\n\n client.awaitAccessToken(Timeout.NONE);\n client.startRtm();\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":36,"symbol":"SampleServer","kind":"class","lang":"java","code":"public class SampleServer extends Dispatcher {\n private final SSLContext sslContext;\n private final String root;\n private final int port;\n\n public SampleServer(SSLContext sslContext, String root, int port) {\n this.sslContext = sslContext;\n this.root = root;\n this.port = port;\n }\n\n public void run() throws IOException {\n MockWebServer server = new MockWebServer();\n server.useHttps(sslContext.getSocketFactory(), false);\n server.setDispatcher(this);\n server.start(port);\n }\n\n @Override public MockResponse dispatch(RecordedRequest request) {\n String path = request.getPath();\n try {\n if (!path.startsWith(\"/\") || path.contains(\"..\")) throw new FileNotFoundException();\n\n File file = new File(root + path);\n return file.isDirectory()\n ? directoryToResponse(path, file)\n : fileToResponse(path, file);\n } catch (FileNotFoundException e) {\n return new MockResponse()\n .setStatus(\"HTTP/1.1 404\")\n .addHeader(\"content-type: text/plain; charset=utf-8\")\n .setBody(\"NOT FOUND: \" + path);\n } catch (IOException e) {\n return new MockResponse()\n .setStatus(\"HTTP/1.1 500\")\n .addHead"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":41,"symbol":"SampleServer","kind":"constructor","lang":"java","code":"public SampleServer(SSLContext sslContext, String root, int port) {\n this.sslContext = sslContext;\n this.root = root;\n this.port = port;\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":47,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws IOException {\n MockWebServer server = new MockWebServer();\n server.useHttps(sslContext.getSocketFactory(), false);\n server.setDispatcher(this);\n server.start(port);\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":54,"symbol":"dispatch","kind":"method","lang":"java","code":"@Override public MockResponse dispatch(RecordedRequest request) {\n String path = request.getPath();\n try {\n if (!path.startsWith(\"/\") || path.contains(\"..\")) throw new FileNotFoundException();\n\n File file = new File(root + path);\n return file.isDirectory()\n ? directoryToResponse(path, file)\n : fileToResponse(path, file);\n } catch (FileNotFoundException e) {\n return new MockResponse()\n .setStatus(\"HTTP/1.1 404\")\n .addHeader(\"content-type: text/plain; charset=utf-8\")\n .setBody(\"NOT FOUND: \" + path);\n } catch (IOException e) {\n return new MockResponse()\n .setStatus(\"HTTP/1.1 500\")\n .addHeader(\"content-type: text/plain; charset=utf-8\")\n .setBody(\"SERVER ERROR: \" + e);\n }\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":76,"symbol":"directoryToResponse","kind":"method","lang":"java","code":"private MockResponse directoryToResponse(String basePath, File directory) {\n if (!basePath.endsWith(\"/\")) basePath += \"/\";\n\n StringBuilder response = new StringBuilder();\n response.append(String.format(\"%s\", basePath));\n response.append(String.format(\"

%s

\", basePath));\n for (String file : directory.list()) {\n response.append(String.format(\"\",\n basePath + file, file));\n }\n response.append(\"\");\n\n return new MockResponse()\n .setStatus(\"HTTP/1.1 200\")\n .addHeader(\"content-type: text/html; charset=utf-8\")\n .setBody(response.toString());\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":94,"symbol":"fileToResponse","kind":"method","lang":"java","code":"private MockResponse fileToResponse(String path, File file) throws IOException {\n return new MockResponse()\n .setStatus(\"HTTP/1.1 200\")\n .setBody(fileToBytes(file))\n .addHeader(\"content-type: \" + contentType(path));\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":101,"symbol":"fileToBytes","kind":"method","lang":"java","code":"private Buffer fileToBytes(File file) throws IOException {\n Buffer result = new Buffer();\n result.writeAll(Okio.source(file));\n return result;\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":107,"symbol":"contentType","kind":"method","lang":"java","code":"private String contentType(String path) {\n if (path.endsWith(\".png\")) return \"image/png\";\n if (path.endsWith(\".jpg\")) return \"image/jpeg\";\n if (path.endsWith(\".jpeg\")) return \"image/jpeg\";\n if (path.endsWith(\".gif\")) return \"image/gif\";\n if (path.endsWith(\".html\")) return \"text/html; charset=utf-8\";\n if (path.endsWith(\".txt\")) return \"text/plain; charset=utf-8\";\n return \"application/octet-stream\";\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":117,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String[] args) throws Exception {\n if (args.length != 4) {\n System.out.println(\"Usage: SampleServer \");\n return;\n }\n\n String keystoreFile = args[0];\n String password = args[1];\n String root = args[2];\n int port = Integer.parseInt(args[3]);\n\n SSLContext sslContext = sslContext(keystoreFile, password);\n SampleServer server = new SampleServer(sslContext, root, port);\n server.run();\n }"} {"repo":"okhttp","file":"samples/static-server/src/main/java/okhttp3/sample/SampleServer.java","line":133,"symbol":"sslContext","kind":"method","lang":"java","code":"private static SSLContext sslContext(String keystoreFile, String password)\n throws GeneralSecurityException, IOException {\n KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());\n try (InputStream in = new FileInputStream(keystoreFile)) {\n keystore.load(in, password.toCharArray());\n }\n KeyManagerFactory keyManagerFactory =\n KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\n keyManagerFactory.init(keystore, password.toCharArray());\n\n TrustManagerFactory trustManagerFactory =\n TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n trustManagerFactory.init(keystore);\n\n SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n sslContext.init(\n keyManagerFactory.getKeyManagers(),\n trustManagerFactory.getTrustManagers(),\n new SecureRandom());\n\n return sslContext;\n }"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/CipherSuiteSurvey.kt","line":25,"symbol":"CipherSuiteSurvey","kind":"class","lang":"kotlin","doc":"Organizes information on SSL cipher suite inclusion and precedence for this spreadsheet. https://docs.google.com/spreadsheets/d/1C3FdZSlCBq_-qrVwG1KDIzNIB3Hyg_rKAcgmSzOsHyQ/edit#gid=0","code":"class CipherSuiteSurvey(\n val clients: List,\n val ianaSuites: IanaSuites,\n val orderBy: List,\n) {\n fun printGoogleSheet() {\n print(\"name\")\n for (client in clients) {\n print(\"\\t\")\n print(client.nameAndVersion)\n }\n println()\n val sortedSuites =\n ianaSuites.suites.sortedBy { ianaSuite ->\n val index = orderBy.indexOfFirst { it.matches(ianaSuite) }\n if (index == -1) Integer.MAX_VALUE else index\n }\n for (suiteId in sortedSuites) {\n print(suiteId.name)\n for (client in clients) {\n print(\"\\t\")\n val index = client.enabled.indexOfFirst { it.matches(suiteId) }\n if (index != -1) {\n print(index + 1)\n }\n }\n println()\n }\n }\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/CipherSuiteSurvey.kt","line":30,"symbol":"printGoogleSheet","kind":"function","lang":"kotlin","code":"fun printGoogleSheet() {\n print(\"name\")\n for (client in clients) {\n print(\"\\t\")\n print(client.nameAndVersion)\n }\n println()\n val sortedSuites =\n ianaSuites.suites.sortedBy { ianaSuite ->\n val index = orderBy.indexOfFirst { it.matches(ianaSuite) }\n if (index == -1) Integer.MAX_VALUE else index\n }\n for (suiteId in sortedSuites) {\n print(suiteId.name)\n for (client in clients) {\n print(\"\\t\")\n val index = client.enabled.indexOfFirst { it.matches(suiteId) }\n if (index != -1) {\n print(index + 1)\n }\n }\n println()\n }\n }"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/Clients.kt","line":28,"symbol":"currentOkHttp","kind":"function","lang":"kotlin","code":"fun currentOkHttp(ianaSuites: IanaSuites): Client =\n Client(\n userAgent = \"OkHttp\",\n version = OkHttp.VERSION,\n enabled =\n ConnectionSpec.MODERN_TLS.cipherSuites!!.map {\n ianaSuites.fromJavaName(it.javaName)\n },\n supported =\n ConnectionSpec.COMPATIBLE_TLS.cipherSuites!!.map {\n ianaSuites.fromJavaName(it.javaName)\n },\n )"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/Clients.kt","line":42,"symbol":"historicOkHttp","kind":"function","lang":"kotlin","code":"fun historicOkHttp(version: String): Client {\n val enabled =\n FileSystem.RESOURCES.read(\"okhttp_$version.txt\".toPath()) {\n this.readUtf8().lines().filter { it.isNotBlank() }.map {\n SuiteId(id = null, name = it.trim())\n }\n }\n return Client(\n userAgent = \"OkHttp\",\n version = version,\n enabled = enabled,\n )\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/Clients.kt","line":56,"symbol":"currentVm","kind":"function","lang":"kotlin","code":"fun currentVm(ianaSuites: IanaSuites): Client =\n systemDefault(\n name = System.getProperty(\"java.vm.name\"),\n version = System.getProperty(\"java.version\"),\n ianaSuites = ianaSuites,\n )"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/Clients.kt","line":63,"symbol":"conscrypt","kind":"function","lang":"kotlin","code":"fun conscrypt(ianaSuites: IanaSuites): Client {\n val version = Conscrypt.version()\n return systemDefault(\n name = \"Conscrypt\",\n version = \"${version.major()}.${version.minor()}\",\n ianaSuites = ianaSuites,\n )\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/Clients.kt","line":72,"symbol":"systemDefault","kind":"function","lang":"kotlin","code":"fun systemDefault(\n name: String,\n version: String,\n ianaSuites: IanaSuites,\n): Client {\n val socketFactory = SSLSocketFactory.getDefault() as SSLSocketFactory\n val sslSocket = socketFactory.createSocket() as SSLSocket\n\n return Client(\n userAgent = name,\n version = version,\n enabled = sslSocket.enabledCipherSuites.map { ianaSuites.fromJavaName(it) },\n supported = sslSocket.supportedCipherSuites.map { ianaSuites.fromJavaName(it) },\n )\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/Iana.kt","line":46,"symbol":"fetchIanaSuites","kind":"function","lang":"kotlin","code":"suspend fun fetchIanaSuites(okHttpClient: OkHttpClient): IanaSuites {\n val url = \"https://www.iana.org/assignments/tls-parameters/tls-parameters-4.csv\"\n\n val call = okHttpClient.newCall(Request(url.toHttpUrl()))\n\n val suites =\n call.executeAsync().use {\n if (!it.isSuccessful) {\n throw IOException(\"Failed ${it.code} ${it.message}\")\n }\n it.body\n .string()\n .lines()\n .mapNotNull { parseIanaCsvRow(it) }\n }\n\n return IanaSuites(\"current\", suites)\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/RunSurvey.kt","line":28,"symbol":"main","kind":"function","lang":"kotlin","code":"@Suppress(\"ktlint:standard:property-naming\")\nsuspend fun main() {\n val includeConscrypt = false\n\n val client =\n OkHttpClient\n .Builder()\n .cache(Cache(FileSystem.SYSTEM, \"build/okhttp_cache\".toPath(), 100_000_000))\n .build()\n\n val sslLabsClients = SslLabsClient(client).clients()\n val ianaSuitesNew = fetchIanaSuites(client)\n\n val android5 = sslLabsClients.first { it.userAgent == \"Android\" && it.version == \"5.0.0\" }\n val android9 = sslLabsClients.first { it.userAgent == \"Android\" && it.version == \"9.0\" }\n val chrome33 = sslLabsClients.first { it.userAgent == \"Chrome\" && it.version == \"33\" }\n val chrome57 = sslLabsClients.first { it.userAgent == \"Chrome\" && it.version == \"57\" }\n val chrome80 = sslLabsClients.first { it.userAgent == \"Chrome\" && it.version == \"80\" }\n val firefox34 = sslLabsClients.first { it.userAgent == \"Firefox\" && it.version == \"34\" }\n val firefox53 = sslLabsClients.first { it.userAgent == \"Firefox\" && it.version == \"53\" }\n val firefox73 = sslLabsClients.first { it.userAgent == \"Firefox\" && it.version == \"73\" }\n val java7 = sslLabsClients.first { it.userAgent == \"Java\" && it.version == \"7u25\" }\n val java12 = sslLabsClients.first { it.u"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/RunSurvey.kt","line":103,"symbol":"rest","kind":"function","lang":"kotlin","code":"fun rest(clients: List): List {\n // combine all ciphers to get these near the top\n return clients.flatMap { it.enabled }\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/ssllabs/SslLabsApi.kt","line":20,"symbol":"SslLabsApi","kind":"interface","lang":"kotlin","code":"interface SslLabsApi {\n @GET(\"getClients\")\n suspend fun clients(): List\n\n companion object {\n const val BASE_URL = \"https://api.ssllabs.com/api/v3/\"\n }\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/ssllabs/SslLabsApi.kt","line":21,"symbol":"clients","kind":"function","lang":"kotlin","code":"@GET(\"getClients\")\n suspend fun clients(): List"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/ssllabs/SslLabsClient.kt","line":26,"symbol":"SslLabsClient","kind":"class","lang":"kotlin","code":"class SslLabsClient(\n callFactory: Call.Factory,\n) {\n private val moshi = Moshi.Builder().build()\n\n private val moshiConverterFactory = MoshiConverterFactory.create(moshi)\n\n private val retrofit =\n Retrofit\n .Builder()\n .baseUrl(SslLabsApi.BASE_URL)\n .addConverterFactory(moshiConverterFactory)\n .callFactory(callFactory)\n .build()\n\n private val sslLabsApi = retrofit.create(SslLabsApi::class.java)\n\n suspend fun clients(): List =\n sslLabsApi.clients().map { userAgent ->\n Client(\n userAgent = userAgent.name,\n version = userAgent.version,\n platform = userAgent.platform,\n enabled = userAgent.suiteNames.map { SuiteId(null, it) },\n )\n }\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/ssllabs/SslLabsClient.kt","line":43,"symbol":"clients","kind":"function","lang":"kotlin","code":"suspend fun clients(): List =\n sslLabsApi.clients().map { userAgent ->\n Client(\n userAgent = userAgent.name,\n version = userAgent.version,\n platform = userAgent.platform,\n enabled = userAgent.suiteNames.map { SuiteId(null, it) },\n )\n }"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/ssllabs/SslLabsClient.kt","line":54,"symbol":"main","kind":"function","lang":"kotlin","code":"suspend fun main() {\n val sslLabsClient =\n SslLabsClient(\n callFactory = OkHttpClient(),\n )\n\n for (client in sslLabsClient.clients()) {\n println(client)\n }\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/types/Client.kt","line":18,"symbol":"Client","kind":"class","lang":"kotlin","code":"data class Client(\n val userAgent: String,\n val version: String,\n val platform: String? = null,\n val enabled: List = listOf(),\n val supported: List = listOf(),\n) {\n val nameAndVersion: String\n get() = \"$userAgent/$version\"\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/types/SuiteId.kt","line":20,"symbol":"SuiteId","kind":"class","lang":"kotlin","code":"data class SuiteId(\n val id: ByteString?,\n val name: String,\n) {\n fun matches(suiteId: SuiteId): Boolean = id == suiteId.id || name.substring(4) == suiteId.name.substring(4)\n}"} {"repo":"okhttp","file":"samples/tlssurvey/src/main/kotlin/okhttp3/survey/types/SuiteId.kt","line":24,"symbol":"matches","kind":"function","lang":"kotlin","code":"fun matches(suiteId: SuiteId): Boolean = id == suiteId.id || name.substring(4) == suiteId.name.substring(4)"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/ClientAndServer.java","line":31,"symbol":"ClientAndServer","kind":"class","lang":"java","doc":"Create UNIX domain sockets for MockWebServer and OkHttp and connect 'em together. Note that we cannot do TLS over domain sockets.","code":"public class ClientAndServer {\n public void run() throws Exception {\n File socketFile = new File(\"/tmp/ClientAndServer.sock\");\n socketFile.delete(); // Clean up from previous runs.\n\n MockWebServer server = new MockWebServer();\n server.setServerSocketFactory(new UnixDomainServerSocketFactory(socketFile));\n server.setProtocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE));\n server.enqueue(new MockResponse().setBody(\"hello\"));\n server.start();\n\n OkHttpClient client = new OkHttpClient.Builder()\n .socketFactory(new UnixDomainSocketFactory(socketFile))\n .protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE))\n .build();\n\n Request request = new Request.Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n System.out.println(response.body().string());\n }\n\n server.shutdown();\n socketFile.delete();\n }\n\n public static void main(String... args) throws Exception {\n new ClientAndServer().run();\n }\n}"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/ClientAndServer.java","line":32,"symbol":"run","kind":"method","lang":"java","code":"public void run() throws Exception {\n File socketFile = new File(\"/tmp/ClientAndServer.sock\");\n socketFile.delete(); // Clean up from previous runs.\n\n MockWebServer server = new MockWebServer();\n server.setServerSocketFactory(new UnixDomainServerSocketFactory(socketFile));\n server.setProtocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE));\n server.enqueue(new MockResponse().setBody(\"hello\"));\n server.start();\n\n OkHttpClient client = new OkHttpClient.Builder()\n .socketFactory(new UnixDomainSocketFactory(socketFile))\n .protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE))\n .build();\n\n Request request = new Request.Builder()\n .url(\"http://publicobject.com/helloworld.txt\")\n .build();\n\n try (Response response = client.newCall(request).execute()) {\n System.out.println(response.body().string());\n }\n\n server.shutdown();\n socketFile.delete();\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/ClientAndServer.java","line":59,"symbol":"main","kind":"method","lang":"java","code":"public static void main(String... args) throws Exception {\n new ClientAndServer().run();\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/TunnelingUnixSocket.java","line":31,"symbol":"TunnelingUnixSocket","kind":"class","lang":"java","doc":"Subtype UNIX socket for a higher-fidelity impersonation of TCP sockets. This is named \"tunneling\" because it assumes the ultimate destination has a hostname and port.","code":"final class TunnelingUnixSocket extends UnixSocket {\n private final File path;\n private InetSocketAddress inetSocketAddress;\n\n TunnelingUnixSocket(File path, UnixSocketChannel channel) {\n super(channel);\n this.path = path;\n }\n\n TunnelingUnixSocket(File path, UnixSocketChannel channel, InetSocketAddress address) {\n this(path, channel);\n this.inetSocketAddress = address;\n }\n\n @Override public void connect(SocketAddress endpoint) throws IOException {\n this.inetSocketAddress = (InetSocketAddress) endpoint;\n super.connect(new UnixSocketAddress(path), 0);\n }\n\n @Override public void connect(SocketAddress endpoint, int timeout) throws IOException {\n this.inetSocketAddress = (InetSocketAddress) endpoint;\n super.connect(new UnixSocketAddress(path), timeout);\n }\n\n @Override public InetAddress getInetAddress() {\n return inetSocketAddress.getAddress();\n }\n}"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/TunnelingUnixSocket.java","line":35,"symbol":"TunnelingUnixSocket","kind":"constructor","lang":"java","code":"TunnelingUnixSocket(File path, UnixSocketChannel channel) {\n super(channel);\n this.path = path;\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/TunnelingUnixSocket.java","line":40,"symbol":"TunnelingUnixSocket","kind":"constructor","lang":"java","code":"TunnelingUnixSocket(File path, UnixSocketChannel channel, InetSocketAddress address) {\n this(path, channel);\n this.inetSocketAddress = address;\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/TunnelingUnixSocket.java","line":45,"symbol":"connect","kind":"method","lang":"java","code":"@Override public void connect(SocketAddress endpoint) throws IOException {\n this.inetSocketAddress = (InetSocketAddress) endpoint;\n super.connect(new UnixSocketAddress(path), 0);\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/TunnelingUnixSocket.java","line":50,"symbol":"connect","kind":"method","lang":"java","code":"@Override public void connect(SocketAddress endpoint, int timeout) throws IOException {\n this.inetSocketAddress = (InetSocketAddress) endpoint;\n super.connect(new UnixSocketAddress(path), timeout);\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/TunnelingUnixSocket.java","line":55,"symbol":"getInetAddress","kind":"method","lang":"java","code":"@Override public InetAddress getInetAddress() {\n return inetSocketAddress.getAddress();\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":33,"symbol":"UnixDomainServerSocketFactory","kind":"class","lang":"java","doc":"Impersonate TCP-style ServerSocketFactory over UNIX domain sockets.","code":"public final class UnixDomainServerSocketFactory extends ServerSocketFactory {\n private final File path;\n\n public UnixDomainServerSocketFactory(File path) {\n this.path = path;\n }\n\n @Override public ServerSocket createServerSocket() throws IOException {\n return new UnixDomainServerSocket();\n }\n\n @Override public ServerSocket createServerSocket(int port) throws IOException {\n return createServerSocket();\n }\n\n @Override public ServerSocket createServerSocket(int port, int backlog) throws IOException {\n return createServerSocket();\n }\n\n @Override public ServerSocket createServerSocket(\n int port, int backlog, InetAddress inetAddress) throws IOException {\n return createServerSocket();\n }\n\n final class UnixDomainServerSocket extends ServerSocket {\n private UnixServerSocketChannel serverSocketChannel;\n private InetSocketAddress endpoint;\n\n UnixDomainServerSocket() throws IOException {\n }\n\n @Override public void bind(SocketAddress endpoint, int backlog) throws IOException {\n this.endpoint = (InetSocketAddress) endpoint;\n\n UnixSocketAddress address = new UnixSocketAddress(path);\n serverSocketChannel = UnixServerSocketChannel.open"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":36,"symbol":"UnixDomainServerSocketFactory","kind":"constructor","lang":"java","code":"public UnixDomainServerSocketFactory(File path) {\n this.path = path;\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":40,"symbol":"createServerSocket","kind":"method","lang":"java","code":"@Override public ServerSocket createServerSocket() throws IOException {\n return new UnixDomainServerSocket();\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":44,"symbol":"createServerSocket","kind":"method","lang":"java","code":"@Override public ServerSocket createServerSocket(int port) throws IOException {\n return createServerSocket();\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":48,"symbol":"createServerSocket","kind":"method","lang":"java","code":"@Override public ServerSocket createServerSocket(int port, int backlog) throws IOException {\n return createServerSocket();\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":52,"symbol":"createServerSocket","kind":"method","lang":"java","code":"@Override public ServerSocket createServerSocket(\n int port, int backlog, InetAddress inetAddress) throws IOException {\n return createServerSocket();\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":57,"symbol":"UnixDomainServerSocket","kind":"class","lang":"java","code":"final class UnixDomainServerSocket extends ServerSocket {\n private UnixServerSocketChannel serverSocketChannel;\n private InetSocketAddress endpoint;\n\n UnixDomainServerSocket() throws IOException {\n }\n\n @Override public void bind(SocketAddress endpoint, int backlog) throws IOException {\n this.endpoint = (InetSocketAddress) endpoint;\n\n UnixSocketAddress address = new UnixSocketAddress(path);\n serverSocketChannel = UnixServerSocketChannel.open();\n serverSocketChannel.configureBlocking(true);\n serverSocketChannel.socket().bind(address);\n }\n\n @Override public int getLocalPort() {\n return 1; // A white lie. There is no local port.\n }\n\n @Override public SocketAddress getLocalSocketAddress() {\n return endpoint;\n }\n\n @Override public Socket accept() throws IOException {\n try {\n UnixSocketChannel channel = serverSocketChannel.accept();\n return new TunnelingUnixSocket(path, channel, endpoint);\n } catch (ClosedChannelException e) {\n SocketException exception = new SocketException();\n exception.initCause(e);\n throw exception;\n }\n }\n\n @Override public void close() throws IO"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":61,"symbol":"UnixDomainServerSocket","kind":"constructor","lang":"java","code":"UnixDomainServerSocket() throws IOException {\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":64,"symbol":"bind","kind":"method","lang":"java","code":"@Override public void bind(SocketAddress endpoint, int backlog) throws IOException {\n this.endpoint = (InetSocketAddress) endpoint;\n\n UnixSocketAddress address = new UnixSocketAddress(path);\n serverSocketChannel = UnixServerSocketChannel.open();\n serverSocketChannel.configureBlocking(true);\n serverSocketChannel.socket().bind(address);\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":73,"symbol":"getLocalPort","kind":"method","lang":"java","code":"@Override public int getLocalPort() {\n return 1; // A white lie. There is no local port.\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":77,"symbol":"getLocalSocketAddress","kind":"method","lang":"java","code":"@Override public SocketAddress getLocalSocketAddress() {\n return endpoint;\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":81,"symbol":"accept","kind":"method","lang":"java","code":"@Override public Socket accept() throws IOException {\n try {\n UnixSocketChannel channel = serverSocketChannel.accept();\n return new TunnelingUnixSocket(path, channel, endpoint);\n } catch (ClosedChannelException e) {\n SocketException exception = new SocketException();\n exception.initCause(e);\n throw exception;\n }\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainServerSocketFactory.java","line":92,"symbol":"close","kind":"method","lang":"java","code":"@Override public void close() throws IOException {\n serverSocketChannel.close();\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainSocketFactory.java","line":27,"symbol":"UnixDomainSocketFactory","kind":"class","lang":"java","doc":"Impersonate TCP-style SocketFactory over UNIX domain sockets.","code":"public final class UnixDomainSocketFactory extends SocketFactory {\n private final File path;\n\n public UnixDomainSocketFactory(File path) {\n this.path = path;\n }\n\n @Override public Socket createSocket() throws IOException {\n UnixSocketChannel channel = UnixSocketChannel.open();\n return new TunnelingUnixSocket(path, channel);\n }\n\n @Override public Socket createSocket(String host, int port) throws IOException {\n Socket result = createSocket();\n\n try {\n result.connect(new InetSocketAddress(host, port));\n } catch (IOException e) {\n result.close();\n throw e;\n }\n return result;\n }\n\n @Override public Socket createSocket(\n String host, int port, InetAddress localHost, int localPort) throws IOException {\n return createSocket(host, port);\n }\n\n @Override public Socket createSocket(InetAddress host, int port) throws IOException {\n Socket result = createSocket();\n\n try {\n result.connect(new InetSocketAddress(host, port));\n } catch (IOException e) {\n result.close();\n throw e;\n }\n return result;\n }\n\n @Override public Socket createSocket(\n InetAddress host, int port, InetAddress localAddress, int localPort"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainSocketFactory.java","line":30,"symbol":"UnixDomainSocketFactory","kind":"constructor","lang":"java","code":"public UnixDomainSocketFactory(File path) {\n this.path = path;\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainSocketFactory.java","line":34,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket() throws IOException {\n UnixSocketChannel channel = UnixSocketChannel.open();\n return new TunnelingUnixSocket(path, channel);\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainSocketFactory.java","line":39,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(String host, int port) throws IOException {\n Socket result = createSocket();\n\n try {\n result.connect(new InetSocketAddress(host, port));\n } catch (IOException e) {\n result.close();\n throw e;\n }\n return result;\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainSocketFactory.java","line":51,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(\n String host, int port, InetAddress localHost, int localPort) throws IOException {\n return createSocket(host, port);\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainSocketFactory.java","line":56,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(InetAddress host, int port) throws IOException {\n Socket result = createSocket();\n\n try {\n result.connect(new InetSocketAddress(host, port));\n } catch (IOException e) {\n result.close();\n throw e;\n }\n return result;\n }"} {"repo":"okhttp","file":"samples/unixdomainsockets/src/main/java/okhttp3/unixdomainsockets/UnixDomainSocketFactory.java","line":68,"symbol":"createSocket","kind":"method","lang":"java","code":"@Override public Socket createSocket(\n InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException {\n return createSocket(host, port);\n }"}