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
  • Loading branch information
vanny96 committed Apr 6, 2024
1 parent cea579b commit 6f3106e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ class Query internal constructor(
/** Shortcut to the [selector]'s parameters. */
val parameters = selector.parameters

val parametersMap = selector.parametersMap

/**
* Reply to the specified key expression.
*
Expand Down
21 changes: 20 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,25 @@ 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 {

val parametersMap = deserializeParametersToMap()

private fun deserializeParametersToMap(): Map<String, String?> {
val keyValuePairs = parameters.split('&').map { parameter ->
if (parameter.contains('=')) {
parameter.split('=').let { it[0] to URLDecoder.decode(it[1], Charsets.UTF_8) }
} else {
parameter to null
}
}
validateParameters(keyValuePairs)
return keyValuePairs.toMap()
}

private fun validateParameters(keyValuePairs: List<Pair<String, String?>>) = keyValuePairs
.groupBy({ it.first }, { it.second })
.forEach { (name, values) -> if (values.size > 1) throw Exception("Duplicated parameter $name detected") }

override fun toString(): String {
return if (parameters.isEmpty()) "$keyExpr" else "$keyExpr?$parameters"
Expand Down
4 changes: 4 additions & 0 deletions zenoh-kotlin/src/commonTest/kotlin/io/zenoh/GetTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -79,19 +79,23 @@ class GetTest {
val session = Session.open().getOrThrow()

var receivedParams = ""
var receivedParamsMap = mapOf<String, String?>()
val keyExpr = TEST_KEY_EXP.intoKeyExpr().getOrThrow()
val queryable = session.declareQueryable(keyExpr).with { it.use { query ->
receivedParams = query.parameters
receivedParamsMap = query.parametersMap
}}.res().getOrThrow()

val params = "arg1=val1,arg2=val2"
val paramsMap = mapOf("arg1" to "val1", "arg2" to "val2")
val selector = Selector(keyExpr, params)
session.get(selector).res()

queryable.close()
session.close()

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

@Test
Expand Down

0 comments on commit 6f3106e

Please sign in to comment.