All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tryfinch.api.client.okhttp.OkHttpClient.kt Maven / Gradle / Ivy

Go to download

The Finch HRIS API provides a unified way to connect to a multitide of HRIS systems. The API requires an access token issued by Finch. By default, Organization and Payroll requests use Finch's [Data Syncs](/developer-resources/Data-Syncs). If a request is made before the initial sync has completed, Finch will request data live from the provider. The latency on live requests may range from seconds to minutes depending on the provider and batch size. For automated integrations, Deductions requests (both read and write) are always made live to the provider. Latencies may range from seconds to minutes depending on the provider and batch size. Employer products are specified by the product parameter, a space-separated list of products that your application requests from an employer authenticating through Finch Connect. Valid product names are— - `company`: Read basic company data - `directory`: Read company directory and organization structure - `individual`: Read individual data, excluding income and employment data - `employment`: Read individual employment and income data - `payment`: Read payroll and contractor related payments by the company - `pay_statement`: Read detailed pay statements for each individual - `benefits`: Create and manage deductions and contributions and enrollment for an employer [![Open in Postman](https://run.pstmn.io/button.svg)](https://god.gw.postman.com/run-collection/21027137-08db0929-883d-4094-a9ce-dbf5a9bee4a4?action=collection%2Ffork&collection-url=entityId%3D21027137-08db0929-883d-4094-a9ce-dbf5a9bee4a4%26entityType%3Dcollection%26workspaceId%3D1edf19bc-e0a8-41e9-ac55-481a4b50790b)

There is a newer version: 1.11.1
Show newest version
package com.tryfinch.api.client.okhttp

import com.google.common.collect.ListMultimap
import com.google.common.collect.MultimapBuilder
import com.tryfinch.api.core.RequestOptions
import com.tryfinch.api.core.http.HttpClient
import com.tryfinch.api.core.http.HttpMethod
import com.tryfinch.api.core.http.HttpRequest
import com.tryfinch.api.core.http.HttpRequestBody
import com.tryfinch.api.core.http.HttpResponse
import com.tryfinch.api.errors.FinchIoException
import java.io.IOException
import java.io.InputStream
import java.net.Proxy
import java.time.Duration
import java.util.concurrent.CompletableFuture
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.BufferedSink

class OkHttpClient
private constructor(private val okHttpClient: okhttp3.OkHttpClient, private val baseUrl: HttpUrl) :
    HttpClient {

    private fun getClient(requestOptions: RequestOptions): okhttp3.OkHttpClient {
        val timeout = requestOptions.timeout ?: return okHttpClient
        return okHttpClient
            .newBuilder()
            .connectTimeout(timeout)
            .readTimeout(timeout)
            .writeTimeout(timeout)
            .callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30))
            .build()
    }

    override fun execute(
        request: HttpRequest,
        requestOptions: RequestOptions,
    ): HttpResponse {
        val call = getClient(requestOptions).newCall(request.toRequest())

        return try {
            call.execute().toResponse()
        } catch (e: IOException) {
            throw FinchIoException("Request failed", e)
        } finally {
            request.body?.close()
        }
    }

    override fun executeAsync(
        request: HttpRequest,
        requestOptions: RequestOptions,
    ): CompletableFuture {
        val future = CompletableFuture()

        request.body?.run { future.whenComplete { _, _ -> close() } }

        val call = getClient(requestOptions).newCall(request.toRequest())

        call.enqueue(
            object : Callback {
                override fun onResponse(call: Call, response: Response) {
                    future.complete(response.toResponse())
                }

                override fun onFailure(call: Call, e: IOException) {
                    future.completeExceptionally(FinchIoException("Request failed", e))
                }
            }
        )

        return future
    }

    override fun close() {
        okHttpClient.dispatcher.executorService.shutdown()
        okHttpClient.connectionPool.evictAll()
        okHttpClient.cache?.close()
    }

    private fun HttpRequest.toRequest(): Request {
        var body: RequestBody? = body?.toRequestBody()
        // OkHttpClient always requires a request body for PUT and POST methods
        if (body == null && (method == HttpMethod.PUT || method == HttpMethod.POST)) {
            body = "".toRequestBody()
        }

        val builder = Request.Builder().url(toUrl()).method(method.name, body)
        headers.forEach(builder::header)

        return builder.build()
    }

    private fun HttpRequest.toUrl(): String {
        url?.let {
            return it
        }

        val builder = baseUrl.newBuilder()
        pathSegments.forEach(builder::addPathSegment)
        queryParams.forEach(builder::addQueryParameter)

        return builder.toString()
    }

    private fun HttpRequestBody.toRequestBody(): RequestBody {
        val mediaType = contentType()?.toMediaType()
        val length = contentLength()

        return object : RequestBody() {
            override fun contentType(): MediaType? {
                return mediaType
            }

            override fun contentLength(): Long {
                return length
            }

            override fun isOneShot(): Boolean {
                return !repeatable()
            }

            override fun writeTo(sink: BufferedSink) {
                writeTo(sink.outputStream())
            }
        }
    }

    private fun Response.toResponse(): HttpResponse {
        val headers = headers.toHeaders()

        return object : HttpResponse {
            override fun statusCode(): Int {
                return code
            }

            override fun headers(): ListMultimap {
                return headers
            }

            override fun body(): InputStream {
                return body!!.byteStream()
            }

            override fun close() {
                body!!.close()
            }
        }
    }

    private fun Headers.toHeaders(): ListMultimap {
        val headers =
            MultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER)
                .arrayListValues()
                .build()

        forEach { pair -> headers.put(pair.first, pair.second) }

        return headers
    }

    companion object {
        @JvmStatic fun builder() = Builder()
    }

    class Builder {

        private var baseUrl: HttpUrl? = null
        // default timeout is 1 minute
        private var timeout: Duration = Duration.ofSeconds(60)
        private var proxy: Proxy? = null

        fun baseUrl(baseUrl: String) = apply { this.baseUrl = baseUrl.toHttpUrl() }

        fun timeout(timeout: Duration) = apply { this.timeout = timeout }

        fun proxy(proxy: Proxy?) = apply { this.proxy = proxy }

        fun build(): OkHttpClient {
            return OkHttpClient(
                okhttp3.OkHttpClient.Builder()
                    .connectTimeout(timeout)
                    .readTimeout(timeout)
                    .writeTimeout(timeout)
                    .callTimeout(if (timeout.seconds == 0L) timeout else timeout.plusSeconds(30))
                    .proxy(proxy)
                    .build(),
                checkNotNull(baseUrl) { "`baseUrl` is required but was not set" },
            )
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy