Skip to content

Commit 90c9b7b

Browse files
Merge pull request #16 from icerockdev/task/WD-306
WD-306 Optimize utils with boilerplate
2 parents 13f9af7 + 5b8f111 commit 90c9b7b

File tree

10 files changed

+129
-87
lines changed

10 files changed

+129
-87
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ repositories {
1212
}
1313

1414
// Append dependency
15-
implementation("com.icerockdev:web-utils:0.4.0")
15+
implementation("com.icerockdev:web-utils:0.5.0")
1616
````
1717

1818
## Library usage

sample/src/main/kotlin/com/icerockdev/sample/server.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ import com.icerockdev.api.Request
1010
import com.icerockdev.exception.ForbiddenException
1111
import com.icerockdev.exception.ServerErrorException
1212
import com.icerockdev.exception.ValidationException
13-
import com.icerockdev.util.QueryParser
14-
import com.icerockdev.util.receiveQuery
13+
import com.icerockdev.api.request.QueryParser
14+
import com.icerockdev.api.request.receiveQuery
1515
import com.icerockdev.webserver.*
1616
import com.icerockdev.webserver.log.JsonDataLogger
1717
import com.icerockdev.webserver.log.JsonSecret

web-utils/build.gradle.kts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ apply(plugin = "java")
1313
apply(plugin = "kotlin")
1414

1515
group = "com.icerockdev"
16-
version = "0.4.0"
16+
version = "0.5.0"
1717

1818
val sourcesJar by tasks.registering(Jar::class) {
1919
classifier = "sources"
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
3+
*/
4+
5+
package com.icerockdev.api.request
6+
7+
import io.ktor.application.ApplicationCall
8+
9+
class Pagination(
10+
val limit: Int = 10,
11+
val offset: Int = 0,
12+
val sortBy: String = "id",
13+
val orderBy: String = "DESC"
14+
)
15+
16+
fun ApplicationCall.getRequestPagination(
17+
limit: Int = 10,
18+
offset: Int = 0,
19+
sortBy: String = "id",
20+
orderBy: String = "DESC"
21+
): Pagination {
22+
return Pagination(
23+
limit = this.parameters["limit"]?.toInt() ?: limit,
24+
offset = this.parameters["offset"]?.toInt() ?: offset,
25+
sortBy = this.parameters["sortBy"] ?: sortBy,
26+
orderBy = this.parameters["orderBy"] ?: orderBy
27+
)
28+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.icerockdev.api.request
2+
3+
import io.ktor.http.Parameters
4+
5+
fun Parameters.parseFilters(): HashMap<String, String> {
6+
val parameters = this
7+
val filters: HashMap<String, String> = hashMapOf()
8+
parameters.entries().forEach {
9+
if (it.key.contains("filters.")) {
10+
val key = it.key.substringAfter(".").toUpperCase()
11+
val value = parameters[it.key]
12+
13+
if (value != null) {
14+
filters[key] = value
15+
}
16+
}
17+
}
18+
19+
return filters
20+
}

web-utils/src/main/kotlin/com/icerockdev/util/QueryParser.kt renamed to web-utils/src/main/kotlin/com/icerockdev/api/request/QueryParser.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
33
*/
44

5-
package com.icerockdev.util
5+
package com.icerockdev.api.request
66

77
import com.fasterxml.jackson.databind.ObjectMapper
88
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
@@ -90,4 +90,4 @@ inline fun <reified T> ApplicationCall.receiveQueryOrNull(): T? {
9090
} catch (e : IllegalArgumentException) {
9191
null
9292
}
93-
}
93+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.icerockdev.util
2+
3+
import org.slf4j.LoggerFactory
4+
import java.net.InetSocketAddress
5+
import java.net.Socket
6+
7+
object CheckNetwork {
8+
private val logger = LoggerFactory.getLogger(CheckNetwork::class.java)
9+
10+
fun isTcpPortAvailable(host: String, port: Int, timeoutMs: Int): Boolean {
11+
return try {
12+
Socket().use { socket ->
13+
socket.reuseAddress = true;
14+
socket.connect(InetSocketAddress(host, port), timeoutMs)
15+
}
16+
true
17+
} catch (ex: Exception) {
18+
false
19+
}
20+
}
21+
22+
fun awaitService(host: String, port: Int, checkIntervalMs: Long = 1000L) {
23+
logger.info("Await connection. Host: $host, Port: $port")
24+
while (!isTcpPortAvailable(host, port, 1000)) {
25+
Thread.sleep(checkIntervalMs)
26+
}
27+
logger.info("Connection ready. Host: $host, Port: $port")
28+
}
29+
}
30+
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.icerockdev.util
2+
3+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
4+
import java.security.MessageDigest
5+
6+
object HashUtils {
7+
fun sha512(input: String) = hashString("SHA-512", input)
8+
9+
fun sha256(input: String) = hashString("SHA-256", input)
10+
11+
fun sha1(input: String) = hashString("SHA-1", input)
12+
13+
fun generatePasswordHash(password: String): String {
14+
return BCryptPasswordEncoder().encode(password)
15+
}
16+
17+
fun verifyPassword(password: String, passwordHash: String): Boolean {
18+
return BCryptPasswordEncoder().matches(password, passwordHash)
19+
}
20+
21+
fun generateRandomToken(): String {
22+
return sha256(System.currentTimeMillis().toString() + generateRandomString(64))
23+
}
24+
25+
fun generateRandomCode(length: Int): String {
26+
return (1..length)
27+
.map { (0..9).random() }
28+
.joinToString("")
29+
}
30+
31+
fun generateRandomString(length: Int): String {
32+
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
33+
return (1..length)
34+
.map { charPool.random() }
35+
.joinToString("")
36+
}
37+
38+
39+
private fun hashString(type: String, input: String): String {
40+
return MessageDigest
41+
.getInstance(type)
42+
.digest(input.toByteArray())
43+
.fold("", { str, it -> str + "%02x".format(it) })
44+
}
45+
}

web-utils/src/main/kotlin/com/icerockdev/util/Pagination.kt

Lines changed: 0 additions & 12 deletions
This file was deleted.

web-utils/src/main/kotlin/com/icerockdev/util/Utils.kt

Lines changed: 0 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -4,82 +4,13 @@
44

55
package com.icerockdev.util
66

7-
import io.ktor.application.ApplicationCall
8-
import io.ktor.http.Parameters
97
import org.joda.time.DateTime
10-
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
118
import java.net.URI
12-
import java.security.MessageDigest
139

1410
fun String.toURI(): URI = URI.create(this)
1511

16-
fun generatePasswordHash(password: String): String {
17-
return BCryptPasswordEncoder().encode(password)
18-
}
19-
20-
fun verifyPassword(password: String, passwordHash: String): Boolean {
21-
return BCryptPasswordEncoder().matches(password, passwordHash)
22-
}
23-
24-
fun generateConfirmationToken(): String {
25-
val bytes = (DateTime.now().millis.toString() + random(64)).toByteArray()
26-
val md = MessageDigest.getInstance("SHA-256")
27-
val digest = md.digest(bytes)
28-
return digest.fold("", { str, it -> str + "%02x".format(it) })
29-
}
30-
31-
fun generateConfirmationCode(length: Int = 4): String {
32-
return random(length)
33-
}
34-
35-
private fun random(length: Int): String {
36-
return (1..length)
37-
.map { (0..9).random() }
38-
.joinToString("")
39-
}
40-
41-
fun Parameters.parseFilters(): HashMap<String, String> {
42-
val parameters = this
43-
val filters: HashMap<String, String> = hashMapOf()
44-
parameters.entries().forEach {
45-
if (it.key.contains("filters.")) {
46-
val key = it.key.substringAfter(".").toUpperCase()
47-
val value = parameters[it.key]
48-
49-
if (value != null) {
50-
filters[key] = value
51-
}
52-
}
53-
}
54-
55-
return filters
56-
}
57-
5812
fun <E> Iterable<E>.replace(old: E, new: E) = map { if (it == old) new else it }
5913

60-
fun ApplicationCall.getRequestPagination(
61-
limit: Int = 10,
62-
offset: Int = 0,
63-
sortBy: String = "id",
64-
orderBy: String = "DESC"
65-
): Pagination {
66-
return Pagination(
67-
limit = this.parameters["limit"]?.toInt() ?: limit,
68-
offset = this.parameters["offset"]?.toInt() ?: offset,
69-
sortBy = this.parameters["sortBy"] ?: sortBy,
70-
orderBy = this.parameters["orderBy"] ?: orderBy
71-
)
72-
}
73-
74-
75-
fun randomStringGenerator(length: Int): String {
76-
val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
77-
return (1..length)
78-
.map { i -> kotlin.random.Random.nextInt(0, charPool.size) }
79-
.map(charPool::get)
80-
.joinToString("")
81-
}
82-
8314
fun getDateTimeString(dateTime: DateTime): String {
8415
return dateTime.toString("yyyy-MM-dd HH:mm:ss")
8516
}

0 commit comments

Comments
 (0)