Skip to content

Commit

Permalink
Introduce detekt (#48)
Browse files Browse the repository at this point in the history
* Introduce detekt
  • Loading branch information
AudunSorheim authored Apr 29, 2024
1 parent f03ab78 commit 34c741d
Show file tree
Hide file tree
Showing 16 changed files with 205 additions and 60 deletions.
10 changes: 9 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "3.2.4"
id("io.spring.dependency-management") version "1.1.4"
id("org.jlleitschuh.gradle.ktlint") version "11.6.0"
id("io.gitlab.arturbosch.detekt") version "1.23.6"
kotlin("jvm") version "1.9.23"
kotlin("plugin.spring") version "1.9.23"
}
Expand Down Expand Up @@ -32,6 +32,7 @@ val mockkVersion = "1.13.10"
val kotestVersion = "5.8.1"
val kotestExtensionsVersion = "2.0.0"
val hikariVersion = "5.1.0"
val detektVersion = "1.23.6"

dependencies {
implementation("org.springframework.boot:spring-boot-starter")
Expand Down Expand Up @@ -66,6 +67,8 @@ dependencies {
}
testImplementation("com.h2database:h2:2.2.224")

detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:$detektVersion")

constraints {
implementation("org.apache.zookeeper:zookeeper") {
because("CVE-2023-44981")
Expand Down Expand Up @@ -112,3 +115,8 @@ tasks {
}
}
}

detekt {
config.from("detekt-config.yml")
buildUponDefaultConfig = true
}
19 changes: 19 additions & 0 deletions detekt-config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
formatting:
active: true
NoWildcardImports:
active: false
style:
MagicNumber:
active: false
WildcardImport:
active: false
MaxLineLength:
active: true
maxLineLength: 120
excludePackageStatements: true
excludeImportStatements: true
excludeCommentStatements: false
excludeRawStrings: true
config:
validation: true
warningsAsErrors: true
2 changes: 1 addition & 1 deletion src/main/kotlin/no/nav/syfo/Application.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ import org.springframework.kafka.annotation.EnableKafka
class Application

fun main(args: Array<String>) {
runApplication<Application>(*args)
runApplication<Application>(args = args)
}
1 change: 1 addition & 0 deletions src/main/kotlin/no/nav/syfo/JacksonKafkaSerializer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ val objectMapper: ObjectMapper = JsonMapper.builder()
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true)
.build()

@Suppress("EmptyFunctionBlock")
class JacksonKafkaSerializer : Serializer<Any> {
override fun serialize(topic: String?, data: Any?): ByteArray? = objectMapper.writeValueAsBytes(data)
override fun close() {}
Expand Down
13 changes: 8 additions & 5 deletions src/main/kotlin/no/nav/syfo/api/AktivitetspliktApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import no.nav.security.token.support.core.api.ProtectedWithClaims
import no.nav.security.token.support.core.context.TokenValidationContextHolder
import no.nav.syfo.TokenValidator
import no.nav.syfo.api.dto.Aktivitetsplikt
import no.nav.syfo.exception.FailedSendingToEsyfovarselException
import no.nav.syfo.exception.LogLevel
import no.nav.syfo.exception.ResourceNotFoundException
import no.nav.syfo.logger
Expand Down Expand Up @@ -58,13 +59,15 @@ class AktivitetspliktApi(
val claims = tokenValidator.validerTokenXClaims()
val fnr = tokenValidator.fnrFraIdportenTokenX(claims)

try {
return try {
aktivitetskravService.sendFerdigstillToVarselbus(fnr)
log.info("Sent les event to varselbus: OK")
return HttpStatus.OK
} catch (e: Exception) {
log.error("Sent les event to varselbus failed due to exception")
return HttpStatus.INTERNAL_SERVER_ERROR
HttpStatus.OK
} catch (e: FailedSendingToEsyfovarselException) {
log.error(
"FailedSendingToEsyfovarselException: Sent les event to varselbus failed. ${e.message}"
)
HttpStatus.INTERNAL_SERVER_ERROR
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package no.nav.syfo.exception

class FailedSendingToEsyfovarselException(cause: Throwable) : Exception(cause)
22 changes: 12 additions & 10 deletions src/main/kotlin/no/nav/syfo/kafka/config/AivenKafkaConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ import org.springframework.kafka.core.KafkaTemplate
import org.springframework.kafka.core.ProducerFactory
import org.springframework.kafka.listener.ContainerProperties

const val aktivitetskravVarselTopic = "teamsykefravr.aktivitetskrav-varsel"
const val aktivitetskravVurderingTopic = "teamsykefravr.aktivitetskrav-vurdering"
const val varselBusTopic = "team-esyfo.varselbus"
const val AKTIVITETSKRAV_VARSEL_TOPIC = "teamsykefravr.aktivitetskrav-varsel"
const val AKTIVITETSKRAV_VURDERING_TOPIC = "teamsykefravr.aktivitetskrav-vurdering"
const val VARSELBUS_TOPIC = "team-esyfo.varselbus"

@Profile("remote")
@Configuration
Expand All @@ -34,19 +34,19 @@ class AivenKafkaConfig(
@Value("\${KAFKA_KEYSTORE_PATH}") private val kafkaKeystorePath: String,
@Value("\${KAFKA_CREDSTORE_PASSWORD}") private val kafkaCredstorePassword: String
) {
private val JAVA_KEYSTORE = "JKS"
private val PKCS12 = "PKCS12"
private val SSL = "SSL"
private val javaKeystore = "JKS"
private val pkcs12 = "PKCS12"
private val ssl = "SSL"

fun commonConfig() = mapOf(
BOOTSTRAP_SERVERS_CONFIG to kafkaBrokers
) + securityConfig()

private fun securityConfig() = mapOf(
CommonClientConfigs.SECURITY_PROTOCOL_CONFIG to SSL,
CommonClientConfigs.SECURITY_PROTOCOL_CONFIG to ssl,
SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG to "", // Disable server host name verification
SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG to JAVA_KEYSTORE,
SslConfigs.SSL_KEYSTORE_TYPE_CONFIG to PKCS12,
SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG to javaKeystore,
SslConfigs.SSL_KEYSTORE_TYPE_CONFIG to pkcs12,
SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG to kafkaTruststorePath,
SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG to kafkaCredstorePassword,
SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG to kafkaKeystorePath,
Expand Down Expand Up @@ -93,7 +93,9 @@ class AivenKafkaConfig(
}

@Bean("EsyfovarselKafkaTemplate")
fun kafkaTemplate(@Qualifier("EsyfovarselProducerFactory") producerFactory: ProducerFactory<String, EsyfovarselHendelse>): KafkaTemplate<String, EsyfovarselHendelse> {
fun kafkaTemplate(
@Qualifier("EsyfovarselProducerFactory") producerFactory: ProducerFactory<String, EsyfovarselHendelse>
): KafkaTemplate<String, EsyfovarselHendelse> {
return KafkaTemplate(producerFactory)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ class AivenKafkaErrorHandler : DefaultErrorHandler(
) {
records.forEach { record ->
log.error(
"Feil i prossesseringen av record med offset: ${record.offset()}, key: ${record.key()} på topic ${record.topic()}",
"Feil i prossesseringen av record med offset: ${record.offset()}, " +
"key: ${record.key()} på topic ${record.topic()}",
thrownException
)
}
Expand All @@ -47,7 +48,8 @@ class AivenKafkaErrorHandler : DefaultErrorHandler(
) {
data.forEach { record ->
log.error(
"Feil i prossesseringen av record med offset: ${record.offset()}, key: ${record.key()} på topic ${record.topic()}",
"Feil i prossesseringen av record med offset: ${record.offset()}, " +
"key: ${record.key()} på topic ${record.topic()}",
thrownException
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import no.nav.syfo.kafka.config.aktivitetskravVarselTopic
import no.nav.syfo.kafka.config.aktivitetskravVurderingTopic
import no.nav.syfo.exception.FailedSendingToEsyfovarselException
import no.nav.syfo.kafka.config.AKTIVITETSKRAV_VARSEL_TOPIC
import no.nav.syfo.kafka.config.AKTIVITETSKRAV_VURDERING_TOPIC
import no.nav.syfo.logger
import no.nav.syfo.metric.Metric
import no.nav.syfo.service.AktivitetskravService
Expand All @@ -16,6 +17,7 @@ import org.springframework.context.annotation.Profile
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.kafka.support.Acknowledgment
import org.springframework.stereotype.Component
import java.io.IOException
import kotlin.system.exitProcess

@Profile("remote")
Expand All @@ -32,7 +34,7 @@ class AktivitetskravKafkaListener @Autowired constructor(
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}

@KafkaListener(topics = [aktivitetskravVarselTopic, aktivitetskravVurderingTopic])
@KafkaListener(topics = [AKTIVITETSKRAV_VARSEL_TOPIC, AKTIVITETSKRAV_VURDERING_TOPIC])
fun listenToTopic(
record: ConsumerRecord<String, String>,
ack: Acknowledgment
Expand All @@ -41,17 +43,37 @@ class AktivitetskravKafkaListener @Autowired constructor(
metric.countRecordReceived()
try {
when (topic) {
aktivitetskravVurderingTopic ->
AKTIVITETSKRAV_VURDERING_TOPIC ->
aktivitetskravService.processAktivitetskravVurdering(objectMapper.readValue(record.value()))
aktivitetskravVarselTopic ->

AKTIVITETSKRAV_VARSEL_TOPIC ->
aktivitetskravService.processAktivitetskravVarsel(objectMapper.readValue(record.value()))

else ->
throw IllegalArgumentException("Received record from topic not in the subscription list: $topic")
}

ack.acknowledge()
} catch (e: RuntimeException) {
log.error("[EsyfovarselAK] Error during record processing from topic $topic. Shutting down application ...", e)
} catch (e: IOException) {
log.error(
"IOException during record processing from topic $topic. Shutting down application ...",
e
)
metric.countKafkaErrorShutdown()
exitProcess(1)
} catch (e: IllegalArgumentException) {
log.error(
"IllegalArgumentException during record processing from topic $topic. Shutting down application ...",
e
)
metric.countKafkaErrorShutdown()
exitProcess(1)
} catch (e: FailedSendingToEsyfovarselException) {
log.error(
"FailedSendingToEsyfovarselException during record processing from " +
"topic $topic. Shutting down application ...",
e
)
metric.countKafkaErrorShutdown()
exitProcess(1)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ data class DocumentComponentDTO(
val key: String? = null,
val title: String?,
val texts: List<String>
) : Serializable
) : Serializable {
companion object {
private const val serialVersionUID = 1L
}
}

enum class DocumentComponentType {
HEADER_H1,
Expand All @@ -35,6 +39,9 @@ data class KAktivitetskravVarsel(
val document: List<DocumentComponentDTO>,
val type: String
) : Serializable, VarselbusEvent {
companion object {
private const val serialVersionUID = 1L
}
override fun personIdent() = personIdent

override fun varselData(): VarselData = VarselData(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ data class KAktivitetskravVurdering(
val sistVurdert: OffsetDateTime?,
val frist: LocalDate?
) : Serializable, VarselbusEvent {
companion object {
private const val serialVersionUID = 1L
}
override fun personIdent() = personIdent

override fun varselData() = VarselData(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
package no.nav.syfo.kafka.producer

import no.nav.syfo.kafka.config.varselBusTopic
import no.nav.syfo.exception.FailedSendingToEsyfovarselException
import no.nav.syfo.kafka.config.VARSELBUS_TOPIC
import no.nav.syfo.kafka.domain.EsyfovarselHendelse
import org.apache.kafka.clients.producer.ProducerRecord
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Profile
import org.springframework.kafka.KafkaException
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Component
import java.util.*
import java.util.concurrent.ExecutionException

@Profile("remote")
@Component
Expand All @@ -23,14 +26,21 @@ class EsyfovarselKafkaProducer @Autowired constructor(
try {
kafkaTemplate.send(
ProducerRecord(
varselBusTopic,
VARSELBUS_TOPIC,
UUID.randomUUID().toString(),
esyfovarselHendelse
)
).get()
} catch (e: Exception) {
log.error("[EsyfovarselAK]: Exception was thrown when attempting to send varsel to esyfovarsel. ${e.message}")
throw e
} catch (e: ExecutionException) {
log.error(
"ExecutionException was thrown when attempting to send varsel to esyfovarsel. ${e.message}"
)
throw FailedSendingToEsyfovarselException(e)
} catch (e: KafkaException) {
log.error(
"KafkaException was thrown when attempting to send varsel to esyfovarsel. ${e.message}"
)
throw FailedSendingToEsyfovarselException(e)
}
}

Expand Down
28 changes: 17 additions & 11 deletions src/main/kotlin/no/nav/syfo/persistence/AktivitetskravDAO.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import no.nav.syfo.api.dto.Aktivitetsplikt
import no.nav.syfo.kafka.consumer.domain.DocumentComponentDTO
import no.nav.syfo.kafka.consumer.domain.KAktivitetskravVarsel
import no.nav.syfo.kafka.consumer.domain.KAktivitetskravVurdering
import no.nav.syfo.logger
import no.nav.syfo.service.domain.AktivitetskravVurdering
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.jdbc.core.JdbcTemplate
Expand All @@ -31,16 +32,18 @@ class AktivitetskravDAO(
val jdbcTemplate: JdbcTemplate
) {

/*
** Dette er sammenheng mellom de ulike UUIDene i varsel og vurdering objekter **
===================================================================================================================================================================================
* Aktivitetskrav identifikator, felles innenfor ett aktivitetskrav. Nytt aktivitetskrav med ny uuid blir laget når veileder gjør NY_VURDERING:
* KAktivitetskravVarsel.aktivitetskravUuid ("aktivitetskrav_uuid" i DB) <--> KAktivitetskravVurdering.uuid ("vurdering_uuid" i DB):
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* KAktivitetskravVarsel.vurderingUuid ("vurdering_uuid" i DB) <--> KAktivitetskravVurdering.sisteVurderingUuid ("siste_vurdering_uuid" i DB): selve vurderings identifikator
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/

private val log = logger()

/*
** Dette er sammenhengen mellom de ulike UUIDene i varsel- og vurderingsobjekter **
* Aktivitetskrav identifikator, felles innenfor ett aktivitetskrav. Et nytt aktivitetskrav
* med en ny uuid blir laget når veileder gjør NY_VURDERING:
* KAktivitetskravVarsel.aktivitetskravUuid ("aktivitetskrav_uuid" i DB) <-->
* KAktivitetskravVurdering.uuid ("vurdering_uuid" i DB):
* KAktivitetskravVarsel.vurderingUuid ("vurdering_uuid" i DB) <-->
* KAktivitetskravVurdering.sisteVurderingUuid ("siste_vurdering_uuid" i DB):
* den faktiske vurderingsidentifikatoren
*/
fun storeAktivitetkravVurdering(vurdering: KAktivitetskravVurdering): Int {
val uuid = UUID.randomUUID()
val lagreSql = """
Expand Down Expand Up @@ -152,6 +155,7 @@ class AktivitetskravDAO(
return try {
namedParameterJdbcTemplate.queryForObject(query, namedParameters, AktivitetspliktRowMapper())
} catch (e: EmptyResultDataAccessException) {
log.debug("Failed to get Aktivitetsplikt", e)
null
}
}
Expand Down Expand Up @@ -183,6 +187,7 @@ class AktivitetskravDAO(
return try {
namedParameterJdbcTemplate.query(query, namedParameters, AktivitetspliktRowMapper())
} catch (e: EmptyResultDataAccessException) {
log.debug("Failed to get historisk aktivitetsplikt", e)
null
}
}
Expand Down Expand Up @@ -212,11 +217,12 @@ class AktivitetskravDAO(

private fun Timestamp.toOffsetDateTime() = this.toInstant().atOffset(ZoneOffset.UTC)

val jsonWriter = ObjectMapper().apply {
private val jsonWriter = ObjectMapper().apply {
registerKotlinModule()
registerModule(JavaTimeModule())
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
}

fun List<String>.toStr() = this.joinToString(separator = ",").trim()

fun List<DocumentComponentDTO>.documentsToStr() = jsonWriter.writeValueAsString(this)
Expand Down
Loading

0 comments on commit 34c741d

Please sign in to comment.