Skip to content

Commit

Permalink
Merge pull request #624 from hexagonkt/develop
Browse files Browse the repository at this point in the history
Minor fixes
  • Loading branch information
jaguililla authored May 2, 2023
2 parents 3ab8b5f + a5ebce9 commit c9a2820
Show file tree
Hide file tree
Showing 13 changed files with 80 additions and 41 deletions.
28 changes: 23 additions & 5 deletions core/src/main/kotlin/com/hexagonkt/core/Jvm.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import kotlin.reflect.KClass
* Object with utilities to gather information about the running JVM.
*/
object Jvm {
private val runtime: Runtime by lazy { Runtime.getRuntime() }

/** Default timezone. */
val timeZone: TimeZone by lazy { TimeZone.getDefault() }

Expand All @@ -30,22 +32,38 @@ object Jvm {
val ip: String by lazy { InetAddress.getLocalHost().hostAddress }

/** Name of the JVM running this program. For example: OpenJDK 64-Bit Server VM. */
val name: String by lazy { System.getProperty("java.vm.name") }
val name: String by lazy { System.getProperty("java.vm.name", "N/A") }

/** Java version aka language level. For example: 11 */
val version: String by lazy { System.getProperty("java.vm.specification.version") }
val version: String by lazy { System.getProperty("java.vm.specification.version", "N/A") }

/** Number of processors available to the Java virtual machine. */
val cpuCount: Int by lazy { Runtime.getRuntime().availableProcessors() }
val cpuCount: Int by lazy { runtime.availableProcessors() }

/** User Time Zone property. Can be set with -D user.timezone=<tz> JVM argument. */
val timezone: String by lazy { System.getProperty("user.timezone") }
val timezone: String by lazy { System.getProperty("user.timezone", "N/A") }

/** User locale consist of 2-letter language code, 2-letter country code and file encoding. */
val localeCode: String by lazy {
"%s_%s.%s".format(locale.language, locale.country, charset.name())
}

/**
* Amount of memory in kilobytes available to the JVM.
*
* @return Total amount of memory in kilobytes.
*/
fun totalMemory(): String =
runtime.totalMemory().let { "%,d".format(it / 1024) }

/**
* Amount of used memory in kilobytes.
*
* @return Used memory in kilobytes.
*/
fun usedMemory(): String =
(runtime.totalMemory() - runtime.freeMemory()).let { "%,d".format(it / 1024) }

/**
* Retrieve a setting by name by looking in the JVM system properties first and in OS
* environment variables if not found.
Expand Down Expand Up @@ -90,6 +108,6 @@ object Jvm {

private fun systemSettingRaw(name: String): String? {
require(name.isNotBlank()) { "Setting name can not be blank" }
return System.getProperty(name) ?: System.getenv(name)
return System.getProperty(name, System.getenv(name))
}
}
6 changes: 6 additions & 0 deletions core/src/test/kotlin/com/hexagonkt/core/JvmTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ internal class JvmTest {
assert(Inet4Address.getAllByName(Jvm.ip).isNotEmpty())
}

@Test fun `JVM metrics have valid values` () {
val numberRegex = Regex("[\\d.,]+")
assert(Jvm.totalMemory().matches(numberRegex))
assert(Jvm.usedMemory().matches(numberRegex))
}

@Test fun `Locale code matches with default locale` () {
assert(Jvm.localeCode.contains(Jvm.locale.country))
assert(Jvm.localeCode.contains(Jvm.locale.language))
Expand Down
8 changes: 4 additions & 4 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ org.gradle.warning.mode=all
org.gradle.console=plain

# Gradle
version=2.8.2
version=2.8.3
group=com.hexagonkt
description=The atoms of your platform

Expand Down Expand Up @@ -39,7 +39,7 @@ mockkVersion=1.13.5
junitVersion=5.9.3
gatlingVersion=3.9.3
jmhVersion=1.36
mkdocsMaterialVersion=9.1.8
mkdocsMaterialVersion=9.1.9
mermaidDokkaVersion=0.4.4
nativeToolsVersion=0.9.21

Expand All @@ -48,7 +48,7 @@ servletVersion=5.0.0
jettyVersion=11.0.15

# http_server_netty
nettyVersion=4.1.91.Final
nettyVersion=4.1.92.Final
nettyTcNativeVersion=2.0.60.Final

# logging
Expand All @@ -63,7 +63,7 @@ dslJsonVersion=1.10.0
freemarkerVersion=2.3.32

# templates_pebble
pebbleVersion=3.2.0
pebbleVersion=3.2.1

# templates_rocker
rockerVersion=1.3.0
Original file line number Diff line number Diff line change
Expand Up @@ -170,14 +170,15 @@ open class JettyClientAdapter : HttpClientPort {
val settings = adapterHttpClient.settings
val contentType = request.contentType ?: settings.contentType
val authorization = request.authorization ?: settings.authorization
val baseUrl = settings.baseUrl

if (settings.useCookies) {
val uri = (adapterHttpClient.settings.baseUrl ?: request.url()).toURI()
val uri = (baseUrl ?: request.url()).toURI()
addCookies(uri, adapterJettyClient.cookieStore, request.cookies)
}

val jettyRequest = adapterJettyClient
.newRequest(URI(settings.baseUrl.toString() + request.path))
.newRequest(URI((baseUrl?.toString() ?: "") + request.path))
.method(HttpMethod.valueOf(request.method.toString()))
.headers {
it.remove("accept-encoding") // Don't send encoding by default
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import com.hexagonkt.core.Ansi.DEFAULT
import com.hexagonkt.core.Ansi.MAGENTA
import com.hexagonkt.core.Ansi.RESET
import com.hexagonkt.core.Ansi.UNDERLINE
import com.hexagonkt.core.Jvm.totalMemory
import com.hexagonkt.core.Jvm.usedMemory
import com.hexagonkt.core.prependIndent
import com.hexagonkt.http.server.HttpServerFeature.ZIP
import com.hexagonkt.http.handlers.HttpHandler
Expand Down Expand Up @@ -127,7 +129,7 @@ data class HttpServer(
)

adapter.startUp(this)
logger.info { "Server started\n${createBanner(nanoTime() - startTimestamp)}" }
logger.info { "Server started${createBanner(nanoTime() - startTimestamp)}" }
}

/**
Expand All @@ -146,7 +148,10 @@ data class HttpServer(
val hostName = if (bindAddress.isAnyLocalAddress) ip else bindAddress.canonicalHostName
val scheme = if (protocol == HTTP) "http" else "https"
val binding = "$scheme://$hostName:$runtimePort"
val banner = settings.banner ?: return " at $binding ($startUpTime ms)"

val jvmMemoryValue = "$BLUE${totalMemory()} KB$RESET"
val usedMemoryValue = "$BOLD$MAGENTA${usedMemory()} KB$RESET"
val serverAdapterValue = "$BOLD$CYAN$portName$RESET"

val protocols = adapter.supportedProtocols()
Expand Down Expand Up @@ -180,16 +185,16 @@ data class HttpServer(
Supported Features: $features
Configuration Options: $options
🖥️️ Running in '$hostnameValue' with $cpuCountValue CPUs
🖥️️ Running in '$hostnameValue' with $cpuCountValue CPUs $jvmMemoryValue of memory
🛠 Using $javaVersionValue
🌍 Locale: $localeValue Timezone: $timezoneValue Charset: $charsetValue
⏱️ Started in $startUpTimeValue (excluding VM)
⏱️ Started in $startUpTimeValue (excluding VM) using $usedMemoryValue
🚀 Served at $bindingValue${if (protocol == HTTP2) " (HTTP/2)" else "" }
"""

val banner = (settings.banner?.let { "$it\n" } ?: banner) + information.trimIndent()
return banner.prependIndent()
val fullBanner = banner + information.trimIndent()
return "\n" + fullBanner.prependIndent()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ data class HttpServerSettings(
val contextPath: String = "",
val protocol: HttpProtocol = HTTP,
val sslSettings: SslSettings? = null,
val banner: String? = null,
val banner: String? = HttpServer.banner,
val zip: Boolean = false,
)
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ internal class HttpServerSettingsTest {
assertEquals(2010, it.bindPort)
assertEquals(HTTP, it.protocol)
assertNull(it.sslSettings)
assertNull(it.banner)
assertEquals(HttpServer.banner, it.banner)
assertEquals(false, it.zip)
}
}
Expand All @@ -25,7 +25,7 @@ internal class HttpServerSettingsTest {
assertEquals(2010, it.bindPort)
assertEquals(HTTP, it.protocol)
assertNull(it.sslSettings)
assertNull(it.banner)
assertEquals(HttpServer.banner, it.banner)
assertEquals(true, it.zip)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@ internal class HttpServerTest {
assertEquals(12345, server.runtimePort)
}

@Test fun `Server without banner creation`() {
val serverSettings = HttpServerSettings(
address("localhost"),
12345,
banner = null,
)

val s = serve(VoidAdapter, serverSettings) {}
s.createBanner(System.currentTimeMillis()).let {
assert(it.startsWith(" at"))
assert(it.contains(" ms)"))
assert(!it.contains("✅HTTP"))
assert(!it.contains("HTTPS"))
assert(!it.contains("(excluding VM)"))
}
}

@Test fun `Banner creation`() {
val bannerPrefix = "Test Banner"
val serverSettings = HttpServerSettings(
Expand All @@ -47,21 +64,15 @@ internal class HttpServerTest {
banner = bannerPrefix,
)

val banners = listOf(
serve(VoidAdapter, serverSettings) {},
)
.map {
it.createBanner(System.currentTimeMillis())
}
.map {
assertEquals(bannerPrefix, it.lines()[0].trimIndent())
val s = serve(VoidAdapter, serverSettings) {}
s.createBanner(System.currentTimeMillis()).let {
assertEquals(bannerPrefix, it.lines()[1].trimIndent())
assertContains(it, "✅HTTP" )
assertContains(it, "HTTPS")
assertFalse(it.contains("ZIP"))
assertFalse(it.contains("✅HTTPS"))
it
assertContains(it, "(excluding VM)")
}
assertContains(banners.first(), "(excluding VM)")
}

@Test fun `Banner creation with enabled features and custom options`() {
Expand Down
9 changes: 0 additions & 9 deletions http_server_netty/src/main/kotlin/module-info.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ class ServletFilter(
"""'$filterName' Servlet filter initialized.
| * Context path: ${filterConfig.servletContext.contextPath}
| * Parameters: $parameterNames
| * Server settings: $serverSettings
""".trimMargin()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ class BenchmarkSimulation: Simulation() {
private val http = HttpDsl.http.baseUrl("$protocol://$host:$port")
private val population = CoreDsl.rampUsers(users).during(5)

private val getBooks = CoreDsl.repeat(times).on(CoreDsl.exec(HttpDsl.http("get /a/books").get("/a/books")))
private val getBooks =
CoreDsl.repeat(times).on(CoreDsl.exec(HttpDsl.http("get /a/books").get("/a/books")))

private val scenario = CoreDsl.scenario("Get Books").exec(getBooks)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@ abstract class ClientTest(
assertEquals("qp=qpValue", getResponse.headers["query-parameters"]?.value)
assertEquals("qp=qpValue", response.headers["query-parameters"]?.value)
checkResponse(response, mapOf("body" to "payload"))

val base = client.settings.baseUrl?.toString()
HttpClient(clientAdapter(), client.settings.copy(baseUrl = null)).request {
val secondResponse = get("$base/queryParameters?qp=qpValue")
assertEquals("qp=qpValue", secondResponse.headers["query-parameters"]?.value)
}
}

@Test fun `HTTP methods without body work ok`() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ fun main() {
internal class HelloWorldTest {

private val client: HttpClient by lazy {
HttpClient(JettyClientAdapter(), HttpClientSettings(URL("http://localhost:${server.runtimePort}")))
val settings = HttpClientSettings(URL("http://localhost:${server.runtimePort}"))
HttpClient(JettyClientAdapter(), settings)
}

@BeforeAll fun initialize() {
Expand Down

0 comments on commit c9a2820

Please sign in to comment.