https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
spring
  • i

    Ivan Feliciano

    09/29/2022, 11:10 PM
    Hi, I have a multi database setup in Spring Boot, each are in the
    application.yml
    file as
    spring.datasource.[db1/db2].[options]
    . Everything is working fine except I am not able to specify a separate schema.sql for each of them. I have tried by making a DataSourceInitializer bean but it is not getting executed (the bean is never even created). A normal
    schema.sql
    file works but is executed on all the databases.
    @Bean(name = ["kvkDsInit"])
        fun dsInit(@Qualifier("kvkDataSource") dataSource: DataSource): DataSourceInitializer {
            val rdp = ResourceDatabasePopulator().apply {
                addScript(ClassPathResource("schema-kvk.sql"))
            }
    
            return DataSourceInitializer().apply {
                setDataSource(dataSource)
                setDatabasePopulator(rdp)
            }
        }
  • y

    Yogeshvu

    10/07/2022, 4:10 PM
    I would like to retrieve response body message for a given 400 status code when using the spring webclient. However, I can only find the error code and not the actual error message contained in the code. I am using following snippet. how to actually extract the response body in the 400 status response .
    val retrievedResource: Mono<String> = myRequest
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError) { Mono.error(RuntimeException("4XX Error ${it.statusCode()}, ${it.bodyToMono(String::class.java)}")) }
                .onStatus(HttpStatus::is5xxServerError) { Mono.error(RuntimeException("5XX Error ${it.statusCode()}, ${it.bodyToMono(String::class.java)}")) }
            .bodyToMono(String::class.java)
            return retrievedResource.share().block()
    g
    • 2
    • 2
  • d

    dany giguere

    10/09/2022, 4:04 PM
    I’m trying to set up a Spring Boot Kotlin app with mysql/reactive. I’m following this simple example:

    https://www.youtube.com/watch?v=Ug7rADxR1oE▾

    . When I call http://localhost:8080/customers I get this 500 error though:
    Failed to obtain R2DBC Connection; nested exception is java.util.NoSuchElementException: Flux#last() didn't observe any onNext signal
    I pushed the project on this public repo: https://github.com/danygiguere/spring-boot-kotlin-reactive but basically, I have this config:
    @Configuration
    class Database : AbstractR2dbcConfiguration() {
    
        override fun connectionFactory(): ConnectionFactory
                = MySqlConnectionFactory.from(
            MySqlConnectionConfiguration.builder()
                .host("localhost")
                .username("root")
                .port(3306)
                .password("root")
                .database("reactive")
                .connectTimeout(Duration.ofSeconds(3))
                .useServerPrepareStatement()
                .build()
        )
    
    }
    my application.yml:
    spring:
        r2dbc:
            url: r2dbc:<mysql://localhost:3306/reactive?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false>
            username: root
            password: root
    and the route in question is:
    @RestController
    @RequestMapping("/customers")
    class CustomerController(val customerRepository: CustomerRepository) {
    
        @GetMapping
        suspend fun getAllCustomer() : Flow<Customer> = customerRepository.findAll().asFlow()
    ...
  • d

    dany giguere

    10/09/2022, 4:11 PM
    Update: one thing I just noticed is if I replace my getAllCustomer function with :
    suspend fun getAllCustomer() : Flux<Customer> = customerRepository.findAll()
    then I get this response:
    {
      "scanAvailable": true,
      "prefetch": -1
    }
  • j

    jmfayard

    10/10/2022, 6:36 PM
    Bonjour. After years of backend with Kotlin I may go back to Java - which I don’t mind - but the company has unfortunately a dumb process where you need to write Java / Spring code in a browser without code completion or quick fixes or documentation or stackoverflow. Do you have a good & simple Java/Spring project I can use to refresh my Java skills? (like putting the type first 🙂 )
    c
    d
    +5
    • 8
    • 14
  • r

    Robert Jaros

    10/22/2022, 12:27 PM
    After upgrading spring boot project to kotlin 1.7.20 different files are produced by the same gradle task (
    bootJar
    ). I can see two tasks being executed with 1.7.20 -
    jar
    and
    inspectClassesForKotlinIC
    , which are not executed with 1.7.10. Anyone has some more information about this change?
    e
    • 2
    • 1
  • j

    João Gabriel Zó

    10/26/2022, 12:09 PM
    is there a way to make every response object turn the fields to snake_case without having to
    @JsonNaming
    every data class?
    t
    • 2
    • 1
  • d

    daphillips

    10/26/2022, 8:40 PM
    I know this question has been asked before, but does using
    @Cachable
    with
    suspend
    functions still not work correctly? Everything I've found seems to indicate it doesn't work, but those findings are also a year or two old
    p
    • 2
    • 1
  • z

    zero_coding

    10/27/2022, 11:39 AM
    https://stackoverflow.com/questions/74221460/trigger-gradlew-test-when-files-have-changed
  • z

    zero_coding

    10/27/2022, 11:39 AM
    would be very happy if someone can help
  • r

    Robert Jaros

    10/31/2022, 5:41 AM
    Anyone is using https://github.com/MarioAriasC/KotlinPrimavera? I've got some legacy projects using this library, but the artifacts were published to https://repo.spring.io/plugins-release/ and it's no longer available.
  • a

    André Martins

    11/08/2022, 11:40 AM
    Hey guys, is it possible to load configurations with different implementation based on a property? eg:
    myConfig:
      myList:
        - type: someType
          propertyA: someValue
          propertyA1: 32
        - type: otherType
          propertyB: otherValue
          propertyB1: abc
    data class MyConfig(val myList: List<Config>)
    
    interface Config {
        fun doStuff()
    }
    
    class SomeType(val propertyA: String, val propertyA1: Int): Config {
        override fun doStuff() {
            println("SomeType $propertyA")
         }
    }
    
    class OtherType(val propertyB: String, val propertyB1: String): Config {
        override fun doStuff() {
            println("OtherType $propertyB and $propertyB1")
         }
    }
    So this way I could do something like
    class MyService(val myConfig: MyConfig) {
        fun serviceFunction() {
           myConfig.myList.forEach(Config::doStuff)
        }
    }
  • a

    Abhishek Saxena

    11/15/2022, 5:58 AM
    Is it mandatory to have the variables in RequestDTO as nullable as jacken is throwing an exception if the value passed for the field is null. Is there a way to integrate bean validation or some alternative to have the fields non-nullable without the jackson throwing the exception?
    t
    • 2
    • 1
  • s

    Shumilin Alexandr

    11/15/2022, 11:47 AM
    Hi! i need help! how can i write SOAP client for reactive spring (webFlux), can you show me example for kotlin?
    m
    • 2
    • 3
  • b

    bob

    11/19/2022, 6:58 PM
    What is the best book/online education for learning Spring if you’re an experienced Kotlin developer? All suggestions welcome 🙂
    j
    b
    • 3
    • 2
  • s

    Shumilin Alexandr

    12/06/2022, 11:45 AM
    Hi please tell me! Why? my entity not updated in db
    if (checkEmailStatusVerification.first == description) { // it's ok
        verification.verificationState = description
        verificationRepository.run { save(verification) } // this code doesn't work
        throw EmailVerificationException("emailAlreadyVerified  ${verification.email}")
    }
    i am use
    //reactive postgre
    implementation("org.springframework.boot:spring-boot-starter-data-r2dbc")
    runtimeOnly("io.r2dbc:r2dbc-postgresql:0.8.13.RELEASE")
    runtimeOnly("org.postgresql:postgresql:42.5.1")
    t
    • 2
    • 13
  • g

    grox13

    12/13/2022, 5:59 PM
    Hi, Whenever adding
    spring-kafka-test
    as a dependency I cannot run tests. Tests start to fail for following reason:
    org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 1.
    	at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:64)
    	...
    Caused by: java.lang.NoClassDefFoundError: org/junit/platform/launcher/TestExecutionListener
    	at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    	...
    	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:97)
    	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    	at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:62)
    	... 18 more
    Caused by: java.lang.ClassNotFoundException: org.junit.platform.launcher.TestExecutionListener
    	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    	... 50 more
    This is what my gradle looks like:
    import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    import org.springframework.boot.gradle.tasks.bundling.BootJar
    
    plugins {
        id("org.springframework.boot") version "3.0.0"
        id("io.spring.dependency-management") version "1.1.0"
        kotlin("jvm") version "1.7.22"
        kotlin("plugin.spring") version "1.7.22"
        `maven-publish`
        `java-test-fixtures`
    }
    
    group = "com.example"
    version = "0.0.1-SNAPSHOT"
    java.sourceCompatibility = JavaVersion.VERSION_17
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        api("org.jetbrains.kotlin:kotlin-reflect")
        api("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    
        api("com.auth0:java-jwt:4.2.1")
        api("com.fasterxml.jackson.module:jackson-module-kotlin")
        api("io.github.microutils:kotlin-logging-jvm:3.0.4")
    
        api("org.springframework.boot:spring-boot-starter")
        api("org.springframework.boot:spring-boot-starter-actuator")
        api("org.springframework.boot:spring-boot-starter-data-mongodb")
        api("org.springframework.boot:spring-boot-starter-validation")
        api("org.springframework.boot:spring-boot-starter-security")
        api("org.springframework.boot:spring-boot-starter-web")
        api("org.springframework.kafka:spring-kafka")
    
        testFixturesApi("org.springframework.boot:spring-boot-starter-test")
        testFixturesApi("org.springframework.restdocs:spring-restdocs-mockmvc")
        testFixturesApi("org.springframework.security:spring-security-test")
        testFixturesApi("org.springframework.kafka:spring-kafka-test")
    }
    
    publishing {
        publications {
            create<MavenPublication>("maven") {
                groupId = project.group.toString()
                artifactId = project.name
                version = project.version.toString()
    
                from(components["java"])
            }
        }
    }
    
    tasks.getByName<BootJar>("bootJar") {
        enabled = false
    }
    
    tasks.getByName<Jar>("jar") {
        enabled = true
    }
    
    tasks.withType<KotlinCompile> {
        kotlinOptions {
            freeCompilerArgs = listOf("-Xjsr305=strict")
            jvmTarget = "17"
        }
    }
    
    tasks.withType<Test> {
        useJUnitPlatform()
    }
    Has anybody experienced similar issue?
    r
    • 2
    • 2
  • o

    orrc

    12/15/2022, 12:46 PM
    Is it at all possible (or wise) to use a
    typealias
    as the return type of a
    @Bean
    ? I just tried this, but it basically turns up as an unqualified
    java.lang.String
    , i.e. if there's another
    @Bean
    returning a
    String
    , they're in conflict:
    typealias SpringProfile = String
    
    @Configuration
    class SpringConfig {
      @Bean fun activeProfile(@Value("\${spring.profiles.active}") name: String): SpringProfile = name
    }
    s
    t
    • 3
    • 7
  • n

    nicholasnet

    12/20/2022, 12:35 PM
    Did any of you tried Spring Boot 3 with Webflux and Kotlin using native GraalVM native build? Is it working properly?
    s
    t
    • 3
    • 2
  • n

    Nikky

    01/04/2023, 11:44 AM
    hi, we upgraded to spring boot 3 and one of the things i cannot figure out .. is that some responses of our server changed from
    application/json
    to
    application/cbor
    (we have SOME responses that are explicitely cbor, but we don’t want all of the API to be) anyone knows how to tweak that.. or how to configure content negotiation or the like ? all tutorials i find for that are horribly outdated…
    d
    • 2
    • 3
  • g

    George

    01/05/2023, 2:07 PM
    Hi, i have encountered a weird problem. I have a simple entity and im saving this entity in db with r2dbc using
    R2dbcEntityTemplate
    directly :
    class MessageRepositoryImpl(private val template: R2dbcEntityTemplate) : MessageRepository {
        override suspend fun save(messageEntity: MessageEntity): MessageEntity =
            template.insert<MessageEntity>().usingAndAwait(messageEntity)
    }
    So far so good. now i want to refactor my entity's id to be a data class. for example: before:
    @Table("messages")
    data class MessageEntity(
        @Id
        @Column("id")
        val id: Int = 0,
    }
    after:
    data class MessageId(private val value: Int) {
        fun toInt() = value
        override fun toString(): String = value.toString()
    }
    
    @InternalHubCoreApi
    @Table("messages")
    data class MessageEntity(
        @Id
        @Column("id")
        val id: MessageId = MessageId(0)
    }
    Now whenever i save something with above
    save()
    function it does not return the write result like before (i.e. the id which is on purpose 0 does not get returned with the actual value). But the entity is saved properly in db with proper (auto-increased) id, meaning if i search for it the result is correct. Has anyone encountered any similar problem? Thanks in advance for any help !!
    • 1
    • 2
  • a

    asavio

    01/08/2023, 7:35 AM
    Has anyone tried playing with Loom in Kotlin and Spring Boot? I’m following this blog post by Spring. But when I print the threads to the console, they aren’t virtual threads!
    Is Virtual Thread: false | Thread[#38,http-nio-8080-exec-3,5,main]
    Is Virtual Thread: false | Thread[#37,http-nio-8080-exec-2,5,main]
    Is Virtual Thread: false | Thread[#41,http-nio-8080-exec-6,5,main]
    Is Virtual Thread: false | Thread[#36,http-nio-8080-exec-1,5,main]
    Is Virtual Thread: false | Thread[#39,http-nio-8080-exec-4,5,main]
    The full code is here: https://github.com/aseemsavio/loomgraphql Here’s the code:
    package com.asavio.loomgraphql
    
    import org.apache.coyote.ProtocolHandler
    import org.springframework.boot.autoconfigure.SpringBootApplication
    import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration
    import org.springframework.boot.runApplication
    import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer
    import org.springframework.context.annotation.Bean
    import org.springframework.core.task.AsyncTaskExecutor
    import org.springframework.core.task.support.TaskExecutorAdapter
    import org.springframework.graphql.data.method.annotation.QueryMapping
    import org.springframework.stereotype.Controller
    import java.util.concurrent.Executors
    
    
    @SpringBootApplication
    class LoomgraphqlApplication
    
    fun main(args: Array<String>) {
        runApplication<LoomgraphqlApplication>(*args)
    }
    
    @Bean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)
    fun asyncTaskExecutor(): AsyncTaskExecutor? {
        return TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor())
    }
    
    @Bean
    fun protocolHandlerVirtualThreadExecutorCustomizer(): TomcatProtocolHandlerCustomizer<*>? {
        return TomcatProtocolHandlerCustomizer { protocolHandler: ProtocolHandler ->
            protocolHandler.executor = Executors.newVirtualThreadPerTaskExecutor()
        }
    }
    
    @Controller
    class PeopleController {
    
        @QueryMapping
        fun people(): List<Person> {
            println("Is Virtual Thread: ${Thread.currentThread().isVirtual} | ${Thread.currentThread()}")
            return listOf(
                Person("jdgahjdagdahjdg", "Jon", 25),
                Person("ddgahjdagdahjdg", "Snow", 26),
                Person("gdgahjdagdahjdg", "Arya", 23),
                Person("qdgahjdagdahjdg", "Stark", 21),
            )
        }
    
    }
    
    data class Person(val id: String, val name: String, val age: Int)
    This is my build.gradle.kts file.
    import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    
    plugins {
        id("org.springframework.boot") version "3.0.1"
        id("io.spring.dependency-management") version "1.1.0"
        id("org.graalvm.buildtools.native") version "0.9.18"
        kotlin("jvm") version "1.8.0"
        kotlin("plugin.spring") version "1.8.0"
    }
    
    group = "com.asavio"
    version = "0.0.1-SNAPSHOT"
    java.sourceCompatibility = JavaVersion.VERSION_19
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation("org.springframework.boot:spring-boot-starter-web")
        implementation("org.springframework.boot:spring-boot-starter-graphql")
        implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
        implementation("org.jetbrains.kotlin:kotlin-reflect")
        implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
        testImplementation("org.springframework.boot:spring-boot-starter-test")
        testImplementation("org.springframework:spring-webflux")
        testImplementation("org.springframework.graphql:spring-graphql-test")
    }
    
    val preview = "--enable-preview"
    
    tasks.withType<org.springframework.boot.gradle.tasks.run.BootRun> {
        jvmArgs = mutableListOf(preview)
    }
    
    tasks.withType<JavaExec> {
        jvmArgs = mutableListOf(preview)
    }
    
    tasks.withType<JavaCompile> {
        options.encoding = "UTF-8"
        options.compilerArgs.add(preview)
        options.compilerArgs.add("-Xlint:preview")
    }
    
    tasks.withType<KotlinCompile> {
        kotlinOptions {
            freeCompilerArgs = listOf("-Xjsr305=strict")
            jvmTarget = "19"
        }
    }
    
    tasks.withType<Test> {
        useJUnitPlatform()
    }
    r
    a
    • 3
    • 3
  • l

    Leonardo Borges

    01/09/2023, 12:20 PM
    Hello! I'm having some issues when trying to add custom headers to a
    HttpServletResponse
    within a suspend function. The approach we are using now is not good, so we would like to find a proper solution:
    @GetMapping("/users")
    suspend fun getUsers(//...parameters, response: HttpServletResponse): List<UsersResource> {
        val users = userService.searchBy(//parameters)
        response.addPaginationHeaders(users.size)
        return users
    }
    For instance,
    addPaginationHeaders
    will be changed only for example purposes, as below:
    internal fun HttpServletResponse.addPaginationHeaders(size: Int) {
        val uri = ServletUriComponentBuilder.fromCurrentRequest().toUriString()
        setHeaders("X-Count", size)
        //...other params
    }
    So, suspend function doesn't work (throws
    java.lang.IllegalStateException: No current ServletRequestAttributes
    ). Instead, we have to place the function body within a
    runBlocking
    to make it work.
    suspend fun getUsers(\\...parameters, response: HttpServletResponse) = runBlocking {
        //same code as above
    }
    Has anyone experienced this issue? Is there any solution besides
    runBlocking
    ?
    s
    e
    • 3
    • 8
  • m

    MArtin

    01/09/2023, 6:42 PM
    Failed to initialize JPA EntityManagerFactory: Could not determine recommended JdbcType for `ar.com.school.management.models.entity.Subject` Hello everyone, I'm new with Kotlin and I'm trying to use it to make an app with Spring boot.I have just done the entities and anything else yet because I want to know if the app runs but I tried running it and it gives me the following exception "Failed to initialize JPA EntityManagerFactory: Could not determine recommended JdbcType for ar.com.school.management.models.entity.Subject"
    package ar.com.school.management.models.entity
    
    import com.fasterxml.jackson.annotation.JsonIgnoreProperties
    import jakarta.persistence.*
    @Entity
    data class Career(@Id
                  @GeneratedValue(strategy = 
                  GenerationType.IDENTITY)
                  @Column(name = "career_id")
                  var id: Long?,
    
                  var name: String?,
    
                  @ManyToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
                  @JoinTable(name = "career_subject",
                      joinColumns = [JoinColumn(name = "career_id", referencedColumnName = "career_id")],
                      inverseJoinColumns = [JoinColumn(name = "subject_id", referencedColumnName = "subject_id")])
                  @JsonIgnoreProperties("subjectCareers")
                  var subjects: List<Subject>? = mutableListOf(),
    
                  @OneToMany(mappedBy = "career")
                  var students: List<Student>? = mutableListOf(),
    
                  @ManyToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY)
                  @JoinTable(name = "career_teacher",
                      joinColumns = [JoinColumn(name = "career_id", referencedColumnName = "career_id")],
                      inverseJoinColumns = [JoinColumn(name = "teacher_id", referencedColumnName = "teacher_id")])
                  @JsonIgnoreProperties("careers")
                  var teachers: List<Teacher>? = mutableListOf()) {
    constructor(): this(null,null,null, null, null)
    }
  • a

    Alexandre A Barbosa

    01/09/2023, 11:43 PM
    hey channel. I’ve been trying to implement a POST with a ByteArray using this:
    <http://requestBuilder.POST|requestBuilder.POST>(HttpRequest.BodyPublishers.ofByteArray(payload.httpBody.toByteArray()))
    but in the controller I get: Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type ‘application/octet-stream;charset=UTF-8’ not supported] My Controller:
    @RestController
    @CrossOrigin
    @RequestMapping(path = "/")
    public class IngestionMockerController {
    @PostMapping(value = "/")
    public ResponseEntity<String> post(
    @RequestBody Byte[] body) {
    System.out.println("HttpRequestIngestionRequest = " + Arrays.stream(body).toArray());
    return new ResponseEntity<>(HttpStatus.CREATED);
    }
    }
    Please, could someone share an example of HTTP Client posting a ByteArray to a POST endpoint (@RequestBody Byte[] body)?
    a
    • 2
    • 4
  • a

    Alexandre A Barbosa

    01/11/2023, 1:15 PM
    hey Channel. I am accustomed to inject beans using Springboot doing, for example:
    @Autowired
    private AccountMapper mapper;
    I want to avoid of instantiate a HttpClient builder every time in my
    @Component
    class. Instead of do
    val client = HttpClient.newBuilder().build()
    every time, please let me know how to inject it using Kotlin.
    s
    d
    • 3
    • 18
  • s

    Shumilin Alexandr

    01/11/2023, 2:48 PM
    Hey Channel! I need help! Test by kotlin and Spring Web Flux, service by react Code of AbstractClass with some initialization
    @ActiveProfiles("test")
    @ExtendWith(SpringExtension::class)
    @SpringBootTest(classes = [ApiApplication::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    @AutoConfigureWireMock(port = 0)
    @ContextConfiguration(initializers = [DBInitializer::class, KeyCloakInitializer::class])
    abstract class BaseIntegrationTest {
    
        @Autowired
        lateinit var webClient: WebTestClient
    
        @Autowired
        lateinit var applicationContext: ApplicationContext
    
        @BeforeEach
        fun setUp() {
            webClient = WebTestClient.bindToApplicationContext(applicationContext)
                .apply(springSecurity())
                .configureClient()
                .build()
        }
    
        fun getTestJwt() = Jwt(
            "token",
            Instant.now(),
            Instant.now().plusSeconds(100),
            mapOf("testHeader" to "testHeader"),
            mapOf("clientId" to "TestExternalSystemCode")
        )
    
    }
    Code of TestMethod
    val request = EmailVerificationStateRequestDto(cus = cusAX, email = testEmail)
    
            val response = webClient
                .mutateWith(
                    mockJwt()
                        .jwt(getTestJwt())
                        .authorities(SimpleGrantedAuthority("emailVerificationState"))
                )
                .post()
                .uri("/emailVerificationState")
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(request), EmailVerificationStateRequestDto::class.java)
                .exchange()
                .expectStatus().is2xxSuccessful
                .returnResult(EmailVerificationStateResponseDto::class.java)
    and i got error log: https://kotlinlang.slack.com/files/T09229ZC6/F04K4PBAR24 please tell my why?
    s
    • 2
    • 8
  • s

    Sam

    01/12/2023, 8:35 AM
    Try using a
    lateinit
    property:
    @MockkBean lateinit var httpClient: HttpClient
    d
    a
    +2
    • 5
    • 13
  • y

    Yogeshvu

    01/13/2023, 5:24 PM
    Anyone have a working example of spring with picocli library? Seems like there is some issues on this: https://github.com/spring-io/start.spring.io/issues/1076
  • a

    Alexandre A Barbosa

    01/13/2023, 6:21 PM
    hey channel. I need to iterate a map and create a new map but with a transformation in the key. I will replace a value in the key based on the original key. I am trying to do in this way but the compile complains of
    fun pathMapped(): Map<String, String> = paths.entries.iterator()
        .forEach { entry -> return mapOf(entry.key.replace("__","/"), entry.value)}
    could someone else here help to do implement this in a correct way?
    k
    • 2
    • 2
Powered by Linen
Title
a

Alexandre A Barbosa

01/13/2023, 6:21 PM
hey channel. I need to iterate a map and create a new map but with a transformation in the key. I will replace a value in the key based on the original key. I am trying to do in this way but the compile complains of
fun pathMapped(): Map<String, String> = paths.entries.iterator()
    .forEach { entry -> return mapOf(entry.key.replace("__","/"), entry.value)}
could someone else here help to do implement this in a correct way?
k

Klitos Kyriacou

01/13/2023, 6:30 PM
fun pathMapped(): Map<String, String> = paths.mapKeys { (k, v) -> k.repace("__","/") }
a

Alexandre A Barbosa

01/13/2023, 7:00 PM
thank you very much @Klitos Kyriacou
View count: 31