0
# Ktor Utils JVM
1
2
Ktor Utils JVM is a comprehensive utility library for the Ktor asynchronous web framework, providing essential functionality for cryptographic operations, date handling, platform-specific utilities, logging infrastructure, pipeline processing, I/O operations, network address handling, and various collection utilities. It serves as a foundational component for Ktor applications running on the JVM platform.
3
4
## Package Information
5
6
- **Package Name**: ktor-utils-jvm
7
- **Package Type**: maven
8
- **Language**: Kotlin
9
- **Installation**: Add to your Gradle build file:
10
```kotlin
11
implementation("io.ktor:ktor-utils-jvm:3.2.0")
12
```
13
14
## Core Imports
15
16
```kotlin
17
import io.ktor.util.*
18
import io.ktor.util.pipeline.*
19
import io.ktor.util.logging.*
20
import io.ktor.util.date.*
21
import io.ktor.util.collections.*
22
```
23
24
## Basic Usage
25
26
```kotlin
27
import io.ktor.util.*
28
import io.ktor.util.pipeline.*
29
30
// Create attributes for type-safe storage
31
val key = AttributeKey<String>("example")
32
val attributes = Attributes()
33
attributes.put(key, "value")
34
35
// Base64 encoding/decoding
36
val encoded = "Hello World".encodeBase64()
37
val decoded = encoded.decodeBase64String()
38
39
// Pipeline execution
40
val pipeline = Pipeline<String, Unit>()
41
pipeline.execute(Unit, "subject")
42
43
// Network address handling
44
val address = NetworkAddress("localhost", 8080)
45
```
46
47
## Architecture
48
49
Ktor Utils JVM is organized around several key architectural components:
50
51
- **Attributes System**: Type-safe attribute storage with generic keys for storing contextual data across different parts of the application
52
- **Pipeline Framework**: Asynchronous execution pipeline with configurable phases and interceptors for request/response processing
53
- **Cryptographic Utilities**: Thread-safe implementations of common cryptographic operations including hashing, encoding, and nonce generation
54
- **I/O Abstractions**: Efficient I/O handling through NIO and channel-based operations with platform-specific optimizations
55
- **Collection Extensions**: Case-insensitive maps, concurrent collections, and other specialized data structures
56
- **Logging Infrastructure**: Structured logging with multiple levels and lazy evaluation for performance
57
- **Date and Time Handling**: GMT-based date operations with HTTP date format support
58
- **Platform Utilities**: JVM-specific implementations and platform detection capabilities
59
60
## Capabilities
61
62
### Attributes & Type System
63
64
Type-safe attribute storage system for associating typed values with keys across application contexts.
65
66
```kotlin { .api }
67
data class AttributeKey<T : Any>(val name: String, private val type: TypeInfo = typeInfo<Any>())
68
69
interface Attributes {
70
fun <T : Any> get(key: AttributeKey<T>): T
71
fun <T : Any> getOrNull(key: AttributeKey<T>): T?
72
fun <T : Any> put(key: AttributeKey<T>, value: T)
73
fun <T : Any> remove(key: AttributeKey<T>)
74
fun <T : Any> computeIfAbsent(key: AttributeKey<T>, block: () -> T): T
75
val allKeys: List<AttributeKey<*>>
76
}
77
78
fun Attributes(concurrent: Boolean = false): Attributes
79
```
80
81
[Attributes & Type System](./attributes.md)
82
83
### Cryptography & Encoding
84
85
Cryptographic operations, encoding/decoding utilities, and secure random generation.
86
87
```kotlin { .api }
88
fun String.encodeBase64(): String
89
fun ByteArray.encodeBase64(): String
90
fun String.decodeBase64String(): String
91
fun String.decodeBase64Bytes(): ByteArray
92
93
fun hex(bytes: ByteArray): String
94
fun hex(s: String): ByteArray
95
fun sha1(bytes: ByteArray): ByteArray
96
fun generateNonce(): String
97
```
98
99
[Cryptography & Encoding](./crypto.md)
100
101
### String & Text Processing
102
103
String handling utilities including case-insensitive operations and HTML processing.
104
105
```kotlin { .api }
106
interface StringValues {
107
val caseInsensitiveName: Boolean
108
operator fun get(name: String): String?
109
fun getAll(name: String): List<String>?
110
fun names(): Set<String>
111
fun entries(): Set<Map.Entry<String, List<String>>>
112
operator fun contains(name: String): Boolean
113
fun isEmpty(): Boolean
114
}
115
116
interface StringValuesBuilder {
117
operator fun set(name: String, value: String)
118
fun append(name: String, value: String)
119
fun appendAll(stringValues: StringValues)
120
fun remove(name: String)
121
fun build(): StringValues
122
}
123
124
fun valuesOf(vararg pairs: Pair<String, List<String>>, caseInsensitiveKey: Boolean = false): StringValues
125
fun String.escapeHTML(): String
126
```
127
128
[String & Text Processing](./strings.md)
129
130
### Collections & Data Structures
131
132
Specialized collection types including case-insensitive maps, concurrent collections, and caching utilities.
133
134
```kotlin { .api }
135
fun <V> caseInsensitiveMap(): MutableMap<String, V>
136
fun caseInsensitiveSet(): MutableSet<String>
137
138
interface ConcurrentMap<K, V> : MutableMap<K, V>
139
class CopyOnWriteHashMap<K, V> : MutableMap<K, V>
140
class LRUCache<K, V>(val maxSize: Int) : MutableMap<K, V>
141
```
142
143
[Collections & Data Structures](./collections.md)
144
145
### Pipeline System
146
147
Asynchronous execution pipeline with configurable phases for request/response processing.
148
149
```kotlin { .api }
150
open class Pipeline<TSubject : Any, TContext : Any>(vararg phases: PipelinePhase) {
151
val attributes: Attributes
152
val developmentMode: Boolean
153
val isEmpty: Boolean
154
155
suspend fun execute(context: TContext, subject: TSubject): TSubject
156
fun addPhase(phase: PipelinePhase)
157
fun intercept(phase: PipelinePhase, block: PipelineInterceptor<TSubject, TContext>)
158
}
159
160
class PipelinePhase(val name: String)
161
class PipelineContext<TSubject : Any, TContext : Any>
162
163
typealias PipelineInterceptor<TSubject, TContext> = suspend PipelineContext<TSubject, TContext>.(TSubject) -> Unit
164
```
165
166
[Pipeline System](./pipeline.md)
167
168
### I/O & Networking
169
170
Network address handling, file channel operations, and stream adapters for efficient I/O.
171
172
```kotlin { .api }
173
typealias NetworkAddress = java.net.SocketAddress
174
fun NetworkAddress(hostname: String, port: Int): NetworkAddress
175
val NetworkAddress.hostname: String
176
val NetworkAddress.port: Int
177
178
// File channel operations
179
fun File.readChannel(): ByteReadChannel
180
fun File.writeChannel(append: Boolean = false): ByteWriteChannel
181
182
// Stream adapters
183
fun ByteReadChannel.toInputStream(): InputStream
184
fun ByteWriteChannel.toOutputStream(): OutputStream
185
186
// NIO utilities
187
fun ReadableByteChannel.readChannel(): ByteReadChannel
188
fun WritableByteChannel.writeChannel(): ByteWriteChannel
189
```
190
191
[I/O & Networking](./io.md)
192
193
### Data Conversion
194
195
Type conversion service with customizable converters for data transformation.
196
197
```kotlin { .api }
198
interface ConversionService {
199
fun <T> fromValues(values: List<String>, type: TypeInfo): T
200
fun <T> toValues(value: T?): List<String>
201
}
202
203
interface DataConversion {
204
fun <T> convert(value: String, type: TypeInfo): T
205
}
206
```
207
208
[Data Conversion](./conversion.md)
209
210
### Date & Time
211
212
GMT date handling with HTTP date format support and timezone operations.
213
214
```kotlin { .api }
215
class GMTDate(
216
val seconds: Int,
217
val minutes: Int,
218
val hours: Int,
219
val dayOfMonth: Int,
220
val month: Month,
221
val year: Int,
222
val dayOfWeek: WeekDay,
223
val dayOfYear: Int,
224
val timestamp: Long
225
)
226
227
enum class Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }
228
enum class WeekDay { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
229
230
fun GMTDate(timestamp: Long): GMTDate
231
fun GMTDate.toHttpDate(): String
232
fun String.fromHttpDate(): GMTDate
233
```
234
235
[Date & Time](./datetime.md)
236
237
### Logging
238
239
Multi-level logging interface with lazy evaluation for performance optimization.
240
241
```kotlin { .api }
242
interface Logger {
243
fun trace(message: String)
244
fun debug(message: String)
245
fun info(message: String)
246
fun warn(message: String)
247
fun error(message: String)
248
fun error(message: String, exception: Throwable)
249
}
250
251
class KtorSimpleLogger(name: String, val level: LogLevel = LogLevel.INFO) : Logger
252
253
fun KtorSimpleLogger(name: String): Logger
254
```
255
256
[Logging](./logging.md)
257
258
### Compression & Encoding
259
260
Content encoding and compression utilities including GZip and Deflate support.
261
262
```kotlin { .api }
263
interface Encoder {
264
fun encode(source: ByteReadChannel): ByteReadChannel
265
}
266
267
interface Decoder {
268
fun decode(source: ByteReadChannel): ByteReadChannel
269
}
270
271
abstract class ContentEncoder : Encoder {
272
abstract val name: String
273
}
274
275
object GZipEncoder : ContentEncoder
276
object DeflateEncoder : ContentEncoder
277
```
278
279
[Compression & Encoding](./compression.md)
280
281
## Types
282
283
```kotlin { .api }
284
// Type information for reflection
285
class TypeInfo
286
287
inline fun <reified T> typeInfo(): TypeInfo
288
289
// Hash function interface
290
interface HashFunction {
291
fun digest(data: ByteArray): ByteArray
292
}
293
294
// Nonce management
295
interface NonceManager {
296
suspend fun newNonce(): String
297
suspend fun verifyNonce(nonce: String): Boolean
298
}
299
```