Skip to content

Commit

Permalink
apply kotlinter v4
Browse files Browse the repository at this point in the history
  • Loading branch information
osoykan committed Oct 9, 2023
1 parent 3376763 commit 041201b
Show file tree
Hide file tree
Showing 91 changed files with 1,411 additions and 1,286 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ fun run(
args: Array<String>,
applicationOverrides: () -> Module = { module { } }
): ApplicationEngine {
val applicationEngine = embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
mainModule(args, applicationOverrides)
}
val applicationEngine =
embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
mainModule(args, applicationOverrides)
}
applicationEngine.start(wait = false)

return applicationEngine
Expand Down Expand Up @@ -82,22 +83,25 @@ fun Application.mainModule(
}
}

fun dataModule(args: Array<String>) = module {
val map = args.associate { it.split("=")[0] to it.split("=")[1] }
single {
val builder = PostgresqlConnectionConfiguration.builder().apply {
host(map["database.host"]!!)
database(map["database.databaseName"]!!)
port(map["database.port"]!!.toInt())
password(map["database.password"]!!)
username(map["database.username"]!!)
fun dataModule(args: Array<String>) =
module {
val map = args.associate { it.split("=")[0] to it.split("=")[1] }
single {
val builder =
PostgresqlConnectionConfiguration.builder().apply {
host(map["database.host"]!!)
database(map["database.databaseName"]!!)
port(map["database.port"]!!.toInt())
password(map["database.password"]!!)
username(map["database.username"]!!)
}
PostgresqlConnectionFactory(builder.connectTimeout(Duration.ofSeconds(10)).build())
}
PostgresqlConnectionFactory(builder.connectTimeout(Duration.ofSeconds(10)).build())
}
}

fun applicationModule() = module {
singleOf(::JediRepository)
singleOf(::JediService)
singleOf(::MutexLockProvider) { bind<LockProvider>() }
}
fun applicationModule() =
module {
singleOf(::JediRepository)
singleOf(::JediService)
singleOf(::MutexLockProvider) { bind<LockProvider>() }
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import kotlinx.coroutines.sync.Mutex
import java.time.Duration

interface LockProvider {

suspend fun acquireLock(
name: String,
duration: Duration
Expand All @@ -14,7 +13,6 @@ interface LockProvider {
}

class MutexLockProvider : LockProvider {

private val mutex = Mutex()

override suspend fun acquireLock(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ class ExampleTest : FunSpec({
postgresql {
shouldExecute(
"""
DROP TABLE IF EXISTS Jedis;
CREATE TABLE IF NOT EXISTS Jedis (
id serial PRIMARY KEY,
name VARCHAR (50) NOT NULL
);
DROP TABLE IF EXISTS Jedis;
CREATE TABLE IF NOT EXISTS Jedis (
id serial PRIMARY KEY,
name VARCHAR (50) NOT NULL
);
""".trimIndent()
)
shouldExecute("INSERT INTO Jedis (id, name) VALUES ('$givenId', 'Obi Wan Kenobi')")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory

class TestSystemConfig : AbstractProjectConfig() {

private val logger: Logger = LoggerFactory.getLogger("WireMockMonitor")

override suspend fun beforeProject() =
TestSystem(baseUrl = "http://localhost:8080")
.with {
Expand All @@ -40,9 +40,10 @@ class TestSystemConfig : AbstractProjectConfig() {
)
}
ktor(
withParameters = listOf(
"ktor.server.port=8001"
),
withParameters =
listOf(
"ktor.server.port=8001"
),
runner = { parameters ->
stove.ktor.example.run(parameters) {
addTestSystemDependencies()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import org.koin.dsl.module
import stove.ktor.example.LockProvider
import java.time.Duration

fun addTestSystemDependencies(): Module = module {
singleOf(::NoOpLockProvider) { bind<LockProvider>() }
}
fun addTestSystemDependencies(): Module =
module {
singleOf(::NoOpLockProvider) { bind<LockProvider>() }
}

class NoOpLockProvider : LockProvider {
override suspend fun acquireLock(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class ProductCreator(
) {
@Value("\${kafka.producer.product-created.topic-name}")
lateinit var productCreatedTopic: String

suspend fun create(req: ProductCreateRequest): String {
val supplierPermission = supplierHttpService.getSupplierPermission(req.id)
if (!supplierPermission.isAllowed) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import java.net.UnknownHostException

class Defaults {
companion object {
val HOST_NAME: String = try {
InetAddress.getLocalHost().hostName
} catch (e: UnknownHostException) {
"stove-service-host"
}
val HOST_NAME: String =
try {
InetAddress.getLocalHost().hostName
} catch (e: UnknownHostException) {
"stove-service-host"
}

const val AGENT_NAME = "stove-service"
const val USER_EMAIL = "[email protected]"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import org.springframework.context.annotation.Configuration

@Configuration
class ObjectMapperConfig {

companion object {
fun createObjectMapperWithDefaults(): ObjectMapper {
val isoInstantModule = SimpleModule()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@ import stove.spring.example.application.handlers.ProductCreator
@RestController
@RequestMapping("/api")
class ProductController(private val productCreator: ProductCreator) {

@GetMapping("/index")
suspend fun get(@RequestParam(required = false) keyword: String): String {
suspend fun get(
@RequestParam(required = false) keyword: String
): String {
return "Hi from Stove framework with $keyword"
}

@PostMapping("/product/create")
suspend fun createProduct(@RequestBody productCreateRequest: ProductCreateRequest): String {
suspend fun createProduct(
@RequestBody productCreateRequest: ProductCreateRequest
): String {
return productCreator.create(productCreateRequest)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ class CouchbaseConfiguration(
private val meterRegistry: MeterRegistry
) {
companion object {
val objectMapper: ObjectMapper = ObjectMapperConfig.createObjectMapperWithDefaults()
.registerModule(JsonValueModule())
val objectMapper: ObjectMapper =
ObjectMapperConfig.createObjectMapperWithDefaults()
.registerModule(JsonValueModule())
}

@Primary
Expand All @@ -50,9 +51,10 @@ class CouchbaseConfiguration(
@Primary
@Bean(destroyMethod = "disconnect")
fun cluster(clusterEnvironment: ClusterEnvironment): ReactiveCluster {
val clusterOptions = ClusterOptions
.clusterOptions(couchbaseProperties.username, couchbaseProperties.password)
.environment(clusterEnvironment)
val clusterOptions =
ClusterOptions
.clusterOptions(couchbaseProperties.username, couchbaseProperties.password)
.environment(clusterEnvironment)

return ReactiveCluster.connect(couchbaseProperties.hosts.joinToString(","), clusterOptions)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ class SupplierHttpService(private val supplierHttpClient: WebClient) : SupplierS
return supplierHttpClient
.get()
.uri {
val builder = it
.path("/suppliers/{id}/allowed")
val builder =
it
.path("/suppliers/{id}/allowed")
builder.build(id)
}
.accept(MediaType.APPLICATION_JSON)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,19 @@ import java.util.concurrent.TimeUnit
@Configuration
@EnableConfigurationProperties(WebClientConfigurationProperties::class)
class WebClientConfiguration(private val webClientConfigurationProperties: WebClientConfigurationProperties) {

companion object {
private const val MAX_MEMORY_SIZE = 50 * 1024 * 1024
}

@Bean
fun supplierHttpClient(exchangeStrategies: ExchangeStrategies): WebClient = defaultWebClientBuilder(
webClientConfigurationProperties.supplierHttp.url,
webClientConfigurationProperties.supplierHttp.connectTimeout,
webClientConfigurationProperties.supplierHttp.readTimeout
)
.exchangeStrategies(exchangeStrategies)
.build()
fun supplierHttpClient(exchangeStrategies: ExchangeStrategies): WebClient =
defaultWebClientBuilder(
webClientConfigurationProperties.supplierHttp.url,
webClientConfigurationProperties.supplierHttp.connectTimeout,
webClientConfigurationProperties.supplierHttp.readTimeout
)
.exchangeStrategies(exchangeStrategies)
.build()

@Bean
fun webClientObjectMapper(): ObjectMapper {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,21 @@ class KafkaProducer(
private val logger: Logger = LoggerFactory.getLogger(KafkaProducer::class.java)

suspend fun send(message: KafkaOutgoingMessage) {
val recordHeaders = message.headers.map { it ->
RecordHeader(
it.key,
it.value.toByteArray()
val recordHeaders =
message.headers.map { it ->
RecordHeader(
it.key,
it.value.toByteArray()
)
}.toMutableList()
val record =
ProducerRecord<String, Any>(
message.topic,
message.partition,
message.key,
message.payload,
recordHeaders
)
}.toMutableList()
val record = ProducerRecord<String, Any>(
message.topic,
message.partition,
message.key,
message.payload,
recordHeaders
)
logger.info("Kafka message has published $message")
kafkaTemplate.send(record)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ interface ConsumerSettings : MapBasedSettings
class DefaultConsumerSettings(
val kafkaProperties: KafkaProperties
) : ConsumerSettings {

@Value("\${kafka.config.thread-count.basic-listener}")
private val basicListenerThreadCount: String = "100"

Expand Down Expand Up @@ -48,5 +47,6 @@ class DefaultConsumerSettings(
}

private fun ofSeconds(seconds: Long) = Duration.ofSeconds(seconds).toMillis().toInt()

private fun ofMinutes(minutes: Long) = Duration.ofMinutes(minutes).toMillis().toInt()
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ class KafkaConsumerConfiguration(
private val objectMapper: ObjectMapper,
private val customConsumerInterceptor: ConsumerAwareRecordInterceptor<String, String>
) {

@Bean
fun kafkaListenerContainerFactory(
kafkaTemplate: KafkaTemplate<String, Any>,
Expand All @@ -30,9 +29,10 @@ class KafkaConsumerConfiguration(
factory.consumerFactory = consumerFactory
factory.containerProperties.isDeliveryAttemptHeader = true
factory.setRecordMessageConverter(stringJsonMessageConverter())
val errorHandler = DefaultErrorHandler(
FixedBackOff(0, 0)
)
val errorHandler =
DefaultErrorHandler(
FixedBackOff(0, 0)
)

factory.setCommonErrorHandler(errorHandler)
factory.setRecordInterceptor(customConsumerInterceptor)
Expand All @@ -49,9 +49,10 @@ class KafkaConsumerConfiguration(
factory.setRecordMessageConverter(stringJsonMessageConverter())
factory.containerProperties.isDeliveryAttemptHeader = true
factory.consumerFactory = consumerRetryFactory
val errorHandler = DefaultErrorHandler(
FixedBackOff(5000, 1)
)
val errorHandler =
DefaultErrorHandler(
FixedBackOff(5000, 1)
)
factory.setCommonErrorHandler(errorHandler)
factory.setRecordInterceptor(customConsumerInterceptor)
return factory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,21 @@ class KafkaProducerConfiguration {
@Bean
fun kafkaTemplate(producerFactory: ProducerFactory<String, Any>): KafkaTemplate<String, Any> {
val kafkaTemplate = KafkaTemplate(producerFactory)
kafkaTemplate.setProducerListener(object : ProducerListener<String, Any> {
override fun onError(
producerRecord: ProducerRecord<String, Any>,
recordMetadata: RecordMetadata?,
exception: java.lang.Exception?
) {
logger.error(
"ProducerListener Topic: ${producerRecord.topic()}, Key: ${producerRecord.value()}",
exception
)
super.onError(producerRecord, recordMetadata, exception)
kafkaTemplate.setProducerListener(
object : ProducerListener<String, Any> {
override fun onError(
producerRecord: ProducerRecord<String, Any>,
recordMetadata: RecordMetadata?,
exception: java.lang.Exception?
) {
logger.error(
"ProducerListener Topic: ${producerRecord.topic()}, Key: ${producerRecord.value()}",
exception
)
super.onError(producerRecord, recordMetadata, exception)
}
}
})
)
return kafkaTemplate
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ class FailingProductCreateConsumer {
groupId = "#{@consumerConfig.groupId}",
containerFactory = KafkaConsumerConfiguration.LISTENER_BEAN_NAME
)
fun listen(cr: ConsumerRecord<String, String>): Unit = runBlocking(MDCContext()) {
logger.info("Received product failing event ${cr.value()}")
fun listen(cr: ConsumerRecord<String, String>): Unit =
runBlocking(MDCContext()) {
logger.info("Received product failing event ${cr.value()}")

throw BusinessException("Failing product create event")
}
throw BusinessException("Failing product create event")
}
}
Loading

0 comments on commit 041201b

Please sign in to comment.