Skip to content

Commit

Permalink
Closes eclipse-zenoh#64, Adds parametersMap to Selector.kt
Browse files Browse the repository at this point in the history
Signed-off-by: Giovanni Barbaro <[email protected]>
  • Loading branch information
vanny96 committed May 14, 2024
1 parent c86d975 commit 5b78309
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
16 changes: 15 additions & 1 deletion zenoh-kotlin/src/commonMain/kotlin/io/zenoh/selector/Selector.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package io.zenoh.selector

import io.zenoh.keyexpr.KeyExpr
import java.net.URLDecoder

/**
* A selector is the combination of a [KeyExpr], which defines the
Expand All @@ -27,7 +28,20 @@ import io.zenoh.keyexpr.KeyExpr
* @property keyExpr The [KeyExpr] of the selector.
* @property parameters The parameters of the selector.
*/
class Selector(val keyExpr: KeyExpr, val parameters: String = ""): AutoCloseable {
class Selector(val keyExpr: KeyExpr, val parameters: String = "") : AutoCloseable {

/** Extracts the selector [parameters]' name-value pairs into a map, returning an error in case of duplicated parameters. */
fun parametersStringMap(): Result<Map<String, String>> = runCatching {
parameters.split('&').fold(mapOf()) { parametersMap, parameter ->
val keyValuePair = parameter.split('=')
val key = keyValuePair[0]
if (parametersMap.containsKey(key)) {
throw IllegalArgumentException("Duplicated parameter `$key` detected.")
}
val value = keyValuePair.getOrNull(1)?.let { URLDecoder.decode(it, Charsets.UTF_8.name()) } ?: ""
parametersMap + (key to value)
}
}

override fun toString(): String {
return if (parameters.isEmpty()) "$keyExpr" else "$keyExpr?$parameters"
Expand Down
18 changes: 10 additions & 8 deletions zenoh-kotlin/src/commonTest/kotlin/io/zenoh/GetTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,21 @@ class GetTest {
@Test
fun getWithSelectorParamsTest() {
var receivedParams = String()
val queryable = session.declareQueryable(keyExpr).with {
it.use { query ->
receivedParams = query.parameters
}
}.res().getOrThrow()

val params = "arg1=val1,arg2=val2"
var receivedParamsMap = mapOf<String, String?>()
val queryable = session.declareQueryable(keyExpr).with { it.use { query ->
receivedParams = query.parameters
receivedParamsMap = query.selector.parametersStringMap().getOrThrow()
}}.res().getOrThrow()

val params = "arg1=val1&arg2=val2&arg3"
val paramsMap = mapOf("arg1" to "val1", "arg2" to "val2", "arg3" to "")
val selector = Selector(keyExpr, params)
session.get(selector).with {}.timeout(Duration.ofMillis(1000)).res()
Thread.sleep(1000)

queryable.close()

assertEquals(params, receivedParams)
assertEquals(paramsMap, receivedParamsMap)
}
}

Expand Down

0 comments on commit 5b78309

Please sign in to comment.