main.name.remal.gradle_plugins.utils.newRetrofitBuilder.kt Maven / Gradle / Ivy
package name.remal.gradle_plugins.utils
import name.remal.gradle_plugins.dsl.DEFAULT_IO_TIMEOUT
import name.remal.gradle_plugins.dsl.utils.getGradleLogger
import name.remal.isKotlinClass
import name.remal.uncheckedCast
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level.BODY
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.Type
import java.util.Optional
import java.util.concurrent.TimeUnit.MILLISECONDS
private val logger = getGradleLogger(Retrofit::class.java)
fun newRetrofitBuilder(httpClientConfigurer: (httpClientBuilder: OkHttpClient.Builder) -> OkHttpClient.Builder = { it }): Retrofit.Builder {
val client = httpClientConfigurer(
OkHttpClient.Builder()
.connectTimeout(DEFAULT_IO_TIMEOUT.toMillis(), MILLISECONDS)
.writeTimeout(DEFAULT_IO_TIMEOUT.toMillis(), MILLISECONDS)
.readTimeout(DEFAULT_IO_TIMEOUT.toMillis(), MILLISECONDS)
.addInterceptor(HttpLoggingInterceptor { logger.info("{}", it) }.setLevel(BODY))
).build()
return Retrofit.Builder()
.client(client)
.addCallAdapterFactory(object : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array, retrofit: Retrofit): CallAdapter<*, *>? {
if (Optional::class.java.isAssignableFrom(getRawType(returnType))) {
return object : CallAdapter {
override fun responseType() = returnType
override fun adapt(call: Call) = call.execute().let { response ->
if (response.isSuccessful) {
return@let response.body()
} else if (404 == response.code()) {
return@let Optional.empty()
} else {
throw call.createCallException(response)
}
}
}
}
return null
}
})
.addCallAdapterFactory(object : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array, retrofit: Retrofit): CallAdapter<*, *>? {
if (Collection::class.java.isAssignableFrom(getRawType(returnType)) || Map::class.java.isAssignableFrom(getRawType(returnType))) {
return object : CallAdapter {
override fun responseType() = returnType
override fun adapt(call: Call) = call.uncheckedCast>().fetchBody()
}
}
return null
}
})
.addCallAdapterFactory(object : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array, retrofit: Retrofit): CallAdapter<*, *>? {
if (getRawType(returnType).isKotlinClass) {
return object : CallAdapter {
override fun responseType() = returnType
override fun adapt(call: Call) = call.uncheckedCast>().fetchBody()
}
}
return null
}
})
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy