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

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). 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:

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())

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

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

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)

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).

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

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?

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

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")
}

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