Skip to content

Commit

Permalink
Merge pull request square#5085 from square/jwilson.0520.use_vals
Browse files Browse the repository at this point in the history
Adopt HttpUrl's new Kotlin API
  • Loading branch information
JakeWharton authored May 21, 2019
2 parents f465599 + e67ec3c commit d01d9f7
Show file tree
Hide file tree
Showing 18 changed files with 64 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1019,7 +1019,7 @@ class MockWebServer : ExternalResource(), Closeable {
) {
for (pushPromise in promises) {
val pushedHeaders = mutableListOf<Header>()
pushedHeaders.add(Header(Header.TARGET_AUTHORITY, url(pushPromise.path).host()))
pushedHeaders.add(Header(Header.TARGET_AUTHORITY, url(pushPromise.path).host))
pushedHeaders.add(Header(Header.TARGET_METHOD, pushPromise.method))
pushedHeaders.add(Header(Header.TARGET_PATH, pushPromise.path))
val pushPromiseHeaders = pushPromise.headers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ class DnsOverHttps internal constructor(builder: Builder) : Dns {
val hosts = builder.bootstrapDnsHosts

return if (hosts != null) {
BootstrapDns(builder.url!!.host(), hosts)
BootstrapDns(builder.url!!.host, hosts)
} else {
builder.systemDns
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,21 @@ class JavaNetAuthenticator : okhttp3.Authenticator {
proxyAddress.hostName,
proxy.connectToInetAddress(url),
proxyAddress.port,
url.scheme(),
url.scheme,
challenge.realm,
challenge.scheme,
url.url(),
url.toUrl(),
Authenticator.RequestorType.PROXY
)
} else {
Authenticator.requestPasswordAuthentication(
url.host(),
url.host,
proxy.connectToInetAddress(url),
url.port(),
url.scheme(),
url.port,
url.scheme,
challenge.realm,
challenge.scheme,
url.url(),
url.toUrl(),
Authenticator.RequestorType.SERVER
)
}
Expand All @@ -80,7 +80,7 @@ class JavaNetAuthenticator : okhttp3.Authenticator {
@Throws(IOException::class)
private fun Proxy.connectToInetAddress(url: HttpUrl): InetAddress {
return when {
type() == Proxy.Type.DIRECT -> InetAddress.getByName(url.host())
type() == Proxy.Type.DIRECT -> InetAddress.getByName(url.host)
else -> (address() as InetSocketAddress).address
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
}
val multimap = mapOf("Set-Cookie" to cookieStrings)
try {
cookieHandler.put(url.uri(), multimap)
cookieHandler.put(url.toUri(), multimap)
} catch (e: IOException) {
Platform.get().log(WARN, "Saving cookies failed for " + url.resolve("/...")!!, e)
}
Expand All @@ -45,7 +45,7 @@ class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val cookieHeaders = try {
// The RI passes all headers. We don't have 'em, so we don't pass 'em!
cookieHandler.get(url.uri(), emptyMap<String, List<String>>())
cookieHandler.get(url.toUri(), emptyMap<String, List<String>>())
} catch (e: IOException) {
Platform.get().log(WARN, "Loading cookies failed for " + url.resolve("/...")!!, e)
return emptyList()
Expand Down Expand Up @@ -102,7 +102,7 @@ class JavaNetCookieJar(private val cookieHandler: CookieHandler) : CookieJar {
result.add(Cookie.Builder()
.name(name)
.value(value)
.domain(url.host())
.domain(url.host)
.build())
pos = pairEnd + 1
}
Expand Down
4 changes: 2 additions & 2 deletions okhttp/src/main/java/okhttp3/Address.kt
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,12 @@ class Address(
this.sslSocketFactory == that.sslSocketFactory &&
this.hostnameVerifier == that.hostnameVerifier &&
this.certificatePinner == that.certificatePinner &&
this.url.port() == that.url.port()
this.url.port == that.url.port
}

override fun toString(): String {
return "Address{" +
"${url.host()}:${url.port()}, " +
"${url.host}:${url.port}, " +
(if (proxy != null) "proxy=$proxy" else "proxySelector=$proxySelector") +
"}"
}
Expand Down
4 changes: 2 additions & 2 deletions okhttp/src/main/java/okhttp3/CertificatePinner.kt
Original file line number Diff line number Diff line change
Expand Up @@ -292,10 +292,10 @@ data class CertificatePinner internal constructor(
internal fun newPin(pattern: String, pin: String): Pin {
val canonicalHostname = when {
pattern.startsWith(WILDCARD) -> {
HttpUrl.get("http://${pattern.substring(WILDCARD.length)}").host()
HttpUrl.get("http://${pattern.substring(WILDCARD.length)}").host
}
else -> {
HttpUrl.get("http://$pattern").host()
HttpUrl.get("http://$pattern").host
}
}

Expand Down
10 changes: 5 additions & 5 deletions okhttp/src/main/java/okhttp3/Cookie.kt
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ data class Cookie private constructor(
*/
fun matches(url: HttpUrl): Boolean {
val domainMatch = if (hostOnly) {
url.host() == domain
url.host == domain
} else {
domainMatch(url.host(), domain)
domainMatch(url.host, domain)
}
if (!domainMatch) return false

Expand Down Expand Up @@ -313,7 +313,7 @@ data class Cookie private constructor(
}

private fun pathMatch(url: HttpUrl, path: String): Boolean {
val urlPath = url.encodedPath()
val urlPath = url.encodedPath

if (urlPath == path) {
return true // As in '/foo' matching '/foo'.
Expand Down Expand Up @@ -426,7 +426,7 @@ data class Cookie private constructor(
}

// If the domain is present, it must domain match. Otherwise we have a host-only cookie.
val urlHost = url.host()
val urlHost = url.host
if (domain == null) {
domain = urlHost
} else if (!domainMatch(urlHost, domain)) {
Expand All @@ -442,7 +442,7 @@ data class Cookie private constructor(
// If the path is absent or didn't start with '/', use the default path. It's a string like
// '/foo/bar' for a URL like 'http://example.com/foo/bar/baz'. It always starts with '/'.
if (path == null || !path.startsWith("/")) {
val encodedPath = url.encodedPath()
val encodedPath = url.encodedPath
val lastSlash = encodedPath.lastIndexOf('/')
path = if (lastSlash != 0) encodedPath.substring(0, lastSlash) else "/"
}
Expand Down
18 changes: 9 additions & 9 deletions okhttp/src/main/java/okhttp3/HttpUrl.kt
Original file line number Diff line number Diff line change
Expand Up @@ -738,15 +738,15 @@ class HttpUrl internal constructor(
fun newBuilder(): Builder {
val result = Builder()
result.scheme = scheme
result.encodedUsername = encodedUsername()
result.encodedPassword = encodedPassword()
result.encodedUsername = encodedUsername
result.encodedPassword = encodedPassword
result.host = host
// If we're set to a default port, unset it in case of a scheme change.
result.port = if (port != defaultPort(scheme)) port else -1
result.encodedPathSegments.clear()
result.encodedPathSegments.addAll(encodedPathSegments())
result.encodedQuery(encodedQuery())
result.encodedFragment = encodedFragment()
result.encodedPathSegments.addAll(encodedPathSegments)
result.encodedQuery(encodedQuery)
result.encodedFragment = encodedFragment
return result
}

Expand Down Expand Up @@ -1365,14 +1365,14 @@ class HttpUrl internal constructor(
}
} else {
// This is a relative link. Copy over all authority components. Also maybe the path & query.
this.encodedUsername = base.encodedUsername()
this.encodedPassword = base.encodedPassword()
this.encodedUsername = base.encodedUsername
this.encodedPassword = base.encodedPassword
this.host = base.host
this.port = base.port
this.encodedPathSegments.clear()
this.encodedPathSegments.addAll(base.encodedPathSegments())
this.encodedPathSegments.addAll(base.encodedPathSegments)
if (pos == limit || input[pos] == '#') {
encodedQuery(base.encodedQuery())
encodedQuery(base.encodedQuery)
}
}

Expand Down
2 changes: 1 addition & 1 deletion okhttp/src/main/java/okhttp3/RealCall.kt
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ internal class RealCall private constructor(
this.callsPerHost = other.callsPerHost
}

fun host(): String = originalRequest.url().host()
fun host(): String = originalRequest.url().host

fun request(): Request = originalRequest

Expand Down
16 changes: 8 additions & 8 deletions okhttp/src/main/java/okhttp3/internal/Util.kt
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,13 @@ fun nonEmptyIntersection(
}

fun hostHeader(url: HttpUrl, includeDefaultPort: Boolean): String {
val host = if (":" in url.host()) {
"[${url.host()}]"
val host = if (":" in url.host) {
"[${url.host}]"
} else {
url.host()
url.host
}
return if (includeDefaultPort || url.port() != HttpUrl.defaultPort(url.scheme())) {
"$host:${url.port()}"
return if (includeDefaultPort || url.port != HttpUrl.defaultPort(url.scheme)) {
"$host:${url.port}"
} else {
host
}
Expand Down Expand Up @@ -288,9 +288,9 @@ fun toHeaderBlock(headers: Headers): List<Header> = (0 until headers.size).map {
}

/** Returns true if an HTTP request for [a] and [b] can reuse a connection. */
fun sameConnection(a: HttpUrl, b: HttpUrl): Boolean = (a.host() == b.host() &&
a.port() == b.port() &&
a.scheme() == b.scheme())
fun sameConnection(a: HttpUrl, b: HttpUrl): Boolean = (a.host == b.host &&
a.port == b.port &&
a.scheme == b.scheme)

fun eventListenerFactory(listener: EventListener): EventListener.Factory =
EventListener.Factory { listener }
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ class CacheStrategy internal constructor(
return if (delta > 0L) delta else 0L
}

if (lastModified != null && cacheResponse.request().url().query() == null) {
if (lastModified != null && cacheResponse.request().url().query == null) {
// As recommended by the HTTP RFC and implemented in Firefox, the max age of a document
// should be defaulted to 10% of the document's age at the time it was served. Default
// expiration dates aren't used for URIs containing a query.
Expand Down
28 changes: 14 additions & 14 deletions okhttp/src/main/java/okhttp3/internal/connection/RealConnection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ class RealConnection(
throw RouteException(UnknownServiceException(
"CLEARTEXT communication not enabled for client"))
}
val host = route.address().url.host()
val host = route.address().url.host
if (!Platform.get().isCleartextTrafficPermitted(host)) {
throw RouteException(UnknownServiceException(
"CLEARTEXT communication to $host not permitted by network security policy"))
Expand Down Expand Up @@ -322,7 +322,7 @@ class RealConnection(
val sink = this.sink!!
socket.soTimeout = 0 // HTTP/2 connection timeouts are set per-stream.
val http2Connection = Http2Connection.Builder(true)
.socket(socket, route.address().url.host(), source, sink)
.socket(socket, route.address().url.host, source, sink)
.listener(this)
.pingIntervalMillis(pingIntervalMillis)
.build()
Expand All @@ -339,12 +339,12 @@ class RealConnection(
try {
// Create the wrapper over the connected socket.
sslSocket = sslSocketFactory!!.createSocket(
rawSocket, address.url.host(), address.url.port(), true /* autoClose */) as SSLSocket
rawSocket, address.url.host, address.url.port, true /* autoClose */) as SSLSocket

// Configure the socket's ciphers, TLS versions, and extensions.
val connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket)
if (connectionSpec.supportsTlsExtensions()) {
Platform.get().configureTlsExtensions(sslSocket, address.url.host(), address.protocols)
Platform.get().configureTlsExtensions(sslSocket, address.url.host, address.protocols)
}

// Force handshake. This can throw!
Expand All @@ -354,24 +354,24 @@ class RealConnection(
val unverifiedHandshake = sslSocketSession.handshake()

// Verify that the socket's certificates are acceptable for the target host.
if (!address.hostnameVerifier!!.verify(address.url.host(), sslSocketSession)) {
if (!address.hostnameVerifier!!.verify(address.url.host, sslSocketSession)) {
val peerCertificates = unverifiedHandshake.peerCertificates
if (peerCertificates.isNotEmpty()) {
val cert = peerCertificates[0] as X509Certificate
throw SSLPeerUnverifiedException("""
|Hostname ${address.url.host()} not verified:
|Hostname ${address.url.host} not verified:
| certificate: ${CertificatePinner.pin(cert)}
| DN: ${cert.subjectDN.name}
| subjectAltNames: ${OkHostnameVerifier.allSubjectAltNames(cert)}
""".trimMargin())
} else {
throw SSLPeerUnverifiedException(
"Hostname ${address.url.host()} not verified (no certificates)")
"Hostname ${address.url.host} not verified (no certificates)")
}
}

// Check that the certificate pinner is satisfied by the certificates presented.
address.certificatePinner!!.check(address.url.host(),
address.certificatePinner!!.check(address.url.host,
unverifiedHandshake.peerCertificates)

// Success! Save the handshake and the ALPN protocol.
Expand Down Expand Up @@ -497,7 +497,7 @@ class RealConnection(
if (!this.route.address().equalsNonHost(address)) return false

// If the host exactly matches, we're done: this connection can carry the address.
if (address.url.host() == this.route().address().url.host()) {
if (address.url.host == this.route().address().url.host) {
return true // This connection is a perfect match.
}

Expand All @@ -518,7 +518,7 @@ class RealConnection(

// 4. Certificate pinning must match the host.
try {
address.certificatePinner!!.check(address.url.host(), handshake()!!.peerCertificates)
address.certificatePinner!!.check(address.url.host, handshake()!!.peerCertificates)
} catch (_: SSLPeerUnverifiedException) {
return false
}
Expand All @@ -543,17 +543,17 @@ class RealConnection(
fun supportsUrl(url: HttpUrl): Boolean {
val routeUrl = route.address().url

if (url.port() != routeUrl.port()) {
if (url.port != routeUrl.port) {
return false // Port mismatch.
}

if (url.host() == routeUrl.host()) {
if (url.host == routeUrl.host) {
return true // Host match. The URL is supported.
}

// We have a host mismatch. But if the certificate matches, we're still good.
return handshake != null && OkHostnameVerifier.verify(
url.host(), handshake!!.peerCertificates[0] as X509Certificate)
url.host, handshake!!.peerCertificates[0] as X509Certificate)
}

@Throws(SocketException::class)
Expand Down Expand Up @@ -690,7 +690,7 @@ class RealConnection(
override fun protocol(): Protocol = protocol!!

override fun toString(): String {
return "Connection{${route.address().url.host()}:${route.address().url.port()}," +
return "Connection{${route.address().url.host}:${route.address().url.port}," +
" proxy=${route.proxy()}" +
" hostAddress=${route.socketAddress()}" +
" cipherSuite=${handshake?.cipherSuite ?: "none"}" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ class RealConnectionPool(
if (failedRoute.proxy().type() != Proxy.Type.DIRECT) {
val address = failedRoute.address()
address.proxySelector.connectFailed(
address.url.uri(), failedRoute.proxy().address(), failure)
address.url.toUri(), failedRoute.proxy().address(), failure)
}

routeDatabase.failed(failedRoute)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class RouteSelector(
listOf(proxy)
} else {
// Try each of the ProxySelector choices until one connection succeeds.
val proxiesOrNull = address.proxySelector.select(url.uri())
val proxiesOrNull = address.proxySelector.select(url.toUri())
if (proxiesOrNull != null && proxiesOrNull.isNotEmpty()) {
proxiesOrNull.toImmutableList()
} else {
Expand All @@ -117,7 +117,7 @@ class RouteSelector(
private fun nextProxy(): Proxy {
if (!hasNextProxy()) {
throw SocketException(
"No route to ${address.url.host()}; exhausted proxy configurations: $proxies")
"No route to ${address.url.host}; exhausted proxy configurations: $proxies")
}
val result = proxies[nextProxyIndex++]
resetNextInetSocketAddress(result)
Expand All @@ -134,8 +134,8 @@ class RouteSelector(
val socketHost: String
val socketPort: Int
if (proxy.type() == Proxy.Type.DIRECT || proxy.type() == Proxy.Type.SOCKS) {
socketHost = address.url.host()
socketPort = address.url.port()
socketHost = address.url.host
socketPort = address.url.port
} else {
val proxyAddress = proxy.address()
require(proxyAddress is InetSocketAddress) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ class Transmitter(
certificatePinner = client.certificatePinner()
}

return Address(url.host(), url.port(), client.dns(), client.socketFactory(),
return Address(url.host, url.port, client.dns(), client.socketFactory(),
sslSocketFactory, hostnameVerifier, certificatePinner, client.proxyAuthenticator(),
client.proxy(), client.protocols(), client.connectionSpecs(), client.proxySelector())
}
Expand Down
Loading

0 comments on commit d01d9f7

Please sign in to comment.