first commit
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
2021-08-11 14:40:05 +02:00
commit 26acf2085c
27 changed files with 926 additions and 0 deletions

75
src/Application.kt Normal file
View File

@@ -0,0 +1,75 @@
package com.kmalbz
import com.kmalbz.api.route.OutputServiceRDBServer
import com.kmalbz.consumer.DatabaseConsumer
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.http.*
import io.ktor.gson.*
import io.ktor.features.*
import org.apache.http.HttpException
import com.kmalbz.database.DatabaseFactory
import com.kmalbz.database.dao.SampleObjects
import io.ktor.util.KtorExperimentalAPI
import com.rabbitmq.client.*
import com.typesafe.config.ConfigFactory
import io.ktor.config.HoconApplicationConfig
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.transactions.transaction
import org.koin.ktor.ext.Koin
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
@KtorExperimentalAPI
@Suppress("unused") // Referenced in application.conf
fun Application.module() {
install(ContentNegotiation) {
gson {
}
}
install(Koin) {
printLogger()
modules(com.kmalbz.di.injectionModule)
}
DatabaseFactory.init()
transaction{
SchemaUtils.create(SampleObjects)
}
val appConfig = HoconApplicationConfig(ConfigFactory.load())
val factory = ConnectionFactory()
factory.host = appConfig.property("ktor.mq.host").getString()
factory.username = appConfig.property("ktor.mq.username").getString()
factory.password = appConfig.property("ktor.mq.password").getString()
val connection = factory.newConnection()
val channel = connection.createChannel()
val rabbitExchangeName = appConfig.property("ktor.mq.exchange").getString()
channel.exchangeDeclare(rabbitExchangeName, BuiltinExchangeType.FANOUT)
val queueName = channel.queueDeclare().queue
channel.queueBind(queueName, rabbitExchangeName, "")
channel.basicConsume(queueName, true, DatabaseConsumer())
routing {
install(StatusPages) {
exception<HttpException> {
call.respond(HttpStatusCode.BadRequest)
}
exception<IllegalStateException> {
call.respond(HttpStatusCode.NotAcceptable)
}
}
OutputServiceRDBServer().apply {
registerOutput()
}
}
}

View File

@@ -0,0 +1,11 @@
package com.kmalbz.api.model
import com.google.gson.annotations.SerializedName
import java.time.LocalDate
data class ApiObject(
@SerializedName("id") val id: Int,
@SerializedName("tag") val tag: String,
@SerializedName("device_id") val device_id: Int,
@SerializedName("device_date") val device_date: LocalDate
)

View File

@@ -0,0 +1,71 @@
package com.kmalbz.api.route
import com.kmalbz.database.service.ISampleObjectService
import io.ktor.application.call
import io.ktor.http.HttpStatusCode
import io.ktor.response.respond
import io.ktor.routing.Routing
import io.ktor.routing.get
import org.koin.ktor.ext.inject
import java.time.LocalDate
import java.time.format.DateTimeFormatter
/**
* Output Service - RDB
*
* This is the output interface of the Birbnetes system.
*/
class OutputServiceRDBServer {
/**
* output
*/
fun Routing.registerOutput() {
val resultObjectService by inject<ISampleObjectService>()
get("/output"){
call.respond(resultObjectService.getAllSampleObjects())
}
get("/output/filter/negative") {
val resultList = resultObjectService.getSampleObjecLessthanId(0.5) ?: call.respond(HttpStatusCode.NotFound)
call.respond(resultList)
}
get("/output/filter/positive") {
val resultList = resultObjectService.getSampleObjecGreaterthanId(0.5) ?: call.respond(HttpStatusCode.NotFound)
call.respond(resultList)
}
get("/output/filter/undecided") {
val resultList = resultObjectService.getSampleObjecEqualsId(0.5) ?: call.respond(HttpStatusCode.NotFound)
call.respond(resultList)
}
get("/output/after/{dateAfter}") {
val dateAfter = call.parameters["dateAfter"] ?: error(HttpStatusCode.NotAcceptable)
val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE
val localDateAfter : LocalDate = LocalDate.parse(dateAfter,dateTimeFormatter)
val resultList = resultObjectService.getSampleObjectafterDate(localDateAfter) ?: call.respond(HttpStatusCode.NotFound)
call.respond(resultList)
}
get("/output/before/{dateBefore}") {
val dateAfter = call.parameters["dateBefore"] ?: error(HttpStatusCode.NotAcceptable)
val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE
val localDateBefore : LocalDate = LocalDate.parse(dateAfter,dateTimeFormatter)
val resultList = resultObjectService.getSampleObjectbeforeDate(localDateBefore) ?: call.respond(HttpStatusCode.NotFound)
call.respond(resultList)
}
get("/output/{tagID}") {
val tagID = call.parameters["tagID"] ?: error(HttpStatusCode.NotAcceptable)
val resultObject = resultObjectService.getSampleObjectbyTag(tagID) ?: call.respond(HttpStatusCode.NotFound)
call.respond(resultObject)
}
}
}

View File

@@ -0,0 +1,35 @@
package com.kmalbz.consumer
import com.google.gson.Gson
import com.kmalbz.api.model.ApiObject
import com.kmalbz.database.service.SampleObjectService
import com.rabbitmq.client.AMQP.BasicProperties
import com.rabbitmq.client.Consumer
import com.rabbitmq.client.Envelope
import com.rabbitmq.client.ShutdownSignalException
class DatabaseConsumer : Consumer {
private val sampleObjectService = SampleObjectService()
private val gson = Gson()
override fun handleConsumeOk(consumerTag : String?) {
}
override fun handleCancelOk(p0 : String?) {
throw UnsupportedOperationException()
}
override fun handleRecoverOk(p0 : String?) {
throw UnsupportedOperationException()
}
override fun handleCancel(p0 : String?) {
throw UnsupportedOperationException()
}
override fun handleDelivery(consumerTag : String?, envelope : Envelope?, basicProperties : BasicProperties?, body : ByteArray?) {
val rawJson = body!!.toString(Charsets.UTF_8)
val apiObject = gson.fromJson(rawJson, ApiObject::class.java)
sampleObjectService.addOne(apiObject)
}
override fun handleShutdownSignal(p0 : String?, p1 : ShutdownSignalException?) {
println("got shutdown signal")
}
}

View File

@@ -0,0 +1,46 @@
package com.kmalbz.database
import com.typesafe.config.ConfigFactory
import com.zaxxer.hikari.*
import io.ktor.config.HoconApplicationConfig
import io.ktor.util.KtorExperimentalAPI
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
object DatabaseFactory {
@KtorExperimentalAPI
private val appConfig = HoconApplicationConfig(ConfigFactory.load())
@KtorExperimentalAPI
private val dbUrl = appConfig.property("ktor.db.jdbc").getString()
@KtorExperimentalAPI
private val dbUser = appConfig.property("ktor.db.user").getString()
@KtorExperimentalAPI
private val dbPassword = appConfig.property("ktor.db.password").getString()
@KtorExperimentalAPI
fun init() {
Database.connect(hikari())
}
@KtorExperimentalAPI
private fun hikari(): HikariDataSource {
val config = HikariConfig()
config.driverClassName = "org.postgresql.Driver"
config.jdbcUrl = dbUrl
config.username = dbUser
config.password = dbPassword
config.maximumPoolSize = 3
config.isAutoCommit = false
config.transactionIsolation = "TRANSACTION_REPEATABLE_READ"
config.validate()
return HikariDataSource(config)
}
suspend fun <T> dbQuery(block: () -> T): T =
withContext(Dispatchers.IO) {
transaction { block() }
}
}

View File

@@ -0,0 +1,14 @@
package com.kmalbz.database.dao
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.`java-time`.date
import java.time.LocalDate
object SampleObjects : IntIdTable() {
val tag: Column<String> = varchar("tag", 32)
val timestamp: Column<LocalDate> = date("timestamp").default(LocalDate.now())
val device_id: Column<Int> = integer("device_id")
val device_date: Column<LocalDate> = date("device_date")
override val primaryKey = PrimaryKey(id, name = "PK_ResultObject_Id")
}

View File

@@ -0,0 +1,14 @@
package com.kmalbz.database.model
import com.kmalbz.database.dao.SampleObjects
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
class SampleObject(id: EntityID<Int>): IntEntity(id) {
companion object : IntEntityClass<SampleObject>(SampleObjects)
var tag by SampleObjects.tag
var timestamp by SampleObjects.timestamp
var device_id by SampleObjects.device_id
var device_date by SampleObjects.device_date
}

View File

@@ -0,0 +1,17 @@
package com.kmalbz.database.service
import com.kmalbz.api.model.ApiObject
import java.time.LocalDate
import java.util.*
interface ISampleObjectService{
fun addOne(apiObject: ApiObject)
suspend fun getAllSampleObjects(): List<ApiObject>
suspend fun getSampleObjectbyTag(tag: String): ApiObject?
suspend fun getSampleObjectbyDate(date: LocalDate): List<ApiObject>?
suspend fun getSampleObjectbeforeDate(date: LocalDate): List<ApiObject>?
suspend fun getSampleObjectafterDate(date: LocalDate): List<ApiObject>?
suspend fun getSampleObjecGreaterthanId(id: Int): List<ApiObject>?
suspend fun getSampleObjecLessthanId(id: Int): List<ApiObject>?
suspend fun getSampleObjecEqualsId(id: Int): List<ApiObject>?
}

View File

@@ -0,0 +1,81 @@
package com.kmalbz.database.service
import com.kmalbz.database.DatabaseFactory.dbQuery
import com.kmalbz.database.model.SampleObject
import com.kmalbz.database.dao.SampleObjects
import com.kmalbz.api.model.ApiObject
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import java.time.LocalDate
import java.util.*
class SampleObjectService : ISampleObjectService {
override fun addOne(apiObject: ApiObject) {
transaction {
SampleObject.new {
tag = apiObject.tag
device_date = apiObject.device_date
device_id = apiObject.device_id
}
}
}
override suspend fun getAllSampleObjects(): List<ApiObject> = dbQuery {
SampleObjects.selectAll().map { toResultObject(it) }
}
override suspend fun getSampleObjectbyTag(tag: String): ApiObject? = dbQuery {
SampleObjects.select {
(SampleObjects.tag eq tag)
}.mapNotNull { toResultObject(it) }
.singleOrNull()
}
override suspend fun getSampleObjectbyDate(date: LocalDate): List<ApiObject>? = dbQuery {
SampleObjects.select {
(SampleObjects.date eq date)
}.mapNotNull { toResultObject(it) }
}
override suspend fun getSampleObjectbeforeDate(date: LocalDate): List<ApiObject>? = dbQuery {
SampleObjects.select {
(SampleObjects.date less date)
}.mapNotNull { toResultObject(it) }
}
override suspend fun getSampleObjectafterDate(date: LocalDate): List<ApiObject>? = dbQuery {
SampleObjects.select {
(SampleObjects.date greater date)
}.mapNotNull { toResultObject(it) }
}
override suspend fun getSampleObjecGreaterthanId(probability: Double): List<ApiObject>? = dbQuery {
SampleObjects.select {
(SampleObjects.probability greater probability)
}.mapNotNull { toResultObject(it) }
}
override suspend fun getSampleObjecLessthanId(probability: Double): List<ApiObject>? = dbQuery {
SampleObjects.select {
(SampleObjects.probability less probability)
}.mapNotNull { toResultObject(it) }
}
override suspend fun getSampleObjecEqualsId(probability: Double): List<ApiObject>? = dbQuery {
SampleObjects.select {
(SampleObjects.probability eq probability)
}.mapNotNull { toResultObject(it) }
}
private fun toResultObject(row: ResultRow): ApiObject =
ApiObject(
tag = row[SampleObjects.tag],
device_date = row[SampleObjects.device_date],
device_id = row[SampleObjects.device_id],
id = row[SampleObjects.id.]
)
}

10
src/di/InjectionModule.kt Normal file
View File

@@ -0,0 +1,10 @@
package com.kmalbz.di
import com.kmalbz.database.service.ISampleObjectService
import com.kmalbz.database.service.SampleObjectService
import org.koin.dsl.module
import org.koin.experimental.builder.singleBy
val injectionModule = module(createdAtStart = true) {
singleBy<ISampleObjectService,SampleObjectService>()
}