Initial files and some experimenting

This commit is contained in:
2025-07-29 20:52:21 -04:00
parent dffb2efeed
commit 954dc97dbd
29 changed files with 1057 additions and 2 deletions

View File

@@ -0,0 +1,15 @@
package codes.kalar
import io.ktor.server.application.*
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
configureHTTP()
configureSecurity()
configureSerialization()
configureDatabases()
configureRouting()
}

View File

@@ -0,0 +1,74 @@
package codes.kalar
import kotlinx.coroutines.*
import kotlinx.serialization.Serializable
import java.sql.Connection
import java.sql.Statement
@Serializable
data class City(val name: String, val population: Int)
class CityService(private val connection: Connection) {
companion object {
private const val CREATE_TABLE_CITIES =
"CREATE TABLE CITIES (ID SERIAL PRIMARY KEY, NAME VARCHAR(255), POPULATION INT);"
private const val SELECT_CITY_BY_ID = "SELECT name, population FROM cities WHERE id = ?"
private const val INSERT_CITY = "INSERT INTO cities (name, population) VALUES (?, ?)"
private const val UPDATE_CITY = "UPDATE cities SET name = ?, population = ? WHERE id = ?"
private const val DELETE_CITY = "DELETE FROM cities WHERE id = ?"
}
init {
val statement = connection.createStatement()
statement.executeUpdate(CREATE_TABLE_CITIES)
}
private var newCityId = 0
// Create new city
suspend fun create(city: City): Int = withContext(Dispatchers.IO) {
val statement = connection.prepareStatement(INSERT_CITY, Statement.RETURN_GENERATED_KEYS)
statement.setString(1, city.name)
statement.setInt(2, city.population)
statement.executeUpdate()
val generatedKeys = statement.generatedKeys
if (generatedKeys.next()) {
return@withContext generatedKeys.getInt(1)
} else {
throw Exception("Unable to retrieve the id of the newly inserted city")
}
}
// Read a city
suspend fun read(id: Int): City = withContext(Dispatchers.IO) {
val statement = connection.prepareStatement(SELECT_CITY_BY_ID)
statement.setInt(1, id)
val resultSet = statement.executeQuery()
if (resultSet.next()) {
val name = resultSet.getString("name")
val population = resultSet.getInt("population")
return@withContext City(name, population)
} else {
throw Exception("Record not found")
}
}
// Update a city
suspend fun update(id: Int, city: City) = withContext(Dispatchers.IO) {
val statement = connection.prepareStatement(UPDATE_CITY)
statement.setString(1, city.name)
statement.setInt(2, city.population)
statement.setInt(3, id)
statement.executeUpdate()
}
// Delete a city
suspend fun delete(id: Int) = withContext(Dispatchers.IO) {
val statement = connection.prepareStatement(DELETE_CITY)
statement.setInt(1, id)
statement.executeUpdate()
}
}

View File

@@ -0,0 +1,71 @@
package codes.kalar
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.sql.Connection
import java.sql.DriverManager
fun Application.configureDatabases() {
val dbConnection: Connection = connectToPostgres()
routing {
get("/database") {
var title = mutableListOf<String>()
// FUZZY SEARCH!!!!
val statement = dbConnection.prepareStatement("SELECT title FROM collection_item WHERE levenshtein(title, ?) <= 10 LIMIT 20")
statement.setString(1, "An Absolutely Remarkable Thing")
val resultSet = statement.executeQuery()
while (resultSet.next()) {
title.addLast(resultSet.getString("title") + "\n")
}
call.respond(title.toString() ?: "No data found")
}
}
}
/**
* Makes a connection to a Postgres database.
*
* In order to connect to your running Postgres process,
* please specify the following parameters in your configuration file:
* - postgres.url -- Url of your running database process.
* - postgres.user -- Username for database connection
* - postgres.password -- Password for database connection
*
* If you don't have a database process running yet, you may need to [download]((https://www.postgresql.org/download/))
* and install Postgres and follow the instructions [here](https://postgresapp.com/).
* Then, you would be able to edit your url, which is usually "jdbc:postgresql://host:port/database", as well as
* user and password values.
*
*
* @param embedded -- if [true] defaults to an embedded database for tests that runs locally in the same process.
* In this case you don't have to provide any parameters in configuration file, and you don't have to run a process.
*
* @return [Connection] that represent connection to the database. Please, don't forget to close this connection when
* your application shuts down by calling [Connection.close]
* */
fun Application.connectToPostgres(embedded: Boolean = false): Connection {
Class.forName("org.postgresql.Driver")
if (embedded) {
log.info("Using embedded H2 database for testing; replace this flag to use postgres")
return DriverManager.getConnection("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "root", "")
} else {
val url = environment.config.property("postgres.url").getString()
log.info("Connecting to postgres database at $url")
val user = environment.config.property("postgres.user").getString()
val password = environment.config.property("postgres.password").getString()
return DriverManager.getConnection(url, user, password)
}
}

26
src/main/kotlin/HTTP.kt Normal file
View File

@@ -0,0 +1,26 @@
package codes.kalar
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.sql.Connection
import java.sql.DriverManager
fun Application.configureHTTP() {
install(DefaultHeaders) {
header("X-Engine", "Ktor") // will send this header with each response
}
routing {
swaggerUI(path = "openapi")
}
}

View File

@@ -0,0 +1,74 @@
package codes.kalar
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.sql.Connection
import java.sql.DriverManager
fun Application.configureRouting() {
routing {
get("/") {
call.respondText("Hello World!")
}
get("/patron") {
if (call.request.queryParameters.isEmpty()) {
call.respond(HttpStatusCode.BadRequest, "Invalid parameters")
}
else {
call.respondText("Hello, ${call.request.queryParameters["patron"]}")
}
}
post("/patron") {
call.respondText("Patron is posted")
}
delete("/patron") {
call.respondText("Do you have permissions?")
}
get("/libraries") {
call.respondText("Libraries are neat!")
}
post("/libraries") {
call.respondText("Library is posted")
}
delete("/libraries/{id}") {
call.respondText("We hate to see you go!")
}
get("/items") {
call.respondText("I'll search for that book!")
}
post("/items") {
call.respondText("Somebody got back from Barnes & Noble!")
}
delete("/items/{id}") {
call.respondText(":(")
}
get("/libraries/{libraryId}/items/{itemId}") {
call.respondText("You asked for ${call.parameters["itemId"]} from ${call.parameters["libraryId"]}")
}
get("/authenticate") {
call.respondText(System.getenv("JWT_DOMAIN") ?: "Ain't life a bitch?")
}
}
}

View File

@@ -0,0 +1,43 @@
package codes.kalar
import java.io.File
import java.util.Properties
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.sql.Connection
import java.sql.DriverManager
fun Application.configureSecurity() {
// Please read the jwt property from the config file if you are using EngineMain
val jwtAudience = environment.config.property("jwt.audience").toString()
val jwtDomain = environment.config.property("jwt.domain").toString()
val jwtRealm = "ktor sample app"
val jwtSecret = environment.config.property("jwt.secret").toString()
authentication {
jwt {
realm = jwtRealm
verifier(
JWT
.require(Algorithm.HMAC256(jwtSecret))
.withAudience(jwtAudience)
.withIssuer(jwtDomain)
.build()
)
validate { credential ->
if (credential.payload.audience.contains(jwtAudience)) JWTPrincipal(credential.payload) else null
}
}
}
}

View File

@@ -0,0 +1,25 @@
package codes.kalar
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.swagger.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.sql.Connection
import java.sql.DriverManager
fun Application.configureSerialization() {
routing {
get("/json/kotlinx-serialization") {
call.respond(mapOf("hello" to "world"))
}
}
}

View File

@@ -0,0 +1,11 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class CheckedOutItem(
val id: Long,
val itemId: Long,
val patronId: Long,
val dueDate: String,
)

View File

@@ -0,0 +1,27 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class CollectionItem(
val id: Long,
val title: String?,
val author: String?,
val publisher: String?,
val publishingDate: String?,
val locNumber: String?,
val deweyDecimalNumber: String?,
val isbn: Int?,
val sortTitle: String?,
val format: String?,
val language: String?,
val pageCount: Int?,
val category: String?,
val description: String?,
val priceInCents: Int?,
val coverImageUri: String?,
val isCheckedIn: Boolean,
val isArchived: Boolean,
val isLost: Boolean,
val lostDate: String?,
)

View File

@@ -0,0 +1,12 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class LateItem(
val id: Long,
val itemId: Long,
val patronId: Long,
val dueDate: String,
var freeInCents: Int,
)

View File

@@ -0,0 +1,10 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class Library(
val id: Long,
val name: String,
val address: String,
)

View File

@@ -0,0 +1,10 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class LibraryCollection(
val id: Long,
val libraryId: Long,
val itemId: Long,
)

View File

@@ -0,0 +1,12 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class LostItem(
val id: Long,
val itemId: Long,
val patronId: Long,
val dueDate: String,
val costInCents: Int,
)

View File

@@ -0,0 +1,11 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class OnHoldItem(
val id: Long,
val itemId: Long,
val patronId: Long,
val holdReleaseDate: String,
)

View File

@@ -0,0 +1,14 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class Patron(
val id: Long,
val name: String,
val hasGoodStanding: Boolean,
val feeTotal: Long,
val isArchived: Boolean,
val lastLogin: String?,
val password: String?,
)

View File

@@ -0,0 +1,11 @@
package codes.kalar.model
import kotlinx.serialization.Serializable
@Serializable
data class Staff(
val id: Long,
val name: String,
val password: String?,
val isArchived: Boolean,
)

View File

@@ -0,0 +1,35 @@
package codes.kalar.service
import codes.kalar.model.CollectionItem
import kotlinx.coroutines.*
import kotlinx.serialization.Serializable
import java.sql.Connection
import java.sql.Statement
class CollectionItemService(private val connection: Connection) {
var pageOfItems = mutableListOf<CollectionItem>()
companion object {
// TODO add create table statement
private const val CREATE_COLLECTION_ITEMS_TABLE = "CREATE TABLE IF NOT EXISTS collection_items ("
private const val SELECT_ITEM_BY_TITLE = "SELECT * FROM collection_items WHERE title = ? limit 10"
private const val INSERT_ITEM = "INSERT INTO collection_items (name, population) VALUES (?, ?)"
private const val UPDATE_ITEM = "UPDATE collection_items SET name = ?, population = ? WHERE id = ?"
private const val DELETE_ITEM = "DELETE FROM collection_items WHERE id = ?"
}
init {
val statement = connection.createStatement()
val tables = connection.metaData.getTables(null, "public", "collection_items", arrayOf("TABLE"))
if (!tables.next()) {
statement.executeUpdate(CREATE_COLLECTION_ITEMS_TABLE)
}
}
suspend fun create(collectionItem: CollectionItem) {}
suspend fun read(collectionItem: CollectionItem) {}
suspend fun update(collectionItem: CollectionItem) {}
suspend fun delete(collectionItem: CollectionItem) {}
}