Ivan Feliciano
09/29/2022, 11:10 PMapplication.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)
}
}
Yogeshvu
10/07/2022, 4:10 PMval 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()
dany giguere
10/09/2022, 4:04 PMhttps://www.youtube.com/watch?v=Ug7rADxR1oE▾
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()
...
dany giguere
10/09/2022, 4:11 PMsuspend fun getAllCustomer() : Flux<Customer> = customerRepository.findAll()
then I get this response:
{
"scanAvailable": true,
"prefetch": -1
}
jmfayard
10/10/2022, 6:36 PMRobert Jaros
10/22/2022, 12:27 PMbootJar
). 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?João Gabriel Zó
10/26/2022, 12:09 PM@JsonNaming
every data class?daphillips
10/26/2022, 8:40 PM@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 oldzero_coding
10/27/2022, 11:39 AMzero_coding
10/27/2022, 11:39 AMRobert Jaros
10/31/2022, 5:41 AMAndré Martins
11/08/2022, 11:40 AMmyConfig:
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)
}
}
Abhishek Saxena
11/15/2022, 5:58 AMShumilin Alexandr
11/15/2022, 11:47 AMbob
11/19/2022, 6:58 PMShumilin Alexandr
12/06/2022, 11:45 AMif (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")
grox13
12/13/2022, 5:59 PMspring-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?orrc
12/15/2022, 12:46 PMtypealias
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
}
nicholasnet
12/20/2022, 12:35 PMNikky
01/04/2023, 11:44 AMapplication/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…George
01/05/2023, 2:07 PMR2dbcEntityTemplate
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 !!asavio
01/08/2023, 7:35 AMIs 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()
}
Leonardo Borges
01/09/2023, 12:20 PMHttpServletResponse
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
?MArtin
01/09/2023, 6:42 PMpackage 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)
}
Alexandre A Barbosa
01/09/2023, 11:43 PM<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)?Alexandre A Barbosa
01/11/2023, 1:15 PM@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.Shumilin Alexandr
01/11/2023, 2:48 PM@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?Sam
01/12/2023, 8:35 AMlateinit
property:
@MockkBean lateinit var httpClient: HttpClient
Yogeshvu
01/13/2023, 5:24 PMAlexandre A Barbosa
01/13/2023, 6:21 PMfun 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?Alexandre A Barbosa
01/13/2023, 6:21 PMfun 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?Klitos Kyriacou
01/13/2023, 6:30 PMfun pathMapped(): Map<String, String> = paths.mapKeys { (k, v) -> k.repace("__","/") }
Alexandre A Barbosa
01/13/2023, 7:00 PM