# java.lang.RuntimeException when using client in Java API in Kotlin

**URL:** <https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013>\
**Category:** Elasticsearch\
**Tags:** language-clients, runtime-fields\
**Created:** [March 5, 2023, 5:47pm UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013 "2023-03-05T17:47:19Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![GAETANO\_SIMONELLI](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/gaetano_simonelli/32/118044_2.png) [@GAETANO\_SIMONELLI](https://discuss.elastic.co/u/GAETANO_SIMONELLI)\
**Post date:** [March 5, 2023, 5:47pm UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013/1 "2023-03-05T17:47:19Z")

</div>

I am trying to use the Elasticsearch Java API in a Kotlin application, following the official tutorial page ([Connecting | Elasticsearch Java API Client [8.6] | Elastic](https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/connecting.html)). However, I am encountering a `java.lang.RuntimeException` when trying to perform basic actions such as `client.search()` or `client.index()`. I am not sure what is causing the error.

Here is an example from my test application:

```auto
val restClient = RestClient.builder(
                HttpHost("localhost", 9200)
            ).build()

            val transport: ElasticsearchTransport = RestClientTransport(
                restClient, JacksonJsonpMapper()
            )
            val client = ElasticsearchClient(transport)
            di("client ${client.toString()}")

            // create a StringReader object containing a JSON-formatted log message
            val input: Reader = StringReader(
                "{'@timestamp': '2022-04-08T13:55:32Z', 'level': 'warn', 'message': 'Some log message'}"
                    .replace('\'', '"')
            )
            // create an IndexRequest with an index named "logs" and the JSON-formatted log message
            // wrapped in a JsonData object
            val request = IndexRequest.of(
                Function { i: IndexRequest.Builder<JsonData?> ->
                    i
                        .index("logsxe")
                        .withJson(input)
                }
            )
            client.update()
            // execute the index request using the Elasticsearch client and store the response
            val response: IndexResponse = client.index(request)

            // log the version of the newly indexed document
            di("Indexed with version " + response.version())

```

---

<div class="post-metadata">

**Author:** ![swallez](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/swallez/32/11972_2.png) [@swallez](https://discuss.elastic.co/u/swallez)\
**Post date:** [March 5, 2023, 6:08pm UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013/2 "2023-03-05T18:08:08Z")

</div>

`java.lang.RuntimeException` doesn't carry a lot of information to understand what's happening. Can you provide the exception message and stack trace?

---

<div class="post-metadata">

**Author:** ![GAETANO\_SIMONELLI](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/gaetano_simonelli/32/118044_2.png) [@GAETANO\_SIMONELLI](https://discuss.elastic.co/u/GAETANO_SIMONELLI)\
**Post date:** [March 5, 2023, 6:43pm UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013/3 "2023-03-05T18:43:32Z")

</div>

here is the complete message error I get from android studio using debug mode:

```auto
023-03-05 19:41:55.425 9155-9155/com.example.etax E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.etax, PID: 9155
    java.lang.RuntimeException
        at org.elasticsearch.client.RestClient.extractAndWrapCause(RestClient.java:938)
        at org.elasticsearch.client.RestClient.performRequest(RestClient.java:300)
        at org.elasticsearch.client.RestClient.performRequest(RestClient.java:288)
        at co.elastic.clients.transport.rest_client.RestClientTransport.performRequest(RestClientTransport.java:147)
        at co.elastic.clients.elasticsearch.ElasticsearchClient.index(ElasticsearchClient.java:1067)
        at com.example.etax.MainActivity.sendFileStandard(MainActivity.kt:96)
        at com.example.etax.MainActivity.onCreate$lambda-0(MainActivity.kt:39)
        at com.example.etax.MainActivity.$r8$lambda$WxtDuuQ6iwM7qx_huJKFXiJu8fI(Unknown Source:0)
        at com.example.etax.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:7570)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1202)
        at android.view.View.performClickInternal(View.java:7525)
        at android.view.View.access$3900(View.java:836)
        at android.view.View$PerformClick.run(View.java:28680)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:254)
        at android.app.ActivityThread.main(ActivityThread.java:8243)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1605)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
        at java.net.InetAddress.getAllByName(InetAddress.java:1152)
        at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
        at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager$InternalAddressResolver.resolveRemoteAddress(PoolingNHttpClientConnectionManager.java:666)
        at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager$InternalAddressResolver.resolveRemoteAddress(PoolingNHttpClientConnectionManager.java:637)
        at org.apache.http.nio.pool.AbstractNIOConnPool.processPendingRequest(AbstractNIOConnPool.java:474)
        at org.apache.http.nio.pool.AbstractNIOConnPool.lease(AbstractNIOConnPool.java:280)
        at org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager.requestConnection(PoolingNHttpClientConnectionManager.java:295)
        at org.apache.http.impl.nio.client.AbstractClientExchangeHandler.requestConnection(AbstractClientExchangeHandler.java:381)
        at org.apache.http.impl.nio.client.DefaultClientExchangeHandlerImpl.start(DefaultClientExchangeHandlerImpl.java:130)
        at org.apache.http.impl.nio.client.CloseableHttpAsyncClientBase.execute(CloseableHttpAsyncClientBase.java:116)
        at org.apache.http.impl.nio.client.InternalHttpAsyncClient.execute(InternalHttpAsyncClient.java:138)
        at org.elasticsearch.client.RestClient.performRequest(RestClient.java:296)

```

---

<div class="post-metadata">

**Author:** ![swallez](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/swallez/32/11972_2.png) [@swallez](https://discuss.elastic.co/u/swallez)\
**Post date:** [March 5, 2023, 7:27pm UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013/4 "2023-03-05T19:27:45Z")

</div>

`Caused by: android.os.NetworkOnMainThreadException`

On Android making network calls on the main thread that handles the UI is forbidden as it can make the application unresponsive ([see docs](https://developer.android.com/reference/android/os/NetworkOnMainThreadException)).

You should do these calls from another thread, or use the async version `RestClient.performRequestAsync()`.

---

<div class="post-metadata">

**Author:** ![GAETANO\_SIMONELLI](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/gaetano_simonelli/32/118044_2.png) [@GAETANO\_SIMONELLI](https://discuss.elastic.co/u/GAETANO_SIMONELLI)\
**Post date:** [March 5, 2023, 7:42pm UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013/5 "2023-03-05T19:42:29Z")

</div>

Thank you for your help, really appreciated. Would you please link me the official guide/info page about the asynchronous call so I can start to work on it?

---

<div class="post-metadata">

**Author:** ![swallez](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/swallez/32/11972_2.png) [@swallez](https://discuss.elastic.co/u/swallez)\
**Post date:** [March 6, 2023, 8:49am UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013/6 "2023-03-06T08:49:20Z")

</div>

> **[Performing requests | Elasticsearch Java API Client \[8.7\] | Elastic](https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/8.7/java-rest-low-usage-requests.html)**

---

<div class="post-metadata">

**Author:** ![GAETANO\_SIMONELLI](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/gaetano_simonelli/32/118044_2.png) [@GAETANO\_SIMONELLI](https://discuss.elastic.co/u/GAETANO_SIMONELLI)\
**Post date:** [March 6, 2023, 1:05pm UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013/8 "2023-03-06T13:05:38Z")

</div>

Unfortunately I get onFailure: java.util.concurrent.CancellationException: Request execution cancelled or if i delete the restclient.close() instruction my app just block (I suppose waiting for the request to be performed).  
I would like to add that while i performed this operations both elasticsearch and kibana was running on my pc  
So i add a waiting instruction and i get a java.net.connectException:connection refused error

```auto
private fun sendFileStandard() {
    val restClient = RestClient.builder(
        HttpHost("localhost", 9200, "http"),
        HttpHost("localhost", 9201, "http")
    ).build()

    val request = Request(
        "GET",
        "/"
    )

    var risultato = "default value"

    doAsync {
        val cancellable: Cancellable = restClient.performRequestAsync(request,
            object : ResponseListener {
                override fun onSuccess(response: Response) {
                    risultato = "success" + response.toString()
                }

                override fun onFailure(exception: Exception) {
                    risultato = "exception" + exception.toString()
                }
            })
    }
    println("risultato: $risultato")
}

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [April 3, 2023, 1:06pm UTC](https://discuss.elastic.co/t/java-lang-runtimeexception-when-using-client-in-java-api-in-kotlin/327013/9 "2023-04-03T13:06:01Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
