scoop:scoop.http.server:0.1.0
src/cookies.scoop
Selected production source · src/cookies.scoop
1
package scoop.http.server3
import scoop.http.*4
import scoop.text.startsWith6
/** Lazily parsed cookies retaining all duplicate values in arrival order. */7
public class RequestCookies internal constructor(private val fields: Array<HttpField>) {8
private val lock: ServerLock = ServerLock()9
private var parsed: HttpCookieHeader? = None11
private fun values(): HttpCookieHeader = lock.withLock {12
if (!present(parsed)) {13
try { parsed = Some(HttpCookieHeader.parseFields(fields)) }14
catch (_: HttpFieldParseException) { reject(400U, "invalid Cookie field") }15
}16
parsed!!17
}19
/** Returns all exact-name matches without decoding their value bytes. */20
public fun getAllBytes(name: String): Array<Array<Byte>> {21
val bytes = name.toByteArray()22
val result = ArrayList<Array<Byte>>()23
for (pair in values().pairs) if (sameBytes(pair.name, bytes)) result.add(pair.value)24
return result.toArray()25
}27
/** Reads a unique cookie, rejecting ambiguous duplicate values. */28
public fun getSingleBytes(name: String): Array<Byte>? {29
val all = getAllBytes(name)30
if (all.size > 1L) reject(400U, "duplicate Cookie: " + name)31
return if (all.size == 0L) None else Some(all[0L])32
}34
/** Strictly decodes all matching cookie values as UTF-8. */35
public fun getAll(name: String): Array<String> {36
val result = ArrayList<String>()37
for (value in getAllBytes(name)) result.add(inputText(value, "Cookie " + name))38
return result.toArray()39
}41
/** Returns one UTF-8 value or None; duplicates are a request rejection. */42
public fun getSingle(name: String): String? = when (getSingleBytes(name)) {43
case None -> None44
case Some(val value) -> Some(inputText(value, "Cookie " + name))45
}46
}48
/** Response-only cookie operations using the existing HTTP cookie model. */49
public class ResponseCookies internal constructor(private val response: HttpResponse) {50
/** Appends one independent Set-Cookie field. */51
public fun append(cookie: HttpSetCookie) { response.add(cookie.toHttpField()) }53
/** Expires the explicitly selected name, path and optional domain. */54
public fun delete(name: String, path: String, domain: String?) {55
if (!path.startsWith("/")) throw IllegalArgumentException(Some("cookie deletion requires an absolute path"))56
val attributes = ArrayList<HttpCookieAttribute>()57
attributes.add(HttpCookieAttribute("Path", path))58
if (present(domain)) attributes.add(HttpCookieAttribute("Domain", domain!!))59
attributes.add(HttpCookieAttribute("Max-Age", "0"))60
attributes.add(HttpCookieAttribute("Expires", "Thu, 01 Jan 1970 00:00:00 GMT"))61
append(HttpSetCookie(HttpCookiePair(name, ""), attributes))62
}63
}