-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.kt
72 lines (63 loc) · 2.13 KB
/
Main.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.mediamarktsaturn.techsummit23
import org.apache.hc.core5.http.HttpResponse
import java.io.*
import java.util.Scanner
fun Serializable.toByteArray(): ByteArray {
val byteArrayOutputStream = ByteArrayOutputStream()
var objectOutputStream: ObjectOutputStream? = null
try {
objectOutputStream = ObjectOutputStream(byteArrayOutputStream)
objectOutputStream.writeObject(this)
objectOutputStream.flush()
val result = byteArrayOutputStream.toByteArray()
return result
} finally {
if (objectOutputStream != null) {
objectOutputStream.close()
}
byteArrayOutputStream.close()
}
}
fun handleResponse(response: HttpResponse?): String {
if (response == null) {
throw IllegalStateException("Response is null")
}
val code: Int = response.code
if (code == 200 || code == 201) {
return response.reasonPhrase
}
if (code >= 400 && code <= 499) {
throw IllegalStateException("Server responses with client error")
}
if (code >= 500 && code <= 599) {
throw IllegalStateException("Server responses with server error")
}
throw IllegalStateException("Receive unexpected response code " + code)
}
private const val DELIMITER = "[^a-zA-Z'äöü]+"
fun File.countWord(): MutableMap<String, Int> {
var scanner: Scanner? = null
try {
scanner = Scanner(this)
scanner.useDelimiter(DELIMITER)
val wordCount: MutableMap<String, Int> = mutableMapOf<String, Int>()
while (scanner.hasNext()) {
val word: String = scanner.next()
if (!wordCount.containsKey(word)) {
wordCount.put(word, 1)
} else {
val currentCount = wordCount.get(word)
if (currentCount != null) {
wordCount.put(word, currentCount + 1)
}
}
}
return wordCount
} catch (e: IOException) {
throw IllegalArgumentException("Unable to read the current file ${this.name}!", e)
} finally {
if (scanner != null) {
scanner.close()
}
}
}