0
\$\begingroup\$

I needed to create a simple CLI utility to check if a specific endpoint is available and (optionally) responds with some expected HTTP code to help troubleshoot users environments (proxy, network restrictions, etc). Here's the code:

import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import java.net.UnknownHostException
import kotlin.system.exitProcess

fun main(args: Array<String>) {
    try {
        require(args.size in 1..2)

        val url = URL(args[0])
        val expectedStatus = try {
            args[1].toInt()
        } catch (e: ArrayIndexOutOfBoundsException) {
            null
        }

        with(url.openConnection() as HttpURLConnection) {
            connectTimeout = 5000
            readTimeout = 5000
            requestMethod = "HEAD"

            val actualStatus = responseCode
            expectedStatus?.let {
                assert(expectedStatus == actualStatus) {
                    "expected HTTP status $expectedStatus, got $actualStatus"
                }
            }
        }
    } catch (e: Throwable) {
        when (e) {
            is IllegalArgumentException,
            is MalformedURLException -> usage()
            is UnknownHostException -> die("IP address of a host could not be determined")
            else -> die("${e.message}")
        }
    }
    println("OK")
}

fun die(message: String) {
    System.err.println(message)
    exitProcess(1)
}

fun usage() {
    die("Usage: java -jar healthchek.jar URL [STATUS]")
}

I'm new to Kotlin and have less experience with JVM, so I'd really appreciate any feedback and review!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.